0

我有一个关于如何配置我的 python 记录器的问题。您可以在下面看到我当前的记录器设置。(http://docs.python.org/2/howto/logging-cookbook.html

logger = logging.getLogger("someName")
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("./log/log.out", "w")
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stderr)
ch.setLevel(logging.ERROR)

frm = logging.Formatter('%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s','H:%M:%S')
fh.setFormatter(frm)
ch.setFormatter(frm)
logger.addHandler(fh)
logger.addHandler(ch)

有没有一种方法可以配置记录器,使其也写入如下错误消息:

print a
>>> NameError: global name 'a' is not defined

非常感谢你的帮助。

4

1 回答 1

5

将您的代码包装在 a try:except Exception:block 和 call中logger.exception()

try:
    print a
except Exception:
    logger.exception('Oops, something went wrong')

您可以向其中添加一条raise语句以重新引发捕获的异常。

演示:

>>> import logging
>>> logging.basicConfig()
>>> logger = logging.getLogger()
>>> def foo():
...     print a
... 
>>> def bar(i=0):
...     if i < 3:
...         bar(i + 1)
...     else:
...         foo()
... 
>>> def baz():
...     try:
...         bar()
...     except Exception:
...        logger.exception('Oops, something went wrong')
... 
>>> def spam(): baz()
... 
>>> spam()
ERROR:root:Oops, something went wrong
Traceback (most recent call last):
  File "<stdin>", line 3, in baz
  File "<stdin>", line 3, in bar
  File "<stdin>", line 3, in bar
  File "<stdin>", line 3, in bar
  File "<stdin>", line 5, in bar
  File "<stdin>", line 2, in foo
NameError: global name 'a' is not defined

回溯是由logging模块记录的,而不是由我的交互式 Python 会话记录的。

回溯从try块到异常;功能是上面的spam()例子不包括在内。

于 2013-09-05T13:16:18.943 回答