Application diagnostics
Record application events without building a logging framework.
Python · Module
Python's logging module provides a flexible event-logging system for applications and libraries. Loggers create records that handlers route, filters select, and formatters lay out.
The module provides a flexible event-logging system. Application code sends records through loggers; handlers route them, filters decide which records pass, and formatters control their final layout.
logging.getLogger(name)| Name | Type | Description |
|---|---|---|
name | str | The logger name used to obtain or identify a logger. |
getLogger(name) returns a Logger object; makeLogRecord(attrdict) returns a LogRecord object.
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s:%(name)s:%(message)s")
logger = logging.getLogger(__name__)
logger.info("started")
logger.error("request failed")Configures the root logger and emits messages through a module-specific logger.
Record application events without building a logging framework.
Let reusable packages emit events that host applications can configure.
Route records to different destinations with controlled selection and presentation.
Loggers are the interface application code calls. Handlers deliver logger-created records to destinations, filters refine which records are output, and formatters define the records' final layout.
Follow-up: How would you make different destinations use different layouts? Attach separate handlers and assign a formatter to each handler.
Use logging.getLogger(name) to obtain a logger, because the documentation says loggers should not be instantiated directly. Reusing a name returns the same Logger object.
Follow-up: Why can a library and its caller coordinate logging? They can use named loggers in the same interpreter, allowing application configuration to handle library records.
A LogRecord is created automatically by a Logger whenever something is logged. The module also permits creating one manually with makeLogRecord(), including for an event received over the wire.
Follow-up: When might manual creation be useful? It can reconstruct an event represented by received or serialized logging data before processing it.
LoggerHandlerFilterFormatterLogRecordgetLoggermakeLogRecordbasicConfig