Python using logger with multiple handlers

≡放荡痞女 提交于 2020-01-06 15:49:50

问题


If I define a logger with 2 handlers in a module A

# module A
import logging

logger = logging.getLogger('PARSER')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('glm_parser.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

Then the module A is imported to other modules for multiple times. However, each time A is imported, the code would be executed, so in the end I have 2 * x handlers, where x is the number of times A is imported.

How do you avoid this problem?

来源:https://stackoverflow.com/questions/38384065/python-using-logger-with-multiple-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!