Standard Library
Logging
A logger name records which part of the program produced the event. The handler and formatter choose where and how the event is shown.
Source
import logging
import sys
logger = logging.getLogger("example.worker")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
parts = ["%(levelname)s", "%(name)s", "%(message)s"]
formatter = logging.Formatter(":".join(parts))
handler.setFormatter(formatter)
logger.handlers[:] = [handler]
logger.propagate = False
logger.debug("hidden detail")
logger.info("service started")
logger.warning("disk almost full")Output
INFO:example.worker:service started
WARNING:example.worker:disk almost fullLevels are thresholds. Raising the handler level to WARNING suppresses later INFO records without changing the call sites.
Source
import logging
import sys
logger = logging.getLogger("example.worker")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.WARNING)
parts = ["%(levelname)s", "%(name)s", "%(message)s"]
formatter = logging.Formatter(":".join(parts))
handler.setFormatter(formatter)
logger.handlers[:] = [handler]
logger.propagate = False
logger.info("hidden after threshold change")
logger.error("write failed")Output
ERROR:example.worker:write failedNotes
- Configure logging once; call named loggers throughout the program.
- Logger and handler levels both participate in filtering.
- Use exceptions for control flow failures, logging for operational evidence, and warnings for soft compatibility problems.
See also
- prerequisite: Exceptions
- related: Testing
- prerequisite: Modules
Run the complete example
Expected output
INFO:example.worker:service started
WARNING:example.worker:disk almost full
ERROR:example.worker:write failed
Execution time appears here after you run the example.