Skip to content

Commit

Permalink
fix: exception log message format (#394)
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-sanche committed Sep 14, 2021
1 parent e18dd89 commit c426bf5
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
5 changes: 5 additions & 0 deletions google/cloud/logging_v2/handlers/structured_log.py
Expand Up @@ -62,9 +62,14 @@ def format(self, record):
# let other formatters alter the message
super_payload = None
if record.msg:
# format the message using default handler behaviors
super_payload = super(StructuredLogHandler, self).format(record)
# properly break any formatting in string to make it json safe
record._formatted_msg = json.dumps(super_payload or "")
# remove exception info to avoid duplicating it
# https://github.com/googleapis/python-logging/issues/382
record.exc_info = None
record.exc_text = None
# convert to GCP structred logging format
gcp_payload = self._gcp_formatter.format(record)
return gcp_payload
2 changes: 1 addition & 1 deletion tests/environment
18 changes: 18 additions & 0 deletions tests/unit/handlers/test_structured_log.py
Expand Up @@ -119,6 +119,24 @@ def test_format_with_quotes(self):
result = handler.format(record)
self.assertIn(expected_result, result)

def test_format_with_exception(self):
"""
When logging a message with an exception, the stack trace should not be appended
"""
import logging
import json

handler = self._make_one()
exception_tuple = (Exception, Exception(), None)
message = "test"
record = logging.LogRecord(
None, logging.INFO, None, None, message, None, exception_tuple
)
record.created = None
handler.filter(record)
result = json.loads(handler.format(record))
self.assertEqual(result["message"], f"{message}\nException")

def test_format_with_line_break(self):
"""
When logging a message containing \n, it should be properly escaped
Expand Down

0 comments on commit c426bf5

Please sign in to comment.