Skip to content
Advertisement

This logger has no handler, yet it prints. Why?

I have a sample logger that I think has no handler, yet it outputs log messages. Here is the code:

import logging

ll = logging.getLogger('ll')
print("Has handlers:", ll.hasHandlers())
print("Handlers:", ll.handlers)
ll.propagate = False

ll.warning("Logging with no Handler!")

And the result says the logger has no handlers, there is an empty list of handlers, yet it prints the output:

%  python example.py
Has handlers: False
Handlers: []
Logging with no Handler!
%

Why does this work? Do I need to add a NullHandler() to stop output?

Advertisement

Answer

It’s because for Python >= 3.2, there is a handler of last resort which outputs events of severity WARNING and greater to sys.stderr.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement