kdt
kdt

Reputation: 28489

Preventing double-output in python FileHandler when log paths overlap

The following code results in the same log message being output twice:

log1 = logging.getLogger('foo')
log1.addHandler(logging.FileHandler('log.txt'))
log2 = logging.getLogger('foo.bar')
log2.addHandler(logging.FileHandler('log.txt'))

log2.warn("test message")

I realize that this is because 'foo.bar' matches both the 'foo' and 'foo.bar' paths, so both loggers get the message. My question is: is there any way to prevent this behaviour other than making sure I never have two loggers pointing to the same file in the same log path?

Upvotes: 0

Views: 1099

Answers (1)

unutbu
unutbu

Reputation: 879869

You can tell log2 not to propagate messages to the handlers of ancestor loggers:

log2.propagate = False

import logging

log1 = logging.getLogger('foo')
log1.addHandler(logging.FileHandler('log.txt'))
log2 = logging.getLogger('foo.bar')
log2.addHandler(logging.FileHandler('log.txt'))
log2.propagate = False
log2.warn("test message")

writes test message only once in log.txt.

Upvotes: 3

Related Questions