【问题标题】:Exception stack trace logging along with method arguments' actual values calls in Python异常堆栈跟踪记录以及 Python 中方法参数的实际值调用
【发布时间】:2019-01-03 11:48:04
【问题描述】:

我需要知道如何记录异常堆栈跟踪以及方法参数的实际值。

为了澄清我的要求,请参考以下示例:

代码示例

import logging
def a(str, str2):
    print str + str2
    raise Exception("Custom err ==> " + str + "----" + str2)
def b(str):
    a(str, "World!")
def c(str):
    b(str)
try:
    val = 'Hello' #Let's say this value is coming from DB
    c(val)
except:
    logging.exception("err", exc_info=True)

Python 中的实际堆栈跟踪

HelloWorld!
ERROR:root:err
Traceback (most recent call last):
  File "except.py", line 14, in <module>
    c('Hello')
  File "except.py", line 11, in c
    b(str)
  File "except.py", line 8, in b
    a(str, "World!")
  File "except.py", line 5, in a
    raise Exception("Custom err ==> " + str + "----" + str2)
Exception: Custom err ==> Hello----World!

Python 中所需的堆栈跟踪

HelloWorld!
ERROR:root:err
Traceback (most recent call last):
  File "except.py", line 14, in <module>
    c('Hello')
  File "except.py", line 11, in c
    b('Hello')
  File "except.py", line 8, in b
    a('Hello', "World!")
  File "except.py", line 5, in a
    raise Exception("Custom err ==> " + str + "----" + str2)
Exception: Custom err ==> Hello----World!

如果您仔细查看 Python 中所需的堆栈跟踪部分,我已经替换了堆栈跟踪中方法参数的评估值。

我希望这个例子能清楚地说明我的要求

【问题讨论】:

    标签: python python-2.7 exception-handling error-logging python-logging


    【解决方案1】:

    您可能不应该使用 str 作为名称,但这不是重点。

    你不能有你的愿望 - 日志模块不打印值它打印用作参数的名称。查看更改的程序(大多数变量名称已更改):

    import logging
    def a(var_name_in_a, var_name_in_a_2):
        print var_name_in_a + var_name_in_a_2
        raise Exception("Custom err ==> " + var_name_in_a + "----" + var_name_in_a_2)
    def b(var_name_in_b):
        a(var_name_in_b, "World!")
    def c(var_name):
        b(var_name)
    try:
        val = 'Hello' #Let's say this value is coming from DB
        c(val)
    except:
        logging.exception("stdout", exc_info=True)
    

    及其输出:

    HelloWorld!
    ERROR:root:err
    Traceback (most recent call last):
      File "test.py", line 11, in <module>
        c(val)
      File "test.py", line 8, in c
        b(var_name)
      File "test.py", line 6, in b
        a(var_name_in_b, "World!")
      File "test.py", line 4, in a
        raise Exception("Custom err ==> " + var_name_in_a + "----" + var_name_in_a_2)
    Exception: Custom err ==> Hello----World!
    

    如果您想要这些值,则必须将它们与异常分开记录 - 并且在它发生之前 - 之后此信息会丢失。

    【讨论】:

    • 抱歉回复晚了。很遗憾,我通常在第一级调试中使用异常堆栈跟踪。在 PHP 中,我可以看到哪些值作为参数传递给函数调用。这让我清楚地了解了首先出了什么问题。我希望 python 也包括类似的异常日志记录
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多