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.