Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: exception log message format #394

Merged
merged 13 commits into from Sep 14, 2021
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