pythonpython-3.xloggingfilehandler

Python logging: Logging error - KeyError: 'level'


Getting KeyError while trying to use the standard python logging module

I am trying to log to both my console and to a file from python using the standard logging module in python

I am using this code (Original source of code) but cannot understand what the error is.


import time
import logging
import logging.handlers


logger = logging.getLogger("MyLog")

logger.setLevel(level=logging.DEBUG)

# Stream
formatter = logging.Formatter("%(level)s %(asctime)s: %(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setLevel(level=logging.INFO)
stream_handler.setFormatter(formatter)

# File
formatter_file = logging.Formatter("[%(levelname)s|%(module)s|L%(lineno)d] %(asctime)s: %(message)s")
timestr = time.strftime("%Y%m%d-%H%M%S")
logFilePath = f"logs/Logs_{timestr}.log"
file_handler = logging.handlers.TimedRotatingFileHandler(filename=logFilePath)
file_handler.setLevel(level=logging.DEBUG)
file_handler.setFormatter(formatter_file)


logger.addHandler(file_handler)
logger.addHandler(stream_handler)

logger.debug("This is a debug message")
logger.info("This is a info message")
logger.warning("This is a warning message")
logger.error("This is a error message")

This is the error that I am getting:

--- Logging error ---
Traceback (most recent call last):
  File "C:\Python36\lib\logging\__init__.py", line 993, in emit
    msg = self.format(record)
  File "C:\Python36\lib\logging\__init__.py", line 839, in format
    return fmt.format(record)
  File "C:\Python36\lib\logging\__init__.py", line 579, in format
    s = self.formatMessage(record)
  File "C:\Python36\lib\logging\__init__.py", line 548, in formatMessage     
    return self._style.format(record)
  File "C:\Python36\lib\logging\__init__.py", line 391, in format
    return self._fmt % record.__dict__
KeyError: 'level'
Call stack:
  File "c:/<user>/WORK/folder/src/test5.py", line 30, in <module>
    logger.info("This is a info message")
Message: 'This is a info message'
Arguments: ()
--- Logging error ---
Traceback (most recent call last):
  File "C:\Python36\lib\logging\__init__.py", line 993, in emit
    msg = self.format(record)
  File "C:\Python36\lib\logging\__init__.py", line 839, in format
    return fmt.format(record)
  File "C:\Python36\lib\logging\__init__.py", line 579, in format
    s = self.formatMessage(record)
  File "C:\Python36\lib\logging\__init__.py", line 548, in formatMessage     
    return self._style.format(record)
  File "C:\Python36\lib\logging\__init__.py", line 391, in format
    return self._fmt % record.__dict__
KeyError: 'level'
Call stack:
  File "c:/<user>/WORK/folder/src/test5.py", line 31, in <module>
    logger.warning("This is a warning message")
Message: 'This is a warning message'
Arguments: ()
--- Logging error ---
Traceback (most recent call last):
  File "C:\Python36\lib\logging\__init__.py", line 993, in emit
    msg = self.format(record)
  File "C:\Python36\lib\logging\__init__.py", line 839, in format
    return fmt.format(record)
  File "C:\Python36\lib\logging\__init__.py", line 579, in format
    s = self.formatMessage(record)
  File "C:\Python36\lib\logging\__init__.py", line 548, in formatMessage
    return self._style.format(record)
  File "C:\Python36\lib\logging\__init__.py", line 391, in format
    return self._fmt % record.__dict__
KeyError: 'level'
Call stack:
  File "c:/<user>/WORK/folder/src/test5.py", line 32, in <module>
    logger.error("This is a error message")
Message: 'This is a error message'
Arguments: ()

Solution

  • "%(level)s %(asctime)s: %(message)s"
    

    should be

    "%(levelname)s %(asctime)s: %(message)s"
    

    ā€“ there is no level key in the log record, as the (slightly obscure) error message is trying to say.

    Newer versions of Python (3.6 is pretty old!) have a better error message:

    File "python3.12/logging/__init__.py", line 466, in format
        raise ValueError('Formatting field not found in record: %s' % e)
    ValueError: Formatting field not found in record: 'level'