Log to stderr with Python logging basicConfig

Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

17 lines
Python 3.9+
import logging

def main():
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
        stream=__import__("sys").stderr,
    )
    logger = logging.getLogger("example")
    logger.debug("Debug message")
    logger.info("Info message")
    logger.warning("Warning message")
    logger.error("Error message")
    logger.critical("Critical message")

if __name__ == "__main__":
    main()

Output

stdout
2024-01-15 10:30:45,123 — example — DEBUG — Debug message
2024-01-15 10:30:45,124 — example — INFO — Info message
2024-01-15 10:30:45,125 — example — WARNING — Warning message
2024-01-15 10:30:45,126 — example — ERROR — Error message
2024-01-15 10:30:45,127 — example — CRITICAL — Critical message

How it works

logging.basicConfig configures the root logger with a handler that writes to sys.stderr by default, but the stream parameter lets you explicitly choose the output target. Setting level=logging.DEBUG means every message at or above DEBUG severity is captured. The format string includes a timestamp (%(asctime)s), logger name, log level, and the message itself. Using stderr keeps log output separate from stdout, so it can be filtered or captured separately in pipelines and production systems.

Common mistakes

  • Calling basicConfig more than once — subsequent calls are ignored by the root logger
  • Forgetting the `level` parameter, so default WARNING severity filters out debug/info messages
  • Using print() for logging instead of the logging module, which loses timestamps and severity levels

Variations

  1. Use `logging.basicConfig(level=logging.INFO)` to skip debug messages in production
  2. Set a file handler with `logging.FileHandler('app.log')` to write logs to a file instead of stderr

Real-world use cases

  • Serving web app logs so they flow to the container's stderr and get picked up by Docker or Kubernetes log collectors.
  • Running CLI scripts where informational output goes to stdout but errors and warnings go to stderr for separate capture.
  • Debugging a service in CI — stderr logs are shown on failure and hidden on success by the test runner.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.