在Python中使用异常堆栈跟踪日志记录以及方法参数的实际值调用

时间:2019-01-03 11:48:05

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

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

要阐明我的要求,请参阅以下示例:

代码示例

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

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

1 个答案:

答案 0 :(得分: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!

如果需要这些值,则必须与异常分开记录日志,并且在发生异常之前,此信息将丢失。