Tutorial

Python Logging Tutorial: How to Use the Logging Module Effectively

Learn how to use Python’s logging module to debug applications, log messages to files, format logs, and manage logging levels effectively.

Drake Nguyen

Founder · System Architect

3 min read

Introduction

The logging module is part of Python’s standard library and provides a flexible framework for tracking events that occur while an application is running. Logging helps developers understand application behavior, diagnose issues, and maintain historical records of important events.

Python logging supports both diagnostic logging (used for debugging and monitoring) and audit logging (used to track user actions and transactions). Logs are most commonly written to files, making them ideal for long-term analysis.

Prerequisites

To follow this guide, you should have Python 3 installed and a basic development environment set up on your local machine or server.

Why Use the logging Module?

Many developers rely on print() statements during debugging, but this approach becomes difficult to manage as applications grow.

The logging module provides a structured, scalable alternative with clear advantages:

  • Separates debugging output from normal program output
  • Allows log messages to be enabled or disabled by severity level
  • Supports logging to files, streams, or external systems
  • Preserves historical records for analysis and auditing

Using logging from the start results in cleaner code and easier maintenance over the lifetime of a project.

Printing Debug Messages to the Console

By default, Python logging only displays messages with a severity level of WARNING or higher. To display debug messages, the logging level must be adjusted.


import logging

logging.basicConfig(level=logging.DEBUG)
  

Once configured, you can replace print() statements with logging calls.


import logging

logging.basicConfig(level=logging.DEBUG)

class Pizza:
    def __init__(self, name, price):
        self.name = name
        self.price = price
        logging.debug(f"Pizza created: {self.name} (${self.price})")

    def make(self, quantity=1):
        logging.debug(f"Made {quantity} {self.name} pizza(s)")

    def eat(self, quantity=1):
        logging.debug(f"Ate {quantity} pizza(s)")
  

Running this code outputs structured debug messages, including the severity level and logger name.

Using Named Loggers

Python supports multiple loggers with different names, allowing you to separate logs by module or feature.


logger1 = logging.getLogger("orders")
logger2 = logging.getLogger("payments")

logger1.debug("Order module log")
logger2.debug("Payment module log")
  

Logging Messages to a File

One of the most powerful features of the logging module is the ability to persist logs to a file.


import logging

logging.basicConfig(
    filename="app.log",
    level=logging.DEBUG
)
  

Log messages will now be appended to app.log each time the program runs.

Adding Timestamps and Formatting

Log entries become more useful when they include timestamps and structured metadata.


logging.basicConfig(
    filename="app.log",
    level=logging.DEBUG,
    format="%(asctime)s:%(levelname)s:%(message)s"
)
  

This format includes the log time, severity level, and message content in a human-readable form.

Logging Levels Explained

Logging levels define the importance of each event. Python logging uses numeric values internally, increasing in severity.

Level Value Function Description
CRITICAL 50 logging.critical() Severe error, program may stop
ERROR 40 logging.error() Serious runtime error
WARNING 30 logging.warning() Unexpected behavior or potential issue
INFO 20 logging.info() General operational messages
DEBUG 10 logging.debug() Detailed diagnostic information

The default logging level is WARNING. Lower levels such as DEBUG must be explicitly enabled.

Conclusion

The Python logging module is a powerful and essential tool for building maintainable, debuggable applications.

By replacing print() statements with structured logs, writing logs to files, and using appropriate severity levels, you gain better insight into your application’s behavior over time.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.