By default the class used to construct a new logger when logging.getLogger
is invoked is logging.Logger
, which will by default set the propagate
attribute to True
(documentation source). According to the documentation,
If this attribute [propagate
] evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger.
So the answer by @fcs will not work as long as one of the logger's parent has some nontrivial handler, which is most likely the case since the root logger is all logger's parent and it pretty much always has StreamHandler
with the stderr
stream.
The following simple fix will work:
import logging
null_logger = logging.getLogger('foo')
null_logger.addHandler(logging.NullHandler()) # read below for reason
null_logger.propagate = False
null_logger.error("error") # This message will still go nowhere
Note that adding the logging.NullHandler
is necessary since if a logging record is not handled by any handler, it will be handled by logging.lastResort
which will still emit this message to stderr
(behavior since Python 3.2).