4

Following are the contents of mylogger.py:

def get_logger(name='my_super_logger'):
    log = logging.getLogger(name)
    log.setLevel(logging.DEBUG)
    formatter = logging.Formatter(fmt='%(asctime)s %(name)s %(message)s',
                                  datefmt='%m/%d/%Y %I:%M:%S %p')
    if not len(log.handlers):
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(formatter)
        log.addHandler(ch)
    # print(id(log))
    return log

and following is contents of myscript.py:

from mylogger import get_logger

_logger = get_logger()

_logger.info('trying info')
_logger.debug('trying debug')

However I am facing two issues. It prints the logs twice and formatter is not working everytime:

09/18/2015 09:59:54 PM my_super_logger trying info 
INFO:my_super_logger:trying info 
09/18/2015 09:59:54 PM my_super_logger trying debug 
DEBUG:my_super_logger:trying debug 

What exactly is the issue with my get_logger code?

I need a custom formatting. However I found out that without adding a handler I cannot add a formatter. So that's why I have added StreamHandler. And the reason for if block is mentioned in this answer. Without that, I would get duplicate log messages printed.

Community
  • 1
  • 1
avi
  • 8,686
  • 10
  • 45
  • 81

1 Answers1

4

The root logger is also emitting the message. Stop propagation up to the root with:

log.propagate = False

If you wanted to format all log output (so messages propagated up to the logger), set the formatter for the root logger.

You can do so with a logging.basicConfig() call provided nothing has yet been sent to the loggers, or by looping over the logger.handlers list of the root logger; you could pick out any StreamHandlers if you so wish:

root_logger = logging.getLogger()  # no name
for handler in root_logger.handlers:
    if isinstance(handler, logging.Streamhandler):
        handler.setFormatter(formatter)
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187