I have setup a logging config file. And a python script reads the config file. However when I pass my print statements to logger.info() it prints them twice to console. I believe this is because of the root logger. Can anyone advise how to set this up correctly so that messages don't print twice to console.
- fileName: logging.conf
[loggers]
keys=root,MainLogger
[handlers]
keys=fileHandler,consoleHandler
[formatters]
keys=fullFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_MainLogger]
level=DEBUG
handlers=fileHandler,consoleHandler
qualname=MainLogger
propogate=0
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fullFormatter
args=('../logs/execution.log','w')
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=fullFormatter
args=(sys.stdout,)
[formatter_fullFormatter]
format=%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s|%(funcName)s|%(lineno)d] %(message)s
datefmt=%Y-%m-%d:%H:%M:%S
- filName: app.py
import logging
from logging.config import fileConfig
fileConfig('logging.conf',disable_existing_loggers=False)
logger=logging.getLogger('MainLogger')
logger.info('hello_world 1')
logger.info('hello_world 2')
The output I see in console is:
2022-02-10:07:45:17,681 INFO [app.py|<module>|6] hello_world 1
2022-02-10:07:45:17,681 INFO [app.py|<module>|6] hello_world 1
2022-02-10:07:45:17,681 INFO [app.py|<module>|7] hello_world 2
2022-02-10:07:45:17,681 INFO [app.py|<module>|7] hello_world 2
In the config file if set the handler to nothing (as shown below) then I will not see the duplicate messages.
[logger_root]
level=DEBUG
handlers=
This seems more like a workaround. I would still like to set the handlers as shown in the config file, instead of using this workaround. That way then through the code the developer has the choice to choose the MainLogger or use the default root logger (logger=logging.getLogger('MainLogger') or logger=logging.getLogger()) without having to modify the logging config file.
Is this the correct way to setup the config file ?
I saw a related issue mentioned in the link below. But it doesn't directly address my issue. log messages appearing twice with Python Logging