我想修改python日志记录以记录脚本启动时(或初始化日志记录模块时)所经过的时间。
000:00 DEBUG bla bla
000:01 ERROR wow! ... this is measured in minutes:seconds
我在日志记录模块中找到了relativeCreated
变量,但是这给我的毫秒级准确性只会使日志垃圾邮件变得更加困难,因此更难以查看时间到达的位置或运行日志的时间。
我该怎么做?
答案 0 :(得分:7)
您可以使用logging.Formatter
子类从relativeCreated
传递给LogRecord
方法获取format
,将其格式化为mins:secs并以格式输出字符串例如在格式字符串中使用其他占位符,例如%(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
以返回格式化的相对时间。
答案 1 :(得分:-1)
我不确定你是否可以使用logging
python模块执行此操作(我可能错了)。
但是,如果您需要应用程序的运行时,我会说您应该在应用程序启动时捕获变量中的时间(使用time
模块)。一旦捕获了时间,您就可以将该变量传递给记录器,以便在遇到错误时计算差异。
答案 2 :(得分:-1)
首先出现在我脑海中。
我现在没有提供任何代码来激励您阅读有关所提及模块的更多信息。