Skip to content

Commit 1d07ea7

Browse files
committed
PB-931 Fix the exc_text field handling in JSON formatter
Adding the exc_text field to the record before formatting a message. This allows for formatting the message through the django logging facility Removing the addition of exc_text to the message directly. Instead adding it to the record, so that it can be formatted through the django logging facility
1 parent 460eccf commit 1d07ea7

File tree

2 files changed

+43
-7
lines changed

2 files changed

+43
-7
lines changed

logging_utilities/formatters/json_formatter.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -343,18 +343,16 @@ def format(self, record):
343343
if self.add_always_extra:
344344
extra = self._get_extra_attrs(record)
345345

346-
message = self.formatMessage(record)
347-
348-
if self.add_always_extra:
349-
self._add_extra_to_message(extra, message)
350-
351346
if record.exc_info:
352347
# Cache the traceback text to avoid converting it multiple times
353348
# (it's constant anyway)
354349
if not record.exc_text:
355350
record.exc_text = self.formatException(record.exc_info)
356-
if record.exc_text:
357-
message['exc_text'] = record.exc_text
351+
352+
message = self.formatMessage(record)
353+
354+
if self.add_always_extra:
355+
self._add_extra_to_message(extra, message)
358356

359357
if record.stack_info:
360358
message['stack_info'] = self.formatStack(record.stack_info)

tests/test_json_formatter.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -787,3 +787,41 @@ def test_missing_attribute(self):
787787
("message", "Composed message without extra"),
788788
])
789789
)
790+
791+
def test_exc_info_without_configuration(self):
792+
"""
793+
Test that the exc_text doesn't appear if it's not configured
794+
in the logger, even though the logging call records it
795+
"""
796+
with self.assertLogs('test_formatter', level=logging.DEBUG) as ctx:
797+
logger = logging.getLogger('test_formatter')
798+
self._configure_logger(
799+
logger,
800+
fmt=dictionary([
801+
('level', 'levelname'),
802+
('request', ['request.path', 'request.method']),
803+
('message', 'message'),
804+
]),
805+
remove_empty=True,
806+
ignore_missing=True
807+
)
808+
809+
try:
810+
raise Exception("Error occurred")
811+
except Exception as e:
812+
logger.critical(
813+
str(e),
814+
exc_info=sys.exc_info(),
815+
extra={'request': {
816+
'path': '/my/path', 'method': 'GET', 'scheme': 'https'
817+
}}
818+
)
819+
820+
self.assertDictEqual(
821+
json.loads(ctx.output[0], object_pairs_hook=dictionary),
822+
dictionary([
823+
("level", "CRITICAL"),
824+
("request", ["/my/path", "GET"]),
825+
("message", "Error occurred"), # no exc_text because it wasn't configured
826+
])
827+
)

0 commit comments

Comments
 (0)