【发布时间】:2023-01-13 14:55:06
【问题描述】:
我使用 logging 模块(logger.info、logger.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