Chris
Chris

Reputation: 6095

Why does Python logging only hide stdout if the handler is added first?

If we attach a handler to the root level logger in Python, we don't see any output in console:

import logging, logging.handlers, os

rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
rootLogger.addHandler(logging.NullHandler())
logging.info("We don't see this comment")

But if we call logging first, we see output in console. We even see that output after we add a handler:

import logging, logging.handlers, os

rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
logging.info("We see this comment")
rootLogger.addHandler(logging.NullHandler())
logging.info("But we also see this comment")

Why is this?

Upvotes: 2

Views: 91

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122486

If you don't specify a handler yourself Python will add a StreamHandler whenever you make a logging call. Presumably this is to prevent confusion whenever someone uses the logging module out of the box.

This behaviour is why, in the second example, you're having a StreamHandler and a NullHandler associated with the root logger. You can see this by looking at .handlers:

>>> rootLogger.handlers
[<logging.StreamHandler object at 0x1022a0650>, <logging.NullHandler object at 0x1022a0790>]

So the added NullHandler won't do anything, the other StreamHandler will do something and that's why you're seeing both logging messages. In the first example you added a handler yourself so there was only one handler, a NullHandler, and Python didn't need to add a handler by itself.

Upvotes: 1

Related Questions