loading...

Logging with Python

petercour profile image petercour ・2 min read

Blinking lights don't really help for solving problems. What does each light mean? In case of error, you can not find the bug that way.

Logging helps to debug your program if something goes wrong. More data means you can analyze better.

Log with Python

Python comes with the logging module. You can write a log message like this:

logger.info("Hello World printed")

The simple program below logs to a file. The log file can then be used for analysis.

#!/usr/bin/python3
import logging

logging.basicConfig(level=logging.INFO, 
                    filename='my_app.log', # log to this file
                    format='%(asctime)s [INFO] %(message)s') # include timestamp

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def main():
    logger.info("Program started")
    print("Hello World")
    logger.info("Hello World printed")
    logger.info("Program finished")

main()

formatting

By default the logger module does not include the time. Time helps to find your bugs as you can see when things happened.

The log file then contains something like this:

2019-07-05 14:44:02,052 [INFO] Program started
2019-07-05 14:44:02,053 [INFO] Hello World printed
2019-07-05 14:44:02,053 [INFO] Program finished

One of the first lines formats the log messages, in case you want to change that:

#!/usr/bin/python3
logging.basicConfig(level=logging.INFO, 
                    filename='my_app.log', # log to this file
                    format='%(asctime)s [INFO] %(message)s') 

Learn Python:

Posted on by:

Discussion

markdown guide