diff --git a/google/cloud/logging_v2/handlers/structured_log.py b/google/cloud/logging_v2/handlers/structured_log.py index f0b4c69e..43e1250a 100644 --- a/google/cloud/logging_v2/handlers/structured_log.py +++ b/google/cloud/logging_v2/handlers/structured_log.py @@ -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 diff --git a/tests/environment b/tests/environment index f30dafa8..17b7a469 160000 --- a/tests/environment +++ b/tests/environment @@ -1 +1 @@ -Subproject commit f30dafa8b62bf197e39edd5aca57ce1cc62e9540 +Subproject commit 17b7a46908320891605908d5baa5f32eb255380e diff --git a/tests/unit/handlers/test_structured_log.py b/tests/unit/handlers/test_structured_log.py index 3d1c11ab..271a6818 100644 --- a/tests/unit/handlers/test_structured_log.py +++ b/tests/unit/handlers/test_structured_log.py @@ -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