← Back to Chapters

Python Logging

? Python Logging

? Quick Overview

Python’s logging module allows you to record events that happen while your program is running. These events (log messages) help you understand what your code is doing, diagnose issues, and monitor your application in development and production.

Unlike simple print() statements, logging supports different levels (info, warning, error, etc.), flexible output destinations (console, file, etc.), and customizable formats (timestamps, severity, message).

? Key Concepts

  • Logger: The main interface you use to log messages.
  • Log Level: Indicates the importance/severity of an event.
  • Handler: Decides where log messages go (console, file, etc.).
  • Formatter: Controls how the log message text looks (time, level, message).
  • Configuration: Using logging.basicConfig() or advanced configuration to set up logging behavior.

? Logging Levels

  • DEBUG – Detailed information for diagnosing problems.
  • INFO – General information about normal program execution.
  • WARNING – Something unexpected happened, but the program can still continue.
  • ERROR – A serious issue that prevented a function from performing a task.
  • CRITICAL – Very serious error; the program itself may not be able to continue running.

? Syntax & Theory

The simplest way to start logging is by using logging.basicConfig() and top-level functions:

  • logging.basicConfig(level=..., filename=..., format=...) – configures the logging system.
  • logging.debug(), logging.info(), logging.warning(), logging.error(), logging.critical() – log at different severity levels.

The level parameter decides the minimum level that will be shown. For example, if level=logging.INFO, then DEBUG messages are ignored, but all higher levels are shown.

The format string can include special placeholders like:

  • %(asctime)s – timestamp of the log record.
  • %(levelname)s – log level name (INFO, WARNING, etc.).
  • %(message)s – the actual log message you passed.

? Code Examples

⚡ Basic Logging

This example shows how to log messages with different severity levels to the console.

? View Basic Logging Example
import logging # Import the logging module

logging.basicConfig(level=logging.INFO) # Configure the logging system
logging.info("This is an info message") # Log an INFO-level message
logging.warning("This is a warning message") # Log a WARNING-level message
logging.error("This is an error message") # Log an ERROR-level message

? Logging to a File

You can send log messages to a file instead of (or in addition to) the console by providing a filename in basicConfig().

? View File Logging Example
import logging # Import the logging module

logging.basicConfig(filename="app.log", level=logging.INFO) # Log INFO and above to app.log
logging.info("This message is written to a file") # Write a log entry to the file

⚙️ Custom Logging Format

Adding timestamps and the log level to each message makes logs much easier to read and analyze.

? View Custom Format Example
import logging # Import the logging module

logging.basicConfig( # Set up logging configuration
    level=logging.INFO, # Minimum level: INFO
    format="%(asctime)s - %(levelname)s - %(message)s" # Include time, level, and message
)
logging.info("Custom formatted log message") # Log a message with the custom format

? Live Output & Explanation

? Sample Console Output

For the custom format example above, your console might show something like:

2025-11-19 12:34:56,789 - INFO - Custom formatted log message
  • 2025-11-19 12:34:56,789%(asctime)s (timestamp).
  • INFO%(levelname)s (log level).
  • Custom formatted log message%(message)s (your text).

If you set level=logging.WARNING, then only WARNING, ERROR, and CRITICAL logs will appear. DEBUG and INFO messages will be ignored.

✅ Tips & Best Practices

  • Prefer logging over print() in real projects, especially in production.
  • Choose appropriate log levels: use DEBUG for deep details, INFO for normal flow, and ERROR/CRITICAL for failures.
  • Always configure a logging level, otherwise important messages may not appear.
  • Use format to include timestamps and log levels for better debugging.
  • For long-running apps, log to a file so you can inspect logs later.

? Try It Yourself

  • Create a script that logs messages at all levels and observe which ones appear when you change the global level in basicConfig().
  • Configure logging to write WARNING and above to a file named errors.log.
  • Add timestamps and log levels to every message using a custom format.
  • Trigger a deliberate error in your code (like dividing by zero) and log an ERROR message when it occurs.
  • Explore advanced usage: create a Logger object with logging.getLogger() and attach separate console and file handlers.

? Use Cases

  • Monitoring a web application’s requests, errors, and performance.
  • Debugging complex data-processing pipelines.
  • Recording important events in desktop or CLI tools.
  • Tracking background jobs or scheduled tasks.