Python › Logging

How do you format log output to include the timestamp, logger name, level, and message?

Beginner

Answer

A Formatter string uses LogRecord attribute placeholders like %(asctime)s, %(name)s, %(levelname)s, and %(message)s, combined into a single format string applied to every emitted record by a handler's setFormatter() call.
import logging

formatter = logging.Formatter('%(asctime)s [%(name)s] %(levelname)s: %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
logging.warning('Low disk space')
# 2024-01-15 10:30:00,123 [root] WARNING: Low disk space
Real-world example An ops team standardizes on a JSON-formatted log line (using a custom Formatter subclass) across all services so their log aggregation platform can parse fields consistently.

Common follow-ups: What other LogRecord attributes are commonly used (%(module)s, %(lineno)d)?;How would you write a JSON-output Formatter?