0

I am working on a piece of code which instantiates its own logger with its own handlers and format.

Now I've added a use of a library which uses the logging module directly and it screws up my logger - The original logger starts printing each line twice in different formats while the default logger prints nothing at all.

Any suggestions? MCVE:

import sys
import logging
log = logging.getLogger('foo')
log.addHandler(logging.StreamHandler(sys.stdout))
log.setLevel(logging.DEBUG)

log.info("works once")
logging.info("Isn't printed")
log.info("printed twice with different format")

Output:

works once
printed twice with different format
INFO:foo:printed twice with different format

It also doesnt seem like the default logger somehow adds an extra handler to my logger instance:

> print log.handlers
[<logging.StreamHandler object at 0x7f5d14314990>]

I can't change the module I've included...

immortal
  • 3,118
  • 20
  • 38

1 Answers1

1

After digging and digging, I finally found the bit of documentation that saved me!

Logger.propagate

If this 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. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.

If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.

The constructor sets this attribute to True.

Setting log.propagate = False ended my misfortune.

It would appear that the 1st use of the default logger through logging.info has initialized the default logger and from that moment the propagation started having an effect.

immortal
  • 3,118
  • 20
  • 38
  • 2
    If you can, open a bug report on the library that you use. Libraries shouldn't use the root logger for their logging needs. It will cause issues like the one you are facing. Libraries should create their own logger (`getLogger()`) and attach a `NullHandler` to it. – m1keil Nov 23 '17 at 00:39