Python Logging Module logging timestamp to include

2019-02-18 04:47发布

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()

Here's the output I get --

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

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

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

2条回答
叼着烟拽天下
2楼-- · 2019-02-18 05:21

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
查看更多
成全新的幸福
3楼-- · 2019-02-18 05:35

I didnt find a easy way to print out microsecond,but %(created).6f could be a temp solution, which will be the result of time.time(),like 1517080746.007748.

Didnt find a way to remove unnecessary part, so if you really need microsecond, but dont want to change your code too much, one easy way will be

logging.basicConfig(level=logging.INFO,format="%(asctime)s.%(msecs)03d[%(levelname)-8s]:%(created).6f %(message)s", datefmt="%Y-%m-%d %H:%M:%S")

It will give you below output,

2018-01-28 04:19:06.807[INFO    ]:1517080746.807794 buy order issued
2018-01-28 04:19:07.007[INFO    ]:1517080747.007806 buy order issued
2018-01-28 04:19:07.207[INFO    ]:1517080747.207817 buy order issued
2018-01-28 04:19:07.407[INFO    ]:1517080747.407829 buy order issued
2018-01-28 04:19:07.607[INFO    ]:1517080747.607840 buy order issued
查看更多
登录 后发表回答