DEV Community

petercour
petercour

Posted on

4

Logging with Python

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:

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs