Python logger prints lines several times

I have the 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) for msg in ["hey", "there"]: a = A() ap(msg) 

The output I get 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 is "there" printed twice? Similarly, if I add another Class A object inside the loop and print a message, it will print three times.

The documentation states that logging.getLogger () always returns the same logger instance if the log name matches. In this case, the name matches. Should it not return the same journal instance? If so, why is the message printed several times?

+6
source share
2 answers

logger is created once, but several handlers are created.

Create A once.

 a = A() for msg in ["hey", "there"]: ap(msg) 

Or modify _get_logger as follows:

 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 
+12
source

In my case, the root log handler is also called. All I did was set the propagate attribute of the log instance to False .

 import logging logger = logging.getLogger("MyLogger") # stop propagting to root logger logger.propagate = False # other log configuration stuff # .... 
+4
source

Source: https://habr.com/ru/post/949823/


All Articles