我正在使用 python 记录器。以下是我的代码:
import os import time import datetime import logging class Logger : def myLogger(self): logger = logging.getLogger('ProvisioningPython') logger.setLevel(logging.DEBUG) now = datetime.datetime.now() handler=logging.FileHandler('/root/credentials/Logs/ProvisioningPython'+ now.strftime("%Y-%m-%d") +'.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) return logger
我遇到的问题是每次logger.info调用的日志文件中都有多个条目。我该如何解决这个问题?
logger.info
logging.getLogger()is 返回给定名称的相同实例。(文档)
logging.getLogger()
问题是每次调用时myLogger(),它都会向实例添加另一个处理程序,这会导致重复日志。
myLogger()
也许是这样的?
import os import time import datetime import logging loggers = {} def myLogger(name): global loggers if loggers.get(name): return loggers.get(name) else: logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) now = datetime.datetime.now() handler = logging.FileHandler( '/root/credentials/Logs/ProvisioningPython' + now.strftime("%Y-%m-%d") + '.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) loggers[name] = logger return logger