【问题标题】:Log stderr to file, prefixed with datetime将 stderr 记录到文件,以日期时间为前缀
【发布时间】:2023-01-13 14:55:06
【问题描述】:

我使用 logging 模块(logger.infologger.debug...)进行正确的日志记录,并将其写入文件。

但在某些极端情况下(外部模块、未捕获的异常等),我有时仍然会向stderr写入错误。

我将其记录到一个文件中:

import sys
sys.stdout, sys.stderr = open("stdout.log", "a+", buffering=1), open("stderr.log", "a+", buffering=1)
print("hello")
1/0

它有效,但如何在每个错误之前记录日期时间?

注意:我想避免在这部分使用logging,而是使用更低级别的东西。

我也想避免这种解决方案:

def exc_handler(ex_cls, ex, tb):
    with open('mylog.log', 'a') as f:
        dt = time.strftime('%Y-%m-%d %H:%M:%S')
        f.write(f"{dt}\n")
        traceback.print_tb(tb, file=f)
        f.write(f"{dt}\n")

sys.excepthook = exc_handler

因为一些外部模块可能会覆盖它。是否有像重写sys.stderr.print这样的低级解决方案?

【问题讨论】:

    标签: python windows logging stderr


    【解决方案1】:

    您可以使用 this cookbook recipe 中描述的方法将记录器视为输出流,然后重定向 sys.std{out,err} 以记录写入它们的内容。然后,当然,您可以配置日志记录以使用您想要的任何格式,包括日期时间前缀,以正常方式使用例如%(asctime)s 格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2018-05-08
      相关资源
      最近更新 更多