Sub topic 12
Logging in libraries and NullHandler
This chapter assumes you know loggers, handlers, levels and propagation from the earlier chapters. It covers a different job: instrumenting a package that other people import, where you don't control the program that runs it.
The library's role
An application owns its output. It decides where records go, how they look, and which levels matter. A library only reports what happens inside it and leaves those decisions to the application.
| Concern | Application | Library |
|---|---|---|
| Call `basicConfig` or `dictConfig` | Yes | No |
| Attach console or file handlers | Yes | No |
| Set the root logger's level | Yes | No |
| Create loggers with `getLogger(__name__)` | Yes | Yes |
| Emit records at sensible levels | Yes | Yes |
| Add a `NullHandler` | No | Once, on the top-level package logger |
If a library configures output itself, it may duplicate the application's lines. It may also write to a destination the user never chose, or override a format the user set carefully. Because of the hierarchy, a library can log freely and the application still controls everything through the names the library's loggers carry.
What happens with no configuration
Suppose a library logs a warning and the application never configured logging. Python 3 has a fallback called the last-resort handler. It is a StreamHandler on stderr with level WARNING, and it prints only the bare message.
The fallback is used only when a record finds no handler anywhere along its propagation path. The next example shows the difference a NullHandler makes.
import logging
noisy = logging.getLogger("noisy")
quiet = logging.getLogger("quiet")
quiet.addHandler(logging.NullHandler())
noisy.warning("Printed to stderr by the last-resort handler")
noisy.info("Dropped: the last-resort handler only accepts WARNING and above")
quiet.warning("Silent: the NullHandler counts as a handler")NullHandler has an emit method that does nothing. Its only effect is that the logging machinery finds a handler, so the last-resort fallback never runs. When the application later configures a real handler, for example on the root logger, records from the library still propagate to it as usual.
Setting up a library
Add the NullHandler once, in the package's __init__.py, on the logger named after the package. Inside __init__.py, __name__ is the package name, so the logger is the top of the library's subtree.
# mylib/__init__.py
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())Every other module creates its own logger from its module name.
# mylib/core.py
import logging
logger = logging.getLogger(__name__)
def fetch(url):
logger.debug("Fetching %s", url)
if not url.startswith("http"):
logger.warning("Unusual URL scheme: %s", url)
return "data from " + urlThe logger in core.py is named mylib.core, so it is a child of mylib. You don't need a NullHandler in each module. The one on mylib is found during propagation and covers the whole subtree.
What the application does
The application decides whether and how the library's records appear. The tuning below uses only the library's logger name.
# app.py
import logging
from mylib.core import fetch
# No configuration yet: nothing is printed.
fetch("ftp://example.com")
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
# Show everything from mylib.
fetch("ftp://example.com")
# Now quiet the library without touching the rest of the program.
logging.getLogger("mylib").setLevel(logging.WARNING)
fetch("https://example.com") # DEBUG is dropped
fetch("ftp://example.org") # WARNING still appearsThe first call prints nothing. The second prints both the DEBUG and WARNING records, tagged mylib.core. After setLevel(logging.WARNING) on mylib, the child mylib.core inherits that effective level, as the hierarchy chapter described. Only the final call's warning appears.
This is why library authors should document their top-level logger name. The name is part of the public interface, because users depend on it to filter and route records.
Rules for library authors
- Use
logging.getLogger(__name__). Hard-coded or ad hoc names break the hierarchy and make filtering by package impossible. - Don't call
basicConfig. It does nothing if the root logger already has handlers. If it does run, it installs a handler on the root logger, which belongs to the application. - Don't add real handlers. The only handler a library should add is the
NullHandler. - Don't set
propagate = False. That would hide your records from the application's handlers. - Don't set levels on handlers or on the root logger. Setting a level on your own package logger is allowed but rarely needed. Leaving it unset (
NOTSET) lets users control it from above. - Use lazy formatting. Write
logger.debug("Fetching %s", url), not an f-string, so the string is only built if a handler will use it. - Guard expensive debug data. If building the message is costly, check first.
import logging
logger = logging.getLogger(__name__)
def summarize(items):
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Items: %s", sorted(items))
return len(items)Libraries and exceptions
A library shouldn't hide errors by logging them. If a call fails, raise an exception and let the caller decide what to do. Logging an exception and then re-raising it often produces the same traceback twice, once from the library and once from the application.
Log events that explain behavior without changing control flow:
- A retry happened.
- A fallback was used.
- A deprecated option was seen.
- A connection was opened or closed.
Keep secrets such as passwords, tokens and full request bodies out of library log messages. Users may send logs to systems with wider access than the program has.
Pitfalls when the application configures logging
Library loggers are usually created when the library is imported, which is often before the application configures logging. This ordering causes two common problems.
disable_existing_loggers.dictConfigdefaults this setting toTrue. Any logger that already exists and isn't named in the configuration is disabled. Imported library loggers are silenced without any error. Set"disable_existing_loggers": Falsein the application's configuration, as shown in thedictConfigchapter.- Configuration that targets the wrong name. Setting a level on
"mylib.core"affects one module. Setting it on"mylib"affects the whole package. Name the highest logger that matches what you want to control.
A related mistake is adding a NullHandler to the root logger inside a library. That affects every logger in the program and can hide records from other libraries that rely on the last-resort fallback. Keep the NullHandler on your own package's logger.
Checking library logging in tests
You can verify that a library emits the records you promise by using assertLogs, covered in a later chapter. The logger name in the test is the same name users rely on.
import logging
import unittest
from mylib.core import fetch
class FetchLoggingTest(unittest.TestCase):
def test_warns_on_unusual_scheme(self):
with self.assertLogs("mylib", level="WARNING") as cm:
fetch("ftp://example.com")
self.assertEqual(
cm.output,
["WARNING:mylib.core:Unusual URL scheme: ftp://example.com"],
)
if __name__ == "__main__":
unittest.main()The test listens on mylib, so it catches records from mylib.core through propagation.
Exercise
A library has logging.getLogger("lib").addHandler(logging.NullHandler()) in its __init__.py. A module lib.net logs a warning, and the application never configures logging. Is the warning printed? What happens if the NullHandler line is removed?
Show answer
With the NullHandler, nothing is printed. The record propagates from lib.net to lib, which has a handler, so the last-resort handler is never used, and the NullHandler discards the record. Without the NullHandler, no handler is found anywhere on the path. The last-resort handler then prints the bare warning message to stderr, because its level is WARNING.
Exercise
After an application calls logging.getLogger("lib").setLevel(logging.ERROR), will a logger.warning(...) call in lib.net reach the application's root handler? Explain using the effective level.
Show answer
No. lib.net has no level of its own, so its effective level is inherited from the nearest ancestor with a level, which is lib at ERROR. A WARNING record is below that threshold, so it is dropped at the logger before any handler is consulted. Handler levels on ancestors don't matter here, since the level check happens on the originating logger.
Exercise
Why should a library avoid calling logging.basicConfig(), even in its own __init__.py?
Show answer
basicConfig installs a handler on the root logger, which belongs to the application. It can duplicate the application's output, send records to a destination the user didn't choose, or stop the application's own basicConfig call from taking effect, since basicConfig does nothing when the root logger already has handlers. A library should only add a NullHandler to its own package logger and leave output configuration to the application.