从异常中获取回溯而不重新引发异常

发布于 2024-12-25 14:05:24 字数 180 浏览 5 评论 0原文

我正在使用 Twister 构建服务器。我还维护服务器错误日志。问题是,如果我让异常在堆栈中一直运行,它会崩溃当前连接并断开用户连接,所以显然我附加了一个裸露的除了以获取其他所有内容。

一旦我捕获到某些内容,有没有办法将回溯作为字符串获取,以便我可以将其存储在某处/自己打印它,而无需引发它并让Python在程序崩溃时为我打印它?

I'm using Twister to build a server. I am also maintaining a server error log. The issue is that if I let an exception run all the way up the stack, it'll crash the current connection and disconnect the user, so obviously I attach a bare except to grab everything else.

Once I've caught something, is there a way to get the traceback as a string so that I can store it somewhere/print it myself without raising it and letting Python print it for me once the program crashes?

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

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

发布评论

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

评论(4

揽清风入怀 2025-01-01 14:05:24

回溯模块包含一些用于打印和检查回溯的辅助函数(例如,traceback.print_tb) - 但重要的是回溯信息本身存储在模块 sys 上的“解释器全局”变量中 - sys.exc_traceback 。

引用自:

http://docs.python.org/reference/compound_stmts.html#try< /a>

在执行 except 子句的套件之前,有关该子句的详细信息
异常被分配给sys模块中的三个变量:
sys.exc_type 接收标识异常的对象;
sys.exc_value 接收异常的参数; sys.exc_traceback
接收一个回溯对象...

您可以将 sys.exc_traceback 对象作为参数传递给traceback.print_tb,以将回溯打印到 except 子句中的标准输出。

The traceback module contains some helper functions for printing and inspecting the traceback (for exameble, traceback.print_tb ) - but the important thing is that the traceback information itself is stored in a "interpreter global" variable - sys.exc_traceback, on the module sys.

Quoting from:

http://docs.python.org/reference/compound_stmts.html#try

Before an except clause’s suite is executed, details about the
exception are assigned to three variables in the sys module:
sys.exc_type receives the object identifying the exception;
sys.exc_value receives the exception’s parameter; sys.exc_traceback
receives a traceback object...

You can pass the sys.exc_traceback object as a parameter to traceback.print_tb to have the traceback printed to stdout within the except clause.

烟酒忠诚 2025-01-01 14:05:24

使用日志记录模块,您可以将回溯记录到文件中:

import logging
logging.basicConfig(level = logging.DEBUG, filename = logfile)
logger = logging.getLogger(__name__)
try:
    1/0
except ZeroDivisionError as err:
    logger.exception(err)

Using the logging module, you could log the traceback to a file:

import logging
logging.basicConfig(level = logging.DEBUG, filename = logfile)
logger = logging.getLogger(__name__)
try:
    1/0
except ZeroDivisionError as err:
    logger.exception(err)
对不⑦ 2025-01-01 14:05:24

试试这个:

import traceback, sys

try:
    # Do something that might raise an exception
    open("/does not exist",'rb')
except:
    traceback.print_exc( file=sys.stderr )
    # Or 
    traceback.print_exc( file=your_open_log_file )

这应该可以解决问题并打印完整的堆栈跟踪。

Try this:

import traceback, sys

try:
    # Do something that might raise an exception
    open("/does not exist",'rb')
except:
    traceback.print_exc( file=sys.stderr )
    # Or 
    traceback.print_exc( file=your_open_log_file )

That should do the trick and print full stack traces too.

情深缘浅 2025-01-01 14:05:24

是的,有一个模块traceback 模块包含打印或格式化异常信息的函数,或者返回原始堆栈帧的函数,以便您可以对它们执行任何您想要的操作。

不过,对于相当复杂的应用程序,我实际上建议使用日志系统而不是普通的旧traceback函数。特别是方法 logging.Logger.exception< /a> 会将有关异常的信息写入您(或软件的用户)配置的任何日志记录目标。默认格式化程序只会打印出回溯,就像 Python 在控制台上一样,但是您可以通过创建 Formatter 并覆盖 format_exception 方法。如果您需要回溯函数来格式化异常输出,则您的重写方法是调用它们的地方。

Yep, there's a module for that. The traceback module contains functions to print or format exception information, or to return the raw stack frames so you can do whatever you want with them.

For a reasonably sophisticated application, though, I would actually recommend using the logging system instead of plain old traceback functions. In particular the method logging.Logger.exception will write information about the exception to whatever logging destination you (or your software's user) has configured. The default formatter will just print out a traceback, as Python would on the console, but you can customize the display of exceptions in your log by creating a Formatter and overriding the format_exception method. Your overridden method is the place to call traceback functions if you need them to format the exception output.

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