I'm using Python logging, and for some reason, all of my messages are appearing twice.
I have a module to configure logging:
# BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting.
def configure_logging(self, logging_file):
self.logger = logging.getLogger("my_logger")
self.logger.setLevel(logging.DEBUG)
self.logger.propagate = 0
# Format for our loglines
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# Setup console logging
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
self.logger.addHandler(ch)
# Setup file logging as well
fh = logging.FileHandler(LOG_FILENAME)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
self.logger.addHandler(fh)
Later on, I call this method to configure logging:
if __name__ == '__main__':
tom = Boy()
tom.configure_logging(LOG_FILENAME)
tom.buy_ham()
And then within say, the buy_ham module, I'd call:
self.logger.info('Successfully able to write to %s' % path)
And for some reason, all the messages are appearing twice. I commented out one of the stream handlers, still the same thing. Bit of a weird one, not sure why this is happening...lol. Assuming I've missed something obvious.
Cheers, Victor
The handler is added each time you call from outside. Try Removeing the Handler after you finish your job:
If you are seeing this problem and you're not adding the handler twice then see abarnert's answer here
From the docs:
So, if you want a custom handler on "test", and you don't want its messages also going to the root handler, the answer is simple: turn off its propagate flag:
logger.propagate = False
A call to
logging.debug()
callslogging.basicConfig()
if there are no root handlers installed. That was happening for me in a test framework where I couldn't control the order that test cases fired. My initialization code was installing the second one. The default uses logging.BASIC_FORMAT that I didn't want.You are calling
configure_logging
twice (maybe in the__init__
method ofBoy
) :getLogger
will return the same object, butaddHandler
does not check if a similar handler has already been added to the logger.Try tracing calls to that method and eliminating one of these. Or set up a flag
logging_initialized
initialized toFalse
in the__init__
method ofBoy
and changeconfigure_logging
to do nothing iflogging_initialized
isTrue
, and to set it toTrue
after you've initialized the logger.If your program creates several
Boy
instances, you'll have to change the way you do things with a globalconfigure_logging
function adding the handlers, and theBoy.configure_logging
method only initializing theself.logger
attribute.Another way of solving this is by checking the handlers attribute of your logger:
I'm a python newbie, but this seemed to work for me (Python 2.7)