Python记录器,相对时间(relativeCreated),可以重置引用吗?

2024-06-14 06:52:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我感兴趣地注意到Python日志类可以发出一个相对时间戳:

https://docs.python.org/3/library/logging.html#logrecord-attributes

它提供了属性relativeCreated,但其记录如下:

Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.

我想知道有没有一种方法可以重置这个参考时间(默认情况下是在加载日志模块时)

我想重置参考时间,并查看相对于我重置的时间点的时间


Tags: thehttpsorgdocs属性logginghtmllibrary
1条回答
网友
1楼 · 发布于 2024-06-14 06:52:30

多亏了@Luv和一些进一步的阅读,这个问题现在已经解决了。事实上,使用过滤器而不是格式化程序是更好的方法,但这为我提供了一个可以报告相对时间的记录器(和一个换行符包装器I值):

'''
Logging utilities

To use, just import "log" from here and call log.debug(msg).
'''
from time import time
import re, logging
from re import RegexFlag as ref # Specifically to avoid a PyDev Error in the IDE.

log = logging.getLogger("my_logger")

class RelativeFilter(logging.Filter):
    '''
    Abuse of a logging filter to augment the logged record with some relative timing data.

    For a justification of this abuse see: 
        https://docs.python.org/3/howto/logging-cookbook.html#context-info

    The benefits are:

    1) Attached to logger and not to a handler 
        (solution customizing Formatter are attached to handlers)
        See: https://stackoverflow.com/questions/37900521/subclassing-logging-formatter-changes-default-behavior-of-logging-formatter

    2) Is called for every message that the logger processes. 
    '''
    time_reference = None
    time_last = None

    # A simple RE to suck out prefix and postfix newlines from the message and make them
    # separately available. The formatter can choose to render these or not as it sees fit
    # but a formatter like:
    #     '%(prefix)s other stuff %(message)s% other stuff (postfix)s'
    # will wrap the whole log message in the prefix/postfix pair. 
    RE = re.compile(r'^(?P<newlines1>\n*)(?P<message>.*?)(?P<newlines2>\n*)$', ref.DOTALL)

    def filter(self, record):
        now = time()

        if not self.time_reference:
            self.time_reference = now
        if not self.time_last:
            self.time_last = now

        matches = self.RE.match(record.msg).groupdict()

        record.relativeReference = now - self.time_reference
        record.relativeLast = now - self.time_last
        record.prefix = matches['newlines1']
        record.postfix = matches['newlines2']
        record.msg = matches['message']

        self.time_last = now 
        return True

relative_filter = RelativeFilter()

log.addFilter(relative_filter)

参考时间可通过以下方式轻松重置:

relative_filter.time_reference = time()

比如说

相关问题 更多 >