Sub topic 12
Logging in Libraries and NullHandler
This chapter assumes you know named loggers, handlers, and how records propagate up the logger hierarchy. A library is code that other programs import. Its logging needs differ from an application's, because the library does not own the process.
The rule: libraries emit, applications configure
A library should create records and leave the decision about where they go to the application. If a library calls basicConfig, adds a StreamHandler, or sets the root logger's level, it overrides choices the application author may have made. Two libraries doing this would also produce duplicate or conflicting output.
Follow these rules in library code:
- Get a logger with
logging.getLogger(__name__), so records carry the package's dotted name. - Add one
NullHandlerto the library's top-level logger. - Never configure the root logger, set handlers other than
NullHandler, or callbasicConfig. - Do not set levels on your loggers. Let the application choose.
What NullHandler does
NullHandler is a handler whose handle method does nothing. Adding it to the library's top-level logger means that when the application has configured nothing, the records have a handler to reach, and nothing is printed.
The NullHandler also matters because of Python's "last resort" handler. If a record reaches the end of the hierarchy and no handler has been found anywhere, Python prints WARNING and higher records to stderr in a bare format. A NullHandler counts as a handler, so this fallback is skipped. Your library stays silent unless the application opts in.
import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
def compute(x):
logger.debug("compute called with %r", x)
return x * 2In a package, put the addHandler line in the package's __init__.py, using logging.getLogger(__name__) there. Submodules call logging.getLogger(__name__) without adding handlers. Their records propagate up to the package logger and then to the application's handlers.
How the application takes control
Because the library's loggers are named after the package, the application can configure them like any other part of the hierarchy. Suppose the library above is a package called mylib. The application can turn on its debug output without touching the library:
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger("mylib").setLevel(logging.DEBUG)
from mylib import compute
compute(21)The mylib logger now has level DEBUG, and its records propagate to the root handler that basicConfig installed. The application can equally raise the level to WARNING to quiet the library.
The NullHandler does not block propagation. The record is handed to the NullHandler, which ignores it, and then continues to the ancestors' handlers because propagate is still true.
Common mistakes
- Calling
basicConfigin a library. It configures the root logger for the whole process. Only the application's entry point should call it. - Adding a
StreamHandlerto the library logger. Output then appears even when the application wants silence, and it can appear twice once the application adds its own handler. - Using the root logger directly (
logging.info(...)). Records have no library-specific name, so the application cannot filter them separately. - Formatting messages eagerly. Write
logger.debug("x=%r", x)rather than an f-string, so the work is skipped when DEBUG is off.
Exercise
A library's top-level logger has a NullHandler and no level set. The application calls logging.basicConfig(level=logging.INFO). Will the library's logger.info("ready") call be printed, and why?
Show answer
Yes. The library logger has no level, so it uses the effective level of its nearest ancestor, the root logger at INFO. The record passes the check, the NullHandler ignores it, and the record then propagates to the root logger's handler, which prints it.
Exercise
Why should a library avoid calling logging.basicConfig?
Show answer
It configures the root logger for the entire process, overriding the application's choices of handlers, levels, and format. Configuration belongs to the application's entry point.