使用自定义时间戳(不是当前时间戳)进行Python日志记录

时间:2017-11-06 21:55:56

标签: python logging

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

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

任何帮助?

2 个答案:

答案 0 :(得分: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之类的内容来动态修改日志消息。

答案 1 :(得分: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})