I have a script which imports a logging module (based on logging
) and another module (which in turn imports the same logging module as the main one -- to have consistent logging accorss the scripts and modules).
Everything works fine except that I get duplicated messages. Below are the scripts stripped down to the problematic part:
The main script. It sets a logging handler, used in a method of his
# the main script
# it is the one started
import dslogger
import mytestmodule
class MyClass():
def __init__(self):
self.log = dslogger.DSLogger().rootLogger
def dosomething(self):
self.log.debug("hello from dosomething")
mytestmodule.MyTestModule()
MyClass().dosomething()
The mytestmodule
. Here stripped down to __init__
:
# mytestmodule.py
import dslogger
class MyTestModule():
def __init__(self):
self.log = dslogger.DSLogger().rootLogger
self.log.debug("hello from mytestmodule")
dslogger.py
, the 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 the main script I get:
2014-11-04 08:56:59,637 [__init__] [DEBUG] hello from mytestmodule
2014-11-04 08:56:59,637 [dosomething] [DEBUG] hello from dosomething
2014-11-04 08:56:59,637 [dosomething] [DEBUG] hello from dosomething
The second and third line are duplicated, even though they are generated by the dosomething()
method which is called only once, from the main script. Why is it so?