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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python记录器,相对时间(relativeCreated),可以重设引用吗?相关的知识,希望对你有一定的参考价值。

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

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

它具有属性relativeCreated,但记录为:

创建LogRecord的时间,以毫秒为单位,相对于日志模块加载的时间。

我想知道有一种方法可以重置此参考时间(默认情况下是加载日志记录模块的时间)。

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

答案

感谢@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>
*)(?P<message>.*?)(?P<newlines2>
*)$', 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()

例如。

以上是关于Python记录器,相对时间(relativeCreated),可以重设引用吗?的主要内容,如果未能解决你的问题,请参考以下文章

Python 打印日志

BUG记录Python中的相对文件路径

BUG记录Python中的相对文件路径

[vsCode实践] 实践记录

python学习记录2

Python 文件路径