Log Levels in Practice
Python defines five standard levels with increasing severity:
DEBUG (10): Detailed diagnostic information.
INFO (20): Confirmation that things are working normally.
WARNING (30): An indication of potential problems or deprecation.
ERROR (40): A failure in a specific operation.
CRITICAL (50): A serious error causing program termination.
NOTSET (0) causes a logger to inherit its parent’s effective level.
Appropriate use of these levels lets you adjust verbosity without changing code.
Two-Stage Filtering: Logger vs Handler
Logger Level: First gate: records below logger.level are discarded immediately.
Handler Level: Second gate: each handler only emits records at or above its handler.level.
This allows, for example, DEBUG messages to be logged to a file but only WARNING and above to the console.
Configuring Logger & Handlers
Use logger.setLevel(...) to control which messages the logger accepts.
Use handler.setLevel(...) to control which accepted messages each handler emits.
Attach multiple handlers for different ouputs (e.g., console vs file) with independent levels.
# Log levels in practice
import logging
import sys
print("Log levels in practice")
print("------\n")
for lvl in (
logging.DEBUG,
logging.INFO,
logging.WARNING,
logging.ERROR,
logging.CRITICAL,
):
print(
f"{logging.getLevelName(lvl):8} = {lvl}"
)
# Two-stage filtering
print("\n")
print("Two stage filtering")
print("------\n")
filter_logger = logging.getLogger("demo.filter")
filter_logger.setLevel(logging.INFO)
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.ERROR)
filter_logger.addHandler(stream_handler)
filter_logger.info("INFO: will not be shown")
filter_logger.error("ERROR: will be shown")
# Configuring logs and handlers
print("\n")
print("Configuring logs and handlers")
print("------\n")
data_logger = logging.getLogger("demo.data")
data_logger.setLevel(logging.DEBUG)
data_sh = logging.StreamHandler(sys.stdout)
data_sh.setLevel(logging.ERROR)
data_fh = logging.FileHandler("process.log", "w")
data_fh.setLevel(logging.INFO)
data_logger.addHandler(data_sh)
data_logger.addHandler(data_fh)
data_logger.debug("DEBUG: will be dropped")
data_logger.info("INFO: file only")
data_logger.warning("WARNING: file only")
data_logger.error("ERROR: file and console")
data_logger.critical("CRITICAL: file and console")
Fold
Fold all
Expand
Expand all
Are you sure you want to delete this link?
Are you sure you want to delete this tag?
The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community