0

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: ()

1 Answer 1

0

You need to add:

import logging

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

The file 'example.log' will be created.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.