使用python的日志模块记录所有异常和错误 [英] Using python's logging module to log all exceptions and errors

查看:26
本文介绍了使用python的日志模块记录所有异常和错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查特定后台文件中的错误,但标准错误流由前台程序控制,问题中文件中的错误未显示.不过,我可以使用 logging 模块并将输出写入文件.我想知道如何使用它来记录所有异常、错误及其回溯.

I want to check for errors in a particular background file, but the standard error stream is being controlled by the program in the foreground and the errors in the file in the question are not being displayed. I can use the logging module and write output to a file, though. I was wondering how I can use this to log all exceptions, errors and their tracebacks.

推荐答案

记录程序中抛出的任何异常可能是个坏主意,因为 Python 也将异常用于正常的控制流.

It's probably a bad idea to log any exception thrown within the program, since Python uses exceptions also for normal control flow.

>

因此,您应该只记录未捕获的异常.您可以使用记录器的 exception() 方法,一旦你有一个异常对象.

Therefore you should only log uncaught exceptions. You can easily do this using a logger's exception() method, once you have an exception object.

要处理所有未捕获的异常,您可以将脚本的入口点包装在 try...except 块中,或者通过重新分配 sys.excepthook():

To handle all uncaught exceptions, you can either wrap your script's entry point in a try...except block, or by installing a custom exception handler by re-assigning sys.excepthook():

import logging
import sys

logger = logging.getLogger('mylogger')
# Configure logger to write to a file...

def my_handler(type, value, tb):
    logger.exception("Uncaught exception: {0}".format(str(value)))

# Install exception handler
sys.excepthook = my_handler

# Run your main script here:
if __name__ == '__main__':
    main()

这篇关于使用python的日志模块记录所有异常和错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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