user13666714
user13666714

Reputation:

Logging to a file in Python

I am trying to create a Python program that will just log user input.

Here is the code:

import logging

# logging setup
logger = logging.getLogger("testapp")
hdlr = logging.FileHandler("test.log")
formatter = logging.Formatter("%(asctime)s %(message)s")
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)

def main():
    userinput = input("> ")
    logger.debug(userinput)
    logger.info(userinput)
    logger.warning(userinput)
    logger.error(userinput)
    logger.critical(userinput)
    a = input("> ")  # wait for a newline before before closing

main()

When I run the code, the warning, error, and critical message get printed, like they should, but a file is not created and nothing is actually logged.

Edit: This error message shows up:

--- Logging error ---
Traceback (most recent call last):
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 1025, in emit
    msg = self.format(record)
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 869, in format
    return fmt.format(record)
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 611, in format
    s = self.formatMessage(record)
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 580, in formatMessage
    return self._style.format(record)
  File "C:\Users\matth\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 422, in format
    return self._fmt % record.__dict__
KeyError: 'level'
Call stack:
  File "C:/Users/matth/PycharmProjects/arb/main.py", line 32, in <module>
    logger.debug("Starting...")
Message: 'Starting...'
Arguments: ()

Upvotes: 0

Views: 162

Answers (1)

Dmitry
Dmitry

Reputation: 334

You need to add:

import logging

logging.basicConfig(filename='example.log',level=logging.DEBUG)

The file 'example.log' will be created.

Upvotes: 0

Related Questions