python - 如何记录 Python 3 异常,但没有其堆栈跟踪?

标签 python python-3.x exception

当我想记录一些特定的异常,但忽略它时,我可以这样做:

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 answerGet 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/

    相关文章:

    python - 以减少的权限运行 python 脚本

    python - 正则表达式以匹配以文本格式编写的年龄

    python-3.x - 如何根据 Excel Dataframe 中的内容突出显示行?

    python - 有没有办法将 pptx-python 与 python 3.7 版本一起使用并使用 pyinstaller 生成 exe?

    Java递归和异常

    java - Android:相同的代码行无法在单独的方法中工作

    python - 如何将代表天数的单个整数转换为 pandas datetime

    python - 对导出到excel的字典进行排序?

    python - 如何解决django中的循环导入错误?

    c# - C# WinForm static void Main 不能捕获异常吗?