Python 自开始以来的记录时间(以秒为单位)

Python logging time since start in seconds

我想添加我的程序达到日志输出的秒数。

我找到了 relativeCreated here 但它会给我毫秒数,例如这个:

logging.basicConfig(format='{relativeCreated:8.0f}ms {levelname:s} {message:s}', style="{")

结果

4081ms INFO my message
6012ms INFO another message

但我希望 运行 时间在小时内,我更愿意。

4s INFO my message
6s INFO another message

我试过了

logging.basicConfig(format='{relativeCreated / 1000:4.0f}s {levelname:s} {message:s}', style="{")

但这会导致

KeyError: 'relativeCreated / 1000'

试试这个:

import time

start_time = time.time()
........
print (str(time.time() - start_time) + ' INFO my message') 

它应该 return 时间 [s]

您可以继承 logging.Formatter 来修改 relativeCreated:

import logging
import time

class RelativeSeconds(logging.Formatter):
    def format(self, record):
        record.relativeCreated = record.relativeCreated // 1000
        return super().format(record)

formatter = RelativeSeconds("%(relativeCreated)ds %(levelname)s %(message)s")

logging.basicConfig()
logging.root.handlers[0].setFormatter(formatter)

logging.error("Test 1")
time.sleep(2)
logging.error("Test 2")

打印:

0s ERROR Test 1
2s ERROR Test 2