Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions google/cloud/logging_v2/handlers/structured_log.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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