Python › Logging

How does logging.NullHandler help library authors avoid the 'No handlers could be found' warning?

Advanced

Answer

Library code should never call basicConfig() or add real handlers, since that forces logging configuration onto whatever application imports it. Instead, libraries attach a NullHandler to their top-level logger, which silently discards records if the consuming application hasn't configured any handlers, avoiding the historical 'No handlers could be found for logger X' warning while leaving full control to the application.
# in mylib/__init__.py
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())

# The application using mylib configures real handlers itself
import logging
logging.basicConfig(level=logging.INFO)
Real-world example An open-source library adds a NullHandler in its top-level __init__.py so it never prints unexpected output or errors when imported into an application that hasn't set up logging yet.

Common follow-ups: Why shouldn't a library call basicConfig()?;What happens if no NullHandler is attached and no handler is configured?