gpt4 book ai didi

python - 如何访问 python LogRecord 的 asctime?

转载 作者:行者123 更新时间:2023-12-04 21:31:08 32 4
gpt4 key购买 nike

我有一个记录器和一个 DuplicateFilter 类,用于过滤已记录一次的消息。我想在我的过滤器中包含日志记录发生的时间,但是当我尝试访问属性 asctime 时,我得到:AttributeError: 'LogRecord' object has no attribute 'asctime'
这是我如何设置记录器的一个小示例:

import logging
import logging.handlers as log_handlers
def setup_logger(filename):
class DuplicateFilter(object):
def __init__(self):
self.msgs = set()

def filter(self, record):
if logger.level == 10:
return True
rv = True
try:
print(record.asctime)
msg = record.threadName + " " + record.msg
if msg in self.msgs:
rv = False
except Exception as e:
print(traceback.format_exc())
return rv
self.msgs.add(msg)
return rv

log_formatter = logging.Formatter("%(asctime)s [%(levelname)-5.5s] [%(threadName)-30.30s] %(message)s")
file_handler = log_handlers.TimedRotatingFileHandler(filename, encoding="UTF-8", when='W6', backupCount=12)
file_handler.setFormatter(log_formatter)

console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)

logger = logging.getLogger(filename)
logger.propagate = False

logger.addHandler(console_handler)
logger.addHandler(file_handler)

logger.setLevel(logging.INFO)

dup_filter = DuplicateFilter()
logger.addFilter(dup_filter)
return logger


log = setup_logger("test.log")
for i in range(3):
log.info("wow")

现在我的记录看起来像这样: 2018-07-18 14:34:49,642 [INFO ] [MainThread ] wow他们显然有一个 asctime,我在我的 Formatter 的构造函数中明确设置了 asctime 属性。唯一的 question类似于我发现的说

To have message and asctime set, you must first call self.format(record) inside the emit method



但是当您像我使用 %(asctime)s 那样指定日志字符串时,logging.Formatter 不会这样做?

编辑: running.t 是对的,我只是不明白文档的含义。我通过将我的格式化程序添加到我的过滤器并在开始时调用格式化函数来解决它:
 def __init__(self, formatter):
self.msgs = {}
self.formatter = formatter

def filter(self, record):
self.formatter.format(record)

最佳答案

filter objects section pyton 日志记录模块文档我发现以下注释:

Note that filters attached to handlers are consulted before an event is emitted by the handler, whereas filters attached to loggers are consulted whenever an event is logged (using debug(), info(), etc.), before sending an event to handlers. This means that events which have been generated by descendant loggers will not be filtered by a logger’s filter setting, unless the filter has also been applied to those descendant loggers.



您的过滤器被添加到记录器中,而格式化程序被添加到处理程序中。所以在我看来你的 filter方法在您指定的任何格式化程序之前应用。

顺便说一句,你的 DuplicateFilter 不应该吗?继承自 logging.Filter ?

关于python - 如何访问 python LogRecord 的 asctime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51402366/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com