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 @@ -15,6 +15,7 @@
"""Logging handler for printing formatted structured logs to standard output.
"""
import json
from copy import copy
import logging.handlers

from google.cloud.logging_v2.handlers.handlers import CloudLoggingFilter
Expand Down Expand Up @@ -59,9 +60,13 @@ def format(self, record):
Returns:
str: A JSON string formatted for GKE fluentd.
"""
# remove unwanted fields
record = copy(record)
record.exc_info = None
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since the record object is used for logging, what is a reason to create a full copy of the record object? why not to reset the .exc_info on the argument directly?
Otherwise, consider to use a distinct variable for the copy instead of "reusing" record.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was doing some experimenting, but ended up modifying the record object directly

# 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 "")
Expand Down
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"], message)

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