Python logging module is printing lines multiple times -


i have following code:

import logging class a(object):     def __init__(self):         self._l = self._get_logger()      def _get_logger(self):         loglevel = logging.info         l = logging.getlogger(__name__)         l.setlevel(logging.info)         h = logging.streamhandler()         f = logging.formatter('%(asctime)s %(levelname)s %(message)s')         h.setformatter(f)         l.addhandler(h)         l.setlevel(loglevel)         return l        def p(self, msg):         self._l.info(msg)  msg in ["hey", "there"]:     = a()     a.p(msg) 

the output is:

2013-07-19 17:42:02,657 info hey 2013-07-19 17:42:02,657 info there 2013-07-19 17:42:02,657 info there 

why "there" being printed twice? similarly, if add object of class inside loop , print message, gets printed thrice.

the documentation says logging.getlogger() return same instance of logger if name of logger matches. in case, name match. should not return same logger instance? if infact doing so, why message getting printed multiple times?

logger created once, multiple handlers created.

create a once.

a = a() msg in ["hey", "there"]:     a.p(msg) 

or change _get_logger follow:

def _get_logger(self):     loglevel = logging.info     l = logging.getlogger(__name__)     if not getattr(l, 'handler_set', none):         l.setlevel(logging.info)         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   

Comments