Python logging module is printing lines multiple times
In my case , the root loggers handler were also being called , All I did was to set propagate
attribute of logger instance to False
.
import logging
logger = logging.getLogger("MyLogger")
# stop propagting to root logger
logger.propagate = False
# other log configuration stuff
# ....
logger is created once, but multiple handlers are created.
Create A
once.
a = A()
for msg in ["hey", "there"]:
a.p(msg)
Or change _get_logger
as follow:
def _get_logger(self):
loglevel = logging.INFO
l = logging.getLogger(__name__)
if not getattr(l, 'handler_set', None):
l.setLevel(loglevel)
h = logging.StreamHandler()
f = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
h.setFormatter(f)
l.addHandler(h)
l.setLevel(loglevel)
l.handler_set = True
return l
UPDATE
Since Python 3.2, you can use logging.Logger.hasHandlers
to see if this logger has any handlers configured. (thanks @toom)
def _get_logger(self):
loglevel = logging.INFO
l = logging.getLogger(__name__)
if not l.hasHandlers():
...
return l