如何更改python日志记录以显示脚本执行开始后经过的时间? [英] How change python logging to display time passed from when the script execution started?

查看:40
本文介绍了如何更改python日志记录以显示脚本执行开始后经过的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修改python日志记录以记录从脚本启动(或日志记录模块初始化)开始所经过的时间.

I want to modify the python logging to log the time elapsed from when the script started (or when the logging module was initialized).

000:00 DEBUG bla bla
000:01 ERROR wow! ... this is measured in minutes:seconds

我在日志记录模块中找到了 relativeCreated 变量,但这使我获得了毫秒级的精度,这只会向日志发送垃圾邮件,从而更难以查看时间流逝或运行日志的方式.

I found the relativeCreated variable in the logging module, but this is givving me millisecond accuracy which would only spam the logs, making harder to see where the time goes or how log it took to run.

我该怎么做?

推荐答案

您可以使用 logging.Formatter 子类,该子类从 LogRecord 传递给其 format 方法,将其格式化为mins:secs并以格式字符串输出,例如在格式字符串中使用其他占位符,例如%(adjustedTime)s :

You can use a logging.Formatter subclass which gets the relativeCreated from the LogRecord passed to its format method, format it as mins:secs and output it in the format string e.g. using a different placeholder in the format string, such as %(adjustedTime)s:

class MyFormatter(logging.Formatter):
    def format(self, record):
        record.adjustedTime = format_as_mins_and_secs(record.relativeCreated)
        return super(MyFormatter, self).format(record)

您可以在其中定义 format_as_mins_and_secs 以返回格式化的相对时间.

where you can define format_as_mins_and_secs to return the formatted relative time.

这篇关于如何更改python日志记录以显示脚本执行开始后经过的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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