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.
Python code
17 linesimport 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
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
- Use `logging.basicConfig(level=logging.INFO)` to skip debug messages in production
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.