Skip to content

Commit

Permalink
Fix message formatting while handling exceptions
Browse files Browse the repository at this point in the history
Consider the following format:

```
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'logzioFormat': {
            'format': '{"additional_field": "value"}',
            'validate': False
        }
    },
    'handlers': {
        'logzio': {
            'class': 'logzio.handler.LogzioHandler',
            'level': 'INFO',
            'formatter': 'logzioFormat',
            'token': '<<LOGZIO-TOKEN>>',
            'logzio_type': 'python-handler',
            'logs_drain_timeout': 5,
            'url': 'https://<<LOGZIO-URL>>:8071',
            'retries_no': 4,
            'retry_timeout': 2,
        }
    },
    'loggers': {
        '': {
            'level': 'DEBUG',
            'handlers': ['logzio'],
            'propagate': True
        }
    }
}
```

And the case, where the user logs an exception:

```
logger.exception("Something")
```

Python appends the exception traceback to the formatted message
(`{"additional_field": "value"}` originally). Which would result in the
logzio handler not being able to parse it as JSON, and thus not adding
the additional fields to the log.
  • Loading branch information
bence-the-great committed Dec 16, 2022
1 parent 7e9a48f commit 90287ab
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
2 changes: 2 additions & 0 deletions logzio/handler.py
Expand Up @@ -79,6 +79,8 @@ def flush(self):
def format(self, record):
message = super(LogzioHandler, self).format(record)
try:
if record.exc_info:
message = message.split("\nTraceback")[0] # only keep the original formatted message part
return json.loads(message)
except (TypeError, ValueError):
return message
Expand Down
11 changes: 8 additions & 3 deletions tests/test_logzioHandler.py
Expand Up @@ -137,7 +137,10 @@ def test_format_string_message(self):
}
)

def test_exc(self):
def test_exception(self):
formatter = logging.Formatter('{"tags": ["staging", "experimental"], "appname": "my-service"}', validate=False)
self.handler.setFormatter(formatter)

try:
raise ValueError("oops.")
except:
Expand All @@ -163,13 +166,15 @@ def test_exc(self):
self.assertDictEqual(
{
'@timestamp': None,
'appname': 'my-service',
'line_number': 10,
'log_level': 'NOTSET',
'logger': 'my-logger',
'message': 'exception test:',
'exception': 'Traceback (most recent call last):\n\n File "", in test_exc\n raise ValueError("oops.")\n\nValueError: oops.\n',
'exception': 'Traceback (most recent call last):\n\n File "", in test_exception\n raise ValueError("oops.")\n\nValueError: oops.\n',
'path_name': 'handler_test.py',
'type': 'python'
'type': 'python',
'tags': ['staging', 'experimental']
},
formatted_message
)

0 comments on commit 90287ab

Please sign in to comment.