Python using logger with multiple handlers

2019-09-12 03:55发布

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?

0条回答
登录 后发表回答