Skip to content

Commit c426bf5

Browse files
fix: exception log message format (#394)
1 parent e18dd89 commit c426bf5

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

google/cloud/logging_v2/handlers/structured_log.py

+5
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,14 @@ def format(self, record):
6262
# let other formatters alter the message
6363
super_payload = None
6464
if record.msg:
65+
# format the message using default handler behaviors
6566
super_payload = super(StructuredLogHandler, self).format(record)
6667
# properly break any formatting in string to make it json safe
6768
record._formatted_msg = json.dumps(super_payload or "")
69+
# remove exception info to avoid duplicating it
70+
# https://github.com/googleapis/python-logging/issues/382
71+
record.exc_info = None
72+
record.exc_text = None
6873
# convert to GCP structred logging format
6974
gcp_payload = self._gcp_formatter.format(record)
7075
return gcp_payload

tests/unit/handlers/test_structured_log.py

+18
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,24 @@ def test_format_with_quotes(self):
119119
result = handler.format(record)
120120
self.assertIn(expected_result, result)
121121

122+
def test_format_with_exception(self):
123+
"""
124+
When logging a message with an exception, the stack trace should not be appended
125+
"""
126+
import logging
127+
import json
128+
129+
handler = self._make_one()
130+
exception_tuple = (Exception, Exception(), None)
131+
message = "test"
132+
record = logging.LogRecord(
133+
None, logging.INFO, None, None, message, None, exception_tuple
134+
)
135+
record.created = None
136+
handler.filter(record)
137+
result = json.loads(handler.format(record))
138+
self.assertEqual(result["message"], f"{message}\nException")
139+
122140
def test_format_with_line_break(self):
123141
"""
124142
When logging a message containing \n, it should be properly escaped

0 commit comments

Comments
 (0)