python记录器多次记录相同的条目
我有一个这样的记录器初始化函数:
def generate_logger():
import logging
LOG_FILENAME = os.path.join(PROJECT_DIR, "mylog.log")
FORMAT = "%(asctime)s : %(message)s"
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fh = logging.FileHandler(LOG_FILENAME)
formatter = logging.Formatter(FORMAT)
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
在我的代码的某些部分,我有这样的异常捕获:
logger = generate_logger()
except AttributeError:
logger.error('Opps we got an error')
奇怪的是,我将相同的错误写入两次,并且只能捕获一次,一旦我更改 logger.error('Opps we遇到错误')
使用 print "test"
,我打印了一次“test”。
问题是什么以及解决方案是什么?
I have a such logger initializing function:
def generate_logger():
import logging
LOG_FILENAME = os.path.join(PROJECT_DIR, "mylog.log")
FORMAT = "%(asctime)s : %(message)s"
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fh = logging.FileHandler(LOG_FILENAME)
formatter = logging.Formatter(FORMAT)
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
And at some part of my code I have such exception catching:
logger = generate_logger()
except AttributeError:
logger.error('Opps we got an error')
Weirdly I get same error written 2 times and it can be caugh only once, once I change logger.error('Opps we got an error')
with print "test"
, I get "test" printed once.
What can be the problem and the solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
每次调用该函数时,都会向根记录器添加一个新的 FileHandler:不带名称参数的 logger.getLogger() 调用每次都会返回相同的记录器对象。
您应该仅调用
generate_logger()
一次,然后通过调用logger.getLogger()
获取相同的记录器对象:(请注意,您不需要
generate_logger( )
现在返回一个值)You are adding a new FileHandler to the root logger every time you call that function: the call to
logger.getLogger()
without a name argument returns the same logger object every time.You should call
generate_logger()
only once and then simply get the same logger object by callinglogger.getLogger()
:(note that you do not need
generate_logger()
to return a value now)我也遇到了同样的问题并遇到了这个页面。是的,我还创建了多个处理程序。在
generate_logger()
中,您可以检查是否有任何其他处理程序并将其删除。I also faced the same problem and came across this page. Yes, I was also creating multiple handlers. In
generate_logger()
, you can check if there's any other handlers and delete them.我认为您可能会以某种方式将两个处理程序添加到记录器中。也许在某个时候会添加隐式处理程序。
I think you're probably getting two handlers added to the logger somehow. Perhaps at some point an implicit handler is being added.
您可能有两个处理程序处理相同的结果日志。
您要创建多少个处理程序?您执行了多少次
generate_logger
?每次执行generate_logger
时,您都会为同一文件创建另一个处理程序,从而导致潜在的重复。You probably have two handlers going to the same resulting log.
How many handlers are you creating? How many times are you executing
generate_logger
? Each time you executegenerate_logger
you'll create another handler to the same file, leading to potential duplication.为此可以使用单例设计模式:
43 class Singleton(type):
44“”“
45 定义一个实例操作,让客户端访问其唯一的
46 个实例。
47“”“
48
49 def init(cls, 名称, 基础, attrs, **kwargs):
50 super().init(名称、基础、属性)
51 cls._instance = 无
52
53 def 调用(cls, *args, **kwargs):
54 如果 cls._instance 为 None:
55 cls._instance = super().调用(*args, **kwargs)
56 返回 cls._instance
57
58
59
60 def _setup_logger(名称, log_file, level=logging.INFO):
61 """功能设置任意数量的记录器"""
62
63 handler =logging.FileHandler(log_file)
64 handler.setFormatter(格式化程序)
65 logger =logging.getLogger(名称)
66 logger.setLevel(级别)
67 logger.addHandler(处理程序)
68
69 返回记录器
70
71类Logger(metaclass=Singleton):
72
73 def init(self, file_name, level):
74 if not (isinstance(file_name, str) and
75 isinstance(level, int)):
76 引发 ValueError("无效参数")
77
78 self.log_inf = _setup_logger('inf', file_name+'.inf', level)
79 self.log_err = _setup_logger('err', file_name+'.err', level)
use can use singleton design pattern for this:
43 class Singleton(type):
44 """
45 Define an Instance operation that lets clients access its unique
46 instance.
47 """
48
49 def init(cls, name, bases, attrs, **kwargs):
50 super().init(name, bases, attrs)
51 cls._instance = None
52
53 def call(cls, *args, **kwargs):
54 if cls._instance is None:
55 cls._instance = super().call(*args, **kwargs)
56 return cls._instance
57
58
59
60 def _setup_logger(name, log_file, level=logging.INFO):
61 """Function setup as many loggers as you want"""
62
63 handler = logging.FileHandler(log_file)
64 handler.setFormatter(formatter)
65 logger = logging.getLogger(name)
66 logger.setLevel(level)
67 logger.addHandler(handler)
68
69 return logger
70
71 class Logger(metaclass=Singleton):
72
73 def init(self, file_name, level):
74 if not (isinstance(file_name, str) and
75 isinstance(level, int)):
76 raise ValueError("Invalid Args")
77
78 self.log_inf = _setup_logger('inf', file_name+'.inf', level)
79 self.log_err = _setup_logger('err', file_name+'.err', level)