Skip to content

Commit 3f33a51

Browse files
authored
Add safe_str method to NewRelicContextFormatter (#219)
* Tweak log formatter to use a safe str function. * Add non-printable object test to logs in context.
1 parent c3a8376 commit 3f33a51

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

newrelic/api/log.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,4 +65,11 @@ def log_record_to_dict(cls, record):
6565
return output
6666

6767
def format(self, record):
68-
return json.dumps(self.log_record_to_dict(record), default=str, separators=(',', ':'))
68+
def safe_str(object, *args, **kwargs):
69+
"""Convert object to str, catching any errors raised."""
70+
try:
71+
return str(object, *args, **kwargs)
72+
except:
73+
return "<unprintable %s object>" % type(object).__name__
74+
75+
return json.dumps(self.log_record_to_dict(record), default=safe_str, separators=(',', ':'))

tests/agent_features/test_logs_in_context.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,14 @@ def log_buffer(caplog):
4646
_logger.removeHandler(_handler)
4747

4848

49+
class NonPrintableObject(object):
50+
def __str__(self):
51+
raise RuntimeError("Unable to print object.")
52+
53+
def __repr__(self):
54+
raise RuntimeError("Unable to print object.")
55+
56+
4957
def test_newrelic_logger_no_error(log_buffer):
5058
extra = {
5159
"string": "foo",
@@ -55,6 +63,7 @@ def test_newrelic_logger_no_error(log_buffer):
5563
"array": [1, 2, 3],
5664
"bool": True,
5765
"non_serializable": {"set"},
66+
"non_printable": NonPrintableObject(),
5867
"object": {
5968
"first": "bar",
6069
"second": "baz",
@@ -91,6 +100,7 @@ def test_newrelic_logger_no_error(log_buffer):
91100
u"extra.array": [1, 2, 3],
92101
u"extra.bool": True,
93102
u"extra.non_serializable": u"set(['set'])" if six.PY2 else u"{'set'}",
103+
u"extra.non_printable": u"<unprintable NonPrintableObject object>",
94104
u"extra.object": {
95105
u"first": u"bar",
96106
u"second": u"baz",

0 commit comments

Comments
 (0)