Learning Tips | Published Nov 16, 2026 | 7 min read

Python Logging: A Practical Guide

Learn Python logging levels, named loggers, handlers, formatters, exception traces, and safe configuration practices.

Diagram showing application log events flowing through a named logger, handler and formatter to console or file output

Python logging records events that help you understand what an application did and diagnose problems later. The standard logging package separates loggers, handlers, and formatters so one event can be sent to a console, file, or other destination. This guide covers a useful starter setup, log levels, exceptions, and common configuration mistakes.

Use logging for events, not ordinary output

Use print() for output intended for a program's user, such as a command-line result. Use logging for operational events: progress, warnings, failures, and diagnostic details that may help you investigate behavior.

Python's standard library exposes severity levels from least to most severe: DEBUG, INFO, WARNING, ERROR, and CRITICAL. Choose a level based on what the event means, not just how urgent it feels. By default the system commonly shows WARNING and above unless configured otherwise.

Create a module-level logger

In each module, a common convention is logging.getLogger(__name__). The logger name then follows the module hierarchy, making it easier to tell where an event came from:

import logging

logger = logging.getLogger(__name__)

def load_profile(profile_id):
    logger.info("Loading profile id=%s", profile_id)
    try:
        return read_profile(profile_id)
    except OSError:
        logger.exception("Could not load profile id=%s", profile_id)
        raise

Pass variable data as arguments instead of building the full message with an f-string. The logging system can defer formatting until it needs to emit the event. logger.exception() records exception information and is intended to be called from an exception handler. Re-raise when the current layer cannot recover.

Configure the application once

A small script can use basicConfig() near program startup to choose the minimum level, destination, and message format:

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)

logger = logging.getLogger(__name__)
logger.info("Application started")

For a script that needs a log file, configure a filename and encoding, and decide how the file should be rotated or retained. For a service, container, or hosted application, writing to standard output may fit the surrounding log collection system better. Choose the destination based on the deployment environment.

basicConfig() is a convenient one-time setup. In larger applications that need multiple destinations or structured configuration, configure handlers and formatters deliberately or use the application's established logging configuration.

Understand logger, handler, and formatter

  • Logger: application code calls it to create an event and assign a severity.
  • Handler: sends records to a destination such as a stream or file.
  • Formatter: controls how a record is rendered, including time, level, logger name, and message.
  • Filter: can accept or reject records for more specific routing.

Logger names form a dotted hierarchy, similar to module names. A child logger's records can propagate to parent handlers. Attaching handlers repeatedly to both a child and an ancestor may print the same event more than once, so attach a handler at the appropriate point and understand propagation before adding another.

Use levels consistently

  • DEBUG: detailed diagnostic information useful while investigating behavior.
  • INFO: notable normal operation, such as a job starting or completing.
  • WARNING: something unexpected occurred, but the program can continue.
  • ERROR: an operation failed and needs attention or recovery.
  • CRITICAL: a serious failure may prevent the application from continuing.

Do not log every loop iteration at INFO or turn a recoverable user input error into CRITICAL. A useful record gives enough context to explain what happened without flooding the output.

Library authors and application owners have different roles

Application code generally owns logging configuration: destinations, formats, and level policy. A reusable library should create named loggers and emit events, but should avoid configuring the root logger or attaching output handlers behind the application's back. The Python documentation recommends a NullHandler for libraries that do not want fallback warning output when no application configuration exists.

Common mistakes to avoid

  1. Using the root-level convenience functions throughout a multi-module package instead of named loggers.
  2. Calling basicConfig() in multiple modules and expecting it to reconfigure existing handlers.
  3. Attaching handlers at multiple levels without checking propagation, which can duplicate messages.
  4. Logging secrets, passwords, access tokens, or unnecessary personal data. Redact sensitive values before emitting records.
  5. Using logger.error() when an exception should be raised, or catching an error and silently continuing without a clear recovery path.
  6. Writing unbounded log files without a rotation or retention policy.

Practical checklist

  1. Create a module logger with getLogger(__name__).
  2. Configure logging once in the application entry point.
  3. Choose a level and include the identifiers needed to investigate an event.
  4. Use exception() inside exception handlers when a traceback is useful.
  5. Check logger propagation and handler placement before diagnosing duplicate messages.
  6. Protect sensitive data and set retention for file destinations.

Logging is most useful when events are consistent, appropriately leveled, and routed according to the application's environment. Start with one logger convention and one clear configuration point, then add destinations only when the operational need is known.

Further reading

Want a structured Java learning path?

Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.

Explore the Java program   Ask for course guidance