0

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

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

代码示例

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 中所需的堆栈跟踪部分,我已经替换了堆栈跟踪中方法参数的评估值。

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

4

1 回答 1

0

您可能不应该使用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!

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

于 2019-01-04T00:22:05.577 回答