Python日志记录模块的日志记录时间戳包括微秒 [英] Python Logging Module logging timestamp to include microsecond

查看:415
本文介绍了Python日志记录模块的日志记录时间戳包括微秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python的日志记录模块记录日志,但需要时间戳记包括微秒.时间戳似乎只能精确到毫秒. 这是我的测试代码

I am using python's logging module for logs, but needed the timestamp to include microsecond. It seems the timestamp can only get as precise as millisecond. Here's my test code

import logging

logging.basicConfig(format='%(asctime)s %(levelname)s {%(module)s} [%(funcName)s] %(message)s',

    datefmt='%Y-%m-%d,%H:%M:%S:%f', level=logging.INFO)

class log2_test():

    def test_class(self):

        logging.warning("Warning2 inside the class")

def get_started2():

    logging.info("Logged2 Here")

if __name__ == '__main__':
    get_started2()

这是我得到的输出-

2015-07-09,16:36:37:f INFO {logger} [get_started2] Logged2 Here

以某种方式,无法识别%f. Python版本是2.7.6.

Somehow, %f is not recognized. Python version is 2.7.6.

如何获取包含微秒的时间戳? 预先感谢.

How do I get the timestamp to include microseconds? Thanks in advance.

推荐答案

我不认为strftime()直接支持%f.记录器确实将毫秒作为单独的毫秒提供属性,因此您可以在现有时间戳之后添加自己,如下所示:

I do not think strftime() would support the %f directly. The logger does though provide milliseconds as a separate msecs attribute, so you could just add it yourself after the existing timestamp as follows:

logging.basicConfig(format='%(asctime)s.%(msecs)03d %(levelname)s {%(module)s} [%(funcName)s] %(message)s', datefmt='%Y-%m-%d,%H:%M:%S', level=logging.INFO)

这使用您的脚本给了我以下输出:

This gave me the following output using your script:

2015-07-10,09:21:16.841 INFO {test script} [get_started2] Logged2 Here

这篇关于Python日志记录模块的日志记录时间戳包括微秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆