如何通过logging模块而不是通过模块输出未捕获的异常stderr?
我意识到这样做的最好方法是:
try:
raise Exception, 'Throwing a boring exception'
except Exception, e:
logging.exception(e)
Run Code Online (Sandbox Code Playgroud)
但是我的情况是如果在没有捕获到异常的情况下自动调用它会非常好logging.exception(...).
在我的所有 Python 主脚本和模块中,我一直在尝试实现一种方法,将未捕获的异常记录到引发异常的模块的记录器中。我在所有文件中都以相同的方式执行此操作:
def log_unhandled_exception(*exc_info):
text = "".join(traceback.format_exception(*exc_info))
logger.critical("An unhandled exception has caused this script to terminate prematurely. Here are the details: {0}".format(text))
sys.exit(2)
def some_function():
# ...
sys.excepthook = log_unhandled_exception
logger = logging.getLogger("Module1") # or "Module2", "Module3", etc., each module has it's own logger
Run Code Online (Sandbox Code Playgroud)
当我遇到未捕获的异常时,有时我无法获得预期的记录器。我认为这与我导入模块的顺序有关:如果我导入 module1 然后导入 module2,然后调用 module2 中的函数并遇到异常,似乎我得到了 module1 的记录器。相反,如果我颠倒导入顺序(module2 在 module1 之前),并且尝试相同的测试(在 module2 中抛出异常),我会正确获取 module2 的记录器。我本以为 LATER 导入会优先(覆盖前者的 sys.excepthook 引用),但没有。
我能够通过在每个模块中为每个记录器引用提供唯一的名称来解决这个问题(我猜......)。因此,要修改上面的代码,此模式的工作原理与模块导入的顺序无关:
def log_unhandled_exception(*exc_info):
text = "".join(traceback.format_exception(*exc_info))
module1_logger.critical("An unhandled exception has caused this script to terminate prematurely. …Run Code Online (Sandbox Code Playgroud) 在我的Tkinter Python应用程序中,我试图用来sys.excepthook处理未捕获的异常,但我的处理程序从未被调用过.堆栈跟踪仍然打印出来.
如何在Tkinter应用程序中处理未捕获的异常?
这是一个简单的例子,展示了我的尝试:
import Tkinter as tk
import tkMessageBox
import traceback
import sys
class MyApp(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.button_frame = tk.Frame(self)
self.button_frame.pack(side='top')
self.button_run = tk.Button(
self.button_frame, text="Run", command=self.run
)
self.button_run.grid(row=0, column=1, sticky='W')
def run(self):
tkMessageBox.showinfo('Info', 'The process is running.')
raise RuntimeError('Tripped.')
def main():
root = tk.Tk() # parent widget
MyApp(root).pack(fill='both', expand=True)
def handle_exception(exc_type, exc_value, exc_traceback):
message = ''.join(traceback.format_exception(exc_type,
exc_value,
exc_traceback))
tkMessageBox.showerror('Error', message)
sys.excepthook = handle_exception
root.mainloop() # enter …Run Code Online (Sandbox Code Playgroud)