Skip to content

Commit e9778e3

Browse files
committed
Merge pull request #2 from fruechel/master
Accept new values from mutate_json_record
2 parents c2a323d + 6f55363 commit e9778e3

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

README.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ ISO8601 date mutation.
110110
json_lib = ujson
111111
112112
def mutate_json_record(self, json_record):
113-
pass
113+
return json_record
114114
115115
Tests
116116
-----

json_log_formatter/__init__.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,13 @@ def format(self, record):
6161
message = record.getMessage()
6262
extra = self.extra_from_record(record)
6363
json_record = self.json_record(message, extra, record)
64-
self.mutate_json_record(json_record)
65-
return self.json_lib.dumps(json_record)
64+
mutated_record = self.mutate_json_record(json_record)
65+
# Backwards compatibility: Functions that overwrite this but don't
66+
# return a new value will return None because they modified the
67+
# argument passed in.
68+
if mutated_record is None:
69+
mutated_record = json_record
70+
return self.json_lib.dumps(mutated_record)
6671

6772
def extra_from_record(self, record):
6873
"""Returns `extra` dict you passed to logger.
@@ -104,3 +109,4 @@ def mutate_json_record(self, json_record):
104109
attr = json_record[attr_name]
105110
if isinstance(attr, datetime):
106111
json_record[attr_name] = attr.isoformat()
112+
return json_record

tests.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,27 @@ def test_message_and_time_and_extra_are_in_json_record_when_extra_is_provided(se
6565
self.assertEqual(set(json_record), expected_fields)
6666

6767

68+
class MutatingFormatter(JSONFormatter):
69+
70+
def mutate_json_record(self, json_record):
71+
new_record = {}
72+
for k, v in json_record.items():
73+
if isinstance(v, datetime):
74+
v = v.isoformat()
75+
new_record[k] = v
76+
return new_record
77+
78+
79+
class MutatingFormatterTest(TestCase):
80+
def setUp(self):
81+
json_handler.setFormatter(MutatingFormatter())
82+
83+
def test_new_record_accepted(self):
84+
logger.info('Sign up', extra={'fizz': DATETIME})
85+
json_record = json.loads(log_buffer.getvalue())
86+
self.assertEqual(json_record['fizz'], DATETIME_ISO)
87+
88+
6889
class JsonLibTest(TestCase):
6990
def setUp(self):
7091
json_handler.setFormatter(JSONFormatter())

0 commit comments

Comments
 (0)