【问题标题】:Python logging using custom timestamps (not current timestamp)使用自定义时间戳(不是当前时间戳)的 Python 日志记录
【发布时间】:2017-11-06 21:55:55
【问题描述】:

我正在通过以下方式使用日志记录模块:

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    filename=my_filename,
                    filemode='w')

logging.info("Set up logger")

写作。输出是:

2017-11-05 19:10:22,762 root      INFO     Set up logger

问题:我想要一个过去(或未来,无论如何)的时间戳,而不是当前时间戳。因此,每当我想在日志中写一些东西时,我可以将日期作为参数传递,例如:

logging.info(msg="Set up logger", date='2010-01-01 19:10:22,762')

为了拥有

2010-01-01 19:10:22,762 root      INFO    Set up logger

有什么帮助吗?

【问题讨论】:

  • 所以您希望时间戳不是实际的时间戳?那有什么意义呢?如果您只想在消息中添加任意内容,您可以已经这样做了,目前还不清楚问题是什么。
  • 如果我把它放在消息中,我就不会有像 %(time)s %(name)s %(levelname)s %(message)s 这样的标准格式
  • 您可以自己进行格式化。
  • 我该怎么做?
  • time.stftime 一样,就像logging 本身使用的一样。

标签: python logging


【解决方案1】:

@m1keil 的答案适用于简单的情况,但如果您希望拥有多个以不同方式格式化时间的处理程序,或者您不需要/不想每次都指定时间,则会变得很麻烦进行日志调用等。这是一个稍微复杂一些的解决方案,但它是“更正确的方法”,并且与日志系统的正常时间戳处理更好地集成:

首先,您需要创建一个日志过滤器(过滤器能够修改通过它们所附加的记录器的日志记录):

class TimestampFilter (logging.Filter):
    """
    This is a logging filter which will check for a `timestamp` attribute on a
    given LogRecord, and if present it will override the LogRecord creation time
    to be that of the timestamp (specified as a time.time()-style value).
    This allows one to override the date/time output for log entries by specifying
    `timestamp` in the `extra` option to the logging call.
    """

    def filter(self, record):
        if hasattr(record, 'timestamp'):
            record.created = record.timestamp
        return True

然后,只需创建一个过滤器实例并将其添加到适当的记录器实例:

logger = logging.getLogger(__name__)
filter = TimestampFilter()
logger.addFilter(filter)

然后,当您想要覆盖日志条目的日期/时间时,在进行日志调用时,请在 extra 中提供时间戳:

my_timestamp = time.time() + 86400  # Let's pretend it's tomorrow already
logger.warn("I am a warning from the future!", extra={'timestamp': my_timestamp})

【讨论】:

    【解决方案2】:

    您可以这样做:

    logging.basicConfig(level=logging.DEBUG,
                        format='%(date)s %(name)-12s %(levelname)-8s %(message)s',
                        filename=my_filename,
                        filemode='w')
    

    并记录:

    logging.info(msg="Set up logger", extra={'date':'2010-01-01 19:10:22,762'})
    

    请注意,由于您在格式中硬编码了 date 参数,因此没有该格式的日志消息将失败。如果你想让它成为可选的,你需要使用类似filters的东西来动态修改你的日志消息。

    【讨论】:

    • 我试过你说的,但没有用:TypeError: _log() got an unexpected keyword argument 'date'
    • 我的坏@riccio777,更新了代码(忘了它是额外的arg)。
    • 谢谢,只是一件小事:字典中的日期应该带引号。
    • 我会在下次发布之前测试我的代码:|很高兴我能帮上忙
    猜你喜欢
    • 2015-02-16
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多