python - Why do I get duplicated logging messages? -
python - Why do I get duplicated logging messages? -
i have script imports logging module (based on logging) , module (which in turn imports same logging module main 1 -- have consistent logging accorss scripts , modules).
everything works fine except duplicated messages. below scripts stripped downwards problematic part:
the main script. sets logging handler, used in method of his
# main script # 1 started import dslogger import mytestmodule class myclass(): def __init__(self): self.log = dslogger.dslogger().rootlogger def dosomething(self): self.log.debug("hello dosomething") mytestmodule.mytestmodule() myclass().dosomething() the mytestmodule. here stripped downwards __init__:
# mytestmodule.py import dslogger class mytestmodule(): def __init__(self): self.log = dslogger.dslogger().rootlogger self.log.debug("hello mytestmodule") dslogger.py, logging module:
import logging class dslogger(): def __init__(self): logformatter = logging.formatter("%(asctime)s [%(funcname)s] [%(levelname)s] %(message)s") self.rootlogger = logging.getlogger(__name__) consolehandler = logging.streamhandler() consolehandler.setformatter(logformatter) self.rootlogger.setlevel(logging.debug) self.rootlogger.addhandler(consolehandler) when running main script get:
2014-11-04 08:56:59,637 [__init__] [debug] hello mytestmodule 2014-11-04 08:56:59,637 [dosomething] [debug] hello dosomething 2014-11-04 08:56:59,637 [dosomething] [debug] hello dosomething the sec , 3rd line duplicated, though generated dosomething() method called once, main script. why so?
what's happening here you're adding 2 streamhandlers same logger.
you initialize dslogger() twice. each time initialize it, phone call self.rootlogger = logging.getlogger(__name__). does not 2 different logger instances, since called same __name__:
import logging x = logging.getlogger('x') id(x) out[42]: 173704528l y = logging.getlogger('x') id(y) out[44]: 173704528l so when phone call self.log.debug("hello mytestmodule"), after dslogger() initalized once, , 1 streamhandler added logger. when initialize myclass, 1 added, , logger has 2 streamhandlers, , every log message printed twice.
python logging
Comments
Post a Comment