madzak / python-json-logger

Json Formatter for the standard python logger
BSD 2-Clause "Simplified" License
1.7k stars 231 forks source link

Renaming "exc_info" breaks logging.log() with KeyError: 'exc_info' #189

Open simonasbuj opened 3 months ago

simonasbuj commented 3 months ago

Hi, I'm renaming 'exc_info' to 'stack_trace' like this:

formatter = jsonlogger.JsonFormatter(
        fmt = "%(asctime)s | %(levelname)s | %(name)s | %(message)s",
        rename_fields={"asctime": "@timestamp", "levelname": "level", "exc_info": "stack_trace"},
        datefmt = "%Y-%m-%d %H:%M:%S"
    )

But after this logging.info("my message") starts throwing this error:

--- Logging error ---
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/logging/__init__.py", line 1110, in emit
    msg = self.format(record)
          ^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/logging/__init__.py", line 953, in format
    return fmt.format(record)
           ^^^^^^^^^^^^^^^^^^
  File "/Users/user/Library/Caches/pypoetry/virtualenvs/logging-sandbox-cF-GGjXI-py3.11/lib/python3.11/site-packages/pythonjsonlogger/jsonlogger.py", line 243, in format
    self.add_fields(log_record, record, message_dict)
  File "/Users/user/Library/Caches/pypoetry/virtualenvs/logging-sandbox-cF-GGjXI-py3.11/lib/python3.11/site-packages/pythonjsonlogger/jsonlogger.py", line 191, in add_fields
    self._perform_rename_log_fields(log_record)
  File "/Users/user/Library/Caches/pypoetry/virtualenvs/logging-sandbox-cF-GGjXI-py3.11/lib/python3.11/site-packages/pythonjsonlogger/jsonlogger.py", line 195, in _perform_rename_log_fields
    log_record[new_field_name] = log_record[old_field_name]
                                 ~~~~~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'exc_info'

I'm using python-json-logger==2.0.7. Seems strange, because it was added in this pull request and it seems to be merged and working? https://github.com/madzak/python-json-logger/pull/160

simonasbuj commented 3 months ago

there's a workaround https://github.com/madzak/python-json-logger/issues/171 But as it says then all logs have exc_info field, but its null. Well at least it works.