On this page
logging
Prev: locale | Up: stdlib_module | Next: lzma
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — logging
Tags: #public #python3 #stdlib
Import
import logging
Overview
Hierarchical, configurable structured event logging with severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL), pluggable handlers (console, rotating files, syslog), and formatters. Use logging instead of print() in any reusable library or long-running service so callers control verbosity and output destinations.
Quick Start
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger(__name__)
logger.info("Service started on port %d", 8080)
Implementation Walkthrough
1. Library vs. Application Pattern
Libraries should only obtain a module logger (logging.getLogger(__name__)) and never call basicConfig(); applications configure handlers once at startup:
import logging
from logging.handlers import RotatingFileHandler
def configure_logging(log_file: str, level: int = logging.INFO) -> None:
root = logging.getLogger()
root.setLevel(level)
fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
console = logging.StreamHandler()
console.setFormatter(fmt)
file_handler = RotatingFileHandler(log_file, maxBytes=1_000_000, backupCount=3, encoding="utf-8")
file_handler.setFormatter(fmt)
root.addHandler(console)
root.addHandler(file_handler)
2. Capturing Tracebacks Cleanly
import logging
logger = logging.getLogger(__name__)
try:
1 / 0
except ZeroDivisionError:
logger.exception("Division failed for denominator=%s", 0)
Gotchas & Boundaries
- Use
%slazy formatting, not f-strings, in log calls:logger.debug("Payload: %s", big_obj)skips formatting whenDEBUGis disabled; f-strings evaluate eagerly every time. - Libraries must not call
logging.basicConfig(): Configuring the root logger inside a library hijacks the host application's logging setup. basicConfig()is a no-op if handlers already exist: Passforce=Trueonly in scripts/tests when you intentionally want to reset handlers.- Never log secrets, tokens, or raw PII: Redact credentials before passing them to logger arguments.
Common Functions
- logging.addLevelName() —
addLevelName(level, levelName)— Associate 'levelName' with 'level'. - logging.basicConfig() —
basicConfig(**kwargs)— Do basic configuration for the logging system. - logging.captureWarnings() —
captureWarnings(capture)— If capture is true, redirect all warnings to the logging package. - logging.critical() —
critical(msg, *args, **kwargs)— Log a message with severity 'CRITICAL' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. - logging.debug() —
debug(msg, *args, **kwargs)— Log a message with severity 'DEBUG' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. - logging.disable() —
disable(level=50)— Disable all logging calls of severity 'level' and below. - logging.error() —
error(msg, *args, **kwargs)— Log a message with severity 'ERROR' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. - logging.exception() —
exception(msg, *args, exc_info=True, **kwargs)— Log a message with severity 'ERROR' on the root logger, with exception information. If the logger has no handlers, basicConfig() is called to add a console handler with a pre-defined format. - logging.fatal() —
fatal(msg, *args, **kwargs)— Don't use this function, use critical() instead. - logging.getHandlerByName() —
getHandlerByName(name)— Get a handler with the specified name, or None if there isn't one with that name. - logging.getHandlerNames() —
getHandlerNames()— Return all known handler names as an immutable set. - logging.getLevelName() —
getLevelName(level)— Return the textual or numeric representation of logging level 'level'. - logging.getLevelNamesMapping() —
getLevelNamesMapping()—logging.getLevelNamesMapping()function. - logging.getLogger() —
getLogger(name=None)— Return a logger with the specified name, creating it if necessary. - logging.getLoggerClass() —
getLoggerClass()— Return the class to be used when instantiating a logger. - logging.getLogRecordFactory() —
getLogRecordFactory()— Return the factory to be used when instantiating a log record. - logging.info() —
info(msg, *args, **kwargs)— Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. - logging.log() —
log(level, msg, *args, **kwargs)— Log 'msg % args' with the integer severity 'level' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. - logging.makeLogRecord() —
makeLogRecord(dict)— Make a LogRecord whose attributes are defined by the specified dictionary, This function is useful for converting a logging event received over a socket connection (which is sent as a dictionary) into a LogRecord - logging.setLoggerClass() —
setLoggerClass(klass)— Set the class to be used when instantiating a logger. The class should define init() such that only a name argument is required, and the init() should call Logger.init() - logging.setLogRecordFactory() —
setLogRecordFactory(factory)— Set the factory to be used when instantiating a log record. - logging.shutdown() —
shutdown(handlerList=[<weakref at 0x10974cea0; to 'logging._StderrHandler' at 0x109740830>])— Perform any cleanup actions in the logging system (e.g. flushing buffers). - logging.warn() —
warn(msg, *args, **kwargs)—logging.warn()function. - logging.warning() —
warning(msg, *args, **kwargs)— Log a message with severity 'WARNING' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
Classes & Objects
- logging.BufferingFormatter — A formatter suitable for formatting a number of records. (Methods:
.format(),.formatFooter(),.formatHeader()) - logging.FileHandler — A handler class which writes formatted logging records to disk files. (Methods:
.acquire(),.addFilter(),.close(),.createLock(),.emit(),.filter()) - logging.Filter — Filter instances are used to perform arbitrary filtering of LogRecords. (Methods:
.filter()) - logging.Formatter — Formatter instances are used to convert a LogRecord to text. (Methods:
.converter(),.format(),.formatException(),.formatMessage(),.formatStack(),.formatTime()) - logging.Handler — Handler instances dispatch logging events to specific destinations. (Methods:
.acquire(),.addFilter(),.close(),.createLock(),.emit(),.filter()) - logging.Logger — Instances of the Logger class represent a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an (Methods:
.addFilter(),.addHandler(),.callHandlers(),.critical(),.debug(),.error()) - logging.LoggerAdapter — An adapter for loggers which makes it easier to specify contextual information in logging output. (Methods:
.critical(),.debug(),.error(),.exception(),.getEffectiveLevel(),.hasHandlers()) - logging.LogRecord — A LogRecord instance represents an event being logged. (Methods:
.getMessage()) - logging.NullHandler — This handler does nothing. It's intended to be used to avoid the "No handlers could be found for logger XXX" one-off warning. This is important for library code, which may contain code to log events. If a user (Methods:
.acquire(),.addFilter(),.close(),.createLock(),.emit(),.filter()) - logging.StreamHandler — A handler class which writes logging records, appropriately formatted, to a stream. Note that this class does not close the stream, as sys.stdout or sys.stderr may be used. (Methods:
.acquire(),.addFilter(),.close(),.createLock(),.emit(),.filter())
Constants & Attributes
logging.BASIC_FORMAT(str) ='%(levelname)s:%(name)s:%(message)s'logging.CRITICAL(int) =50logging.DEBUG(int) =10logging.ERROR(int) =40logging.FATAL(int) =50logging.INFO(int) =20logging.NOTSET(int) =0logging.WARN(int) =30logging.WARNING(int) =30logging.lastResort(_StderrHandler) =<_StderrHandler <stderr> (WARNING)>logging.raiseExceptions(bool) =True
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/locale
- tuts/python3/stdlib_module/logging/addLevelName
- tuts/python3/stdlib_module/logging/basicConfig
- tuts/python3/stdlib_module/logging/BufferingFormatter
- tuts/python3/stdlib_module/logging/captureWarnings
- tuts/python3/stdlib_module/logging/critical
- tuts/python3/stdlib_module/logging/debug
- tuts/python3/stdlib_module/logging/disable
- tuts/python3/stdlib_module/logging/error
- tuts/python3/stdlib_module/logging/exception
- tuts/python3/stdlib_module/logging/fatal
- tuts/python3/stdlib_module/logging/FileHandler
- tuts/python3/stdlib_module/logging/Filter
- tuts/python3/stdlib_module/logging/Formatter
- tuts/python3/stdlib_module/logging/getHandlerByName
- tuts/python3/stdlib_module/logging/getHandlerNames
- tuts/python3/stdlib_module/logging/getLevelName
- tuts/python3/stdlib_module/logging/getLevelNamesMapping
- tuts/python3/stdlib_module/logging/getLogger
- tuts/python3/stdlib_module/logging/getLoggerClass
- tuts/python3/stdlib_module/logging/getLogRecordFactory
- tuts/python3/stdlib_module/logging/Handler
- tuts/python3/stdlib_module/logging/info
- tuts/python3/stdlib_module/logging/log
- tuts/python3/stdlib_module/logging/Logger
- tuts/python3/stdlib_module/logging/LoggerAdapter
- tuts/python3/stdlib_module/logging/LogRecord
- tuts/python3/stdlib_module/logging/makeLogRecord
- tuts/python3/stdlib_module/logging/NullHandler
- tuts/python3/stdlib_module/logging/setLoggerClass
- tuts/python3/stdlib_module/logging/setLogRecordFactory
- tuts/python3/stdlib_module/logging/shutdown
- tuts/python3/stdlib_module/logging/StreamHandler
- tuts/python3/stdlib_module/logging/warn
- tuts/python3/stdlib_module/logging/warning
- tuts/python3/stdlib_module/lzma
- tuts/python3/stdlib_module/pprint
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/syslog
- tuts/python3/stdlib_module/traceback
- tuts/python3/tutorials/intermediate_python_and_software_engineering
- tuts/python3/tutorials/intermediate_python_and_software_engineering/testing_and_debugging
Related notes
- tuts/python3/stdlib_module/locale Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/logging/addLevelName Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/logging/basicConfig Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/logging/BufferingFormatter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/logging/captureWarnings Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/logging/critical Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/logging/debug Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/logging/disable Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/logging/error Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/logging/exception Linked here; links to this page; shared tags: #stdlib