Pythonlogging日志修改,显示成毫秒级时间戳 -> 1628822017676
Posted 青禾tester
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pythonlogging日志修改,显示成毫秒级时间戳 -> 1628822017676相关的知识,希望对你有一定的参考价值。
一、初始配置和日志显示
1、配置
format=%(asctime)s.%(msecs)03d %(name)s %(relativeCreated)d %(levelname)s %(module)s %(funcName)s %(message)s
datefmt=%Y/%m/%d %H:%M:%S
2、打印日志
2021/08/12 20:56:59.708 root 13280 INFO login click_mine_tab uicase2
2021/08/12 20:57:00.744 root 14317 INFO login click_avatar uicase3
2021/08/12 20:57:03.091 root 16664 INFO login click_other_login uicase3
2021/08/12 20:57:04.294 root 17866 INFO login click_phone_number uicase3
2021/08/12 20:57:04.933 root 18505 INFO login click_login_next uicase3
2021/08/12 20:57:06.477 root 20049 INFO login click_password_input uicase3
2021/08/12 20:57:07.288 root 20861 INFO login click_login_next2 uicase4
但预期希望显示成时间戳形式-> 类似:1628822021208
二、修改配置
1、直接修改 logging -> init.py
def formatTime(self, record, datefmt=None):
"""
Return the creation time of the specified LogRecord as formatted text.
This method should be called from format() by a formatter which
wants to make use of a formatted time. This method can be overridden
in formatters to provide for any specific requirement, but the
basic behaviour is as follows: if datefmt (a string) is specified,
it is used with time.strftime() to format the creation time of the
record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used.
The resulting string is returned. This function uses a user-configurable
function to convert the creation time to a tuple. By default,
time.localtime() is used; to change this for a particular formatter
instance, set the 'converter' attribute to a function with the same
signature as time.localtime() or time.gmtime(). To change it for all
formatters, for example if you want all logging times to be shown in GMT,
set the 'converter' attribute in the Formatter class.
"""
ct = self.converter(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
# s = time.strftime(self.default_time_format, ct)
# if self.default_msec_format:
# s = self.default_msec_format % (s, record.msecs)
t = time.time()
nowTime = lambda: int(round(t * 1000))
s = nowTime()
return s
2、配置里注掉 datefmt 这一行
format=%(asctime)s.%(msecs)03d %(name)s %(relativeCreated)d %(levelname)s %(module)s %(funcName)s %(message)s
;datefmt=%Y/%m/%d %H:%M:%S
3、再次执行,日志打印
1628822017676 root 7100 INFO login click_mine_tab uicase2
1628822018704 root 8129 INFO login click_avatar uicase3
1628822020039 root 9463 INFO login click_other_login uicase3
1628822021208 root 10633 INFO login click_phone_number uicase3
1628822021730 root 11154 INFO login click_login_next uicase3
1628822023385 root 12809 INFO login click_password_input uicase3
1628822024184 root 13608 INFO login click_login_next2 uicase4
✅ 不错子✌🏻
以上是关于Pythonlogging日志修改,显示成毫秒级时间戳 -> 1628822017676的主要内容,如果未能解决你的问题,请参考以下文章