我正在用logging.error将Python异常消息打印到日志文件:
import logging
try:
1/0
except ZeroDivisionError as e:
logging.error(e) # ERROR:root:division by zero
是否可以打印有关异常和生成异常的代码的更详细信息,而不仅仅是异常字符串?行号或堆栈跟踪之类的东西会很棒。
我正在用logging.error将Python异常消息打印到日志文件:
import logging
try:
1/0
except ZeroDivisionError as e:
logging.error(e) # ERROR:root:division by zero
是否可以打印有关异常和生成异常的代码的更详细信息,而不仅仅是异常字符串?行号或堆栈跟踪之类的东西会很棒。
当前回答
如果“调试信息”意味着异常引发时的值,那么logging.exception(…)将不起作用。因此,您需要一个工具来自动记录所有变量值和回溯行。
在盒子外面你会得到log
2020-03-30 18:24:31 main ERROR File "./temp.py", line 13, in get_ratio
2020-03-30 18:24:31 main ERROR return height / width
2020-03-30 18:24:31 main ERROR height = 300
2020-03-30 18:24:31 main ERROR width = 0
2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero
看看一些pypi工具,我命名为:
tbvaccine traceback-with-variables better-exceptions
其中一些会给你很严重的崩溃信息:
但你可能会在pypi上找到更多
其他回答
如果“调试信息”意味着异常引发时的值,那么logging.exception(…)将不起作用。因此,您需要一个工具来自动记录所有变量值和回溯行。
在盒子外面你会得到log
2020-03-30 18:24:31 main ERROR File "./temp.py", line 13, in get_ratio
2020-03-30 18:24:31 main ERROR return height / width
2020-03-30 18:24:31 main ERROR height = 300
2020-03-30 18:24:31 main ERROR width = 0
2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero
看看一些pypi工具,我命名为:
tbvaccine traceback-with-variables better-exceptions
其中一些会给你很严重的崩溃信息:
但你可能会在pypi上找到更多
一个干净的方法是使用format_exc(),然后解析输出以获得相关部分:
from traceback import format_exc
try:
1/0
except Exception:
print 'the relevant part is: '+format_exc().split('\n')[-2]
问候
日志记录有一个好处。SiggyF的答案没有显示的异常是,你可以传递一个任意的消息,日志仍然会显示所有异常细节的完整跟踪:
import logging
try:
1/0
except ZeroDivisionError:
logging.exception("Deliberate divide by zero traceback")
默认情况下(在最近的版本中)只是将错误打印到sys. log行为。Stderr,它看起来像这样:
>>> import logging
>>> try:
... 1/0
... except ZeroDivisionError:
... logging.exception("Deliberate divide by zero traceback")
...
ERROR:root:Deliberate divide by zero traceback
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
如果你可以处理额外的依赖,那么使用twisted.log,你不必显式地记录错误,而且它还会返回整个回溯和时间到文件或流。
您可以记录堆栈跟踪而不出现异常。
https://docs.python.org/3/library/logging.html#logging.Logger.debug
The second optional keyword argument is stack_info, which defaults to False. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying exc_info: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.
例子:
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> logging.getLogger().info('This prints the stack', stack_info=True)
INFO:root:This prints the stack
Stack (most recent call last):
File "<stdin>", line 1, in <module>
>>>