当我想记录一些特定的异常,但忽略它时,我可以这样做:
import logging
logger = logging.getLogger(__name__)
try:
something_that_may_fail()
except NameError:
logger.error("It failed with:", exc_info=True)
(这实际上是一个 MRE ,因为 something_that_may_fail
还没有被定义,所以 try
块将引发 NameError
和消息 name 'something_that_may_fail' is not defined
。😉)然而,这也会记录堆栈跟踪:
It failed with:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'something_that_may_fail' is not defined
有时这不是我想要的:在某些情况下,我已经知道异常类型和异常消息(连同我的自定义日志消息)就足够了,并且不想用不知道的堆栈跟踪扩展日志我有什么新东西。所以我想要一个简单的日志条目It failed with:
NameError: name 'something_that_may_fail' is not defined
我可以通过传递一个三元组作为 exc_info
来实现这一点。 , 堆栈跟踪组件由 None
替换:import logging
import sys
logger = logging.getLogger(__name__)
try:
something_that_may_fail()
except NameError:
exc_type, exc_value, _trace = sys.exc_info()
logger.error("It failed with:", exc_info=(exc_type, exc_value, None))
但我不确定这有多可靠。 ( The documentation 没有提到元组可能会或可能不会偏离 sys.exc_info()
返回的元组。)自己检查异常
...
except NameError as e:
...
有其自身的问题:f"{type(e)}"
给出字符串 <class 'NameError'>
而不仅仅是字符串 NameError
builtin.
相当笨重,而不是我想要的异常处理代码。见 the currently accepted answer至 Get fully qualified class name of an object in Python . e.args[0]
? (除了 NameError
之外,我可能还用于其他异常(具有更多子类型),我在此处仅将其用作示例。) 那么在没有堆栈跟踪的情况下记录异常类型和消息的正确方法是什么?有没有比我的跟踪更清洁的方法-
None
上面的黑客?
最佳答案
traceback.format_exception_only
可以用于:
import logging
import sys
import traceback
logger = logging.getLogger(__name__)
try:
something_that_may_fail()
except NameError:
exc_type, exc_value, _trace = sys.exc_info()
exc_desc_lines = traceback.format_exception_only(exc_type, exc_value)
exc_desc = ''.join(exc_desc_lines).rstrip()
logger.error(f"It failed with:\n{exc_desc}")
或没有 sys
:import logging
import traceback
logger = logging.getLogger(__name__)
try:
something_that_may_fail()
except NameError as e:
exc_desc_lines = traceback.format_exception_only(type(e), e)
exc_desc = ''.join(exc_desc_lines).rstrip()
logger.error(f"It failed with:\n{exc_desc}")
(通过查看 how the logging
module actually extracts and formats information from exc_info
找到了这个。有 traceback.print_exception
is being used ,所以我查看了 traceback
模块中还有什么可用的。)
关于python - 如何记录 Python 3 异常,但没有其堆栈跟踪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68532872/