如何记录Python异常?

发布于 2024-10-08 11:34:47 字数 332 浏览 0 评论 0 原文

如何在 Python 中记录异常?

我查看了一些选项,发现我可以使用以下代码访问实际的异常详细信息:

import sys
import traceback

try:
    1/0
except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    traceback.print_exception(exc_type, exc_value, exc_traceback)

我想以某种方式将字符串 print_exception() 抛出到标准输出,以便我可以记录它。

How can I log an exception in Python?

I've looked at some options and found out I can access the actual exception details using this code:

import sys
import traceback

try:
    1/0
except:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    traceback.print_exception(exc_type, exc_value, exc_traceback)

I would like to somehow get the string print_exception() throws to stdout so that I can log it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

澉约 2024-10-15 11:34:47

看一下 logging.exception (Python 日志模块)

import logging 
def foo():
    try:
        some_code()
    except:
        logging.exception('')

这应该自动处理获取当前异常的回溯并正确记录它。

Take a look at logging.exception (Python Logging Module)

import logging 
def foo():
    try:
        some_code()
    except:
        logging.exception('')

This should automatically take care of getting the traceback for the current exception and logging it properly.

半山落雨半山空 2024-10-15 11:34:47

在 Python 3.5 中,您可以在 exc_info 参数中传递异常实例:

import logging
try:
    1/0
except Exception as e:
   logging.error('Error at %s', 'division', exc_info=e)

In Python 3.5 you can pass exception instance in exc_info argument:

import logging
try:
    1/0
except Exception as e:
   logging.error('Error at %s', 'division', exc_info=e)
孤独岁月 2024-10-15 11:34:47

要回答您的问题,您可以使用 print_exception() 的字符串版本="noreferrer">traceback.format_exception() 函数。它将回溯消息作为字符串列表返回,而不是将其打印到标准输出,因此您可以用它做您想做的事情。例如:

import sys
import traceback

try:
    asdf
except NameError:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
    print ''.join('!! ' + line for line in lines)  # Log it or whatever here

这显示:

!! Traceback (most recent call last):
!!   File "<stdin>", line 2, in <module>
!! NameError: name 'asdf' is not defined

但是,我绝对建议使用标准 Python 日志记录模块,如 rlotun 所建议的。这不是最容易设置的事情,但它是非常可定制的。

To answer your question, you can get the string version of print_exception() using the traceback.format_exception() function. It returns the traceback message as a list of strings rather than printing it to stdout, so you can do what you want with it. For example:

import sys
import traceback

try:
    asdf
except NameError:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
    print ''.join('!! ' + line for line in lines)  # Log it or whatever here

This displays:

!! Traceback (most recent call last):
!!   File "<stdin>", line 2, in <module>
!! NameError: name 'asdf' is not defined

However, I'd definitely recommend using the standard Python logging module, as suggested by rlotun. It's not the easiest thing to set up, but it's very customizable.

泪之魂 2024-10-15 11:34:47

记录异常就像将 exc_info=True 关键字参数添加到任何日志消息中一样简单,请参阅 http://docs.python.org/2/library/logging.html

示例:

try: 
    raise Exception('lala')
except Exception:
    logging.info('blah', exc_info=True)

输出(当然,取决于您的日志处理程序配置):

2012-11-29 10:18:12,778 - root - INFO - <ipython-input-27-5af852892344> : 3 - blah
Traceback (most recent call last):
  File "<ipython-input-27-5af852892344>", line 1, in <module>
    try: raise Exception('lala')
Exception: lala

Logging exceptions is as simple as adding the exc_info=True keyword argument to any log message, see entry for Logger.debug in http://docs.python.org/2/library/logging.html.

Example:

try: 
    raise Exception('lala')
except Exception:
    logging.info('blah', exc_info=True)

output (depending, of course, on your log handler config):

2012-11-29 10:18:12,778 - root - INFO - <ipython-input-27-5af852892344> : 3 - blah
Traceback (most recent call last):
  File "<ipython-input-27-5af852892344>", line 1, in <module>
    try: raise Exception('lala')
Exception: lala
征﹌骨岁月お 2024-10-15 11:34:47

首先,考虑在 except 子句中使用正确的异常类型。
然后,命名异常,您可以打印它:

try:
    1/0
except Exception as e:
    print e

根据您的 Python 版本,您必须使用

except Exception, e

First of all, consider using a proper Exception type on your except clause.
Then, naming the exception, you can print it:

try:
    1/0
except Exception as e:
    print e

Dependending on your Python version, you must use

except Exception, e
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文