在Python中配置日志记录

时间:2013-09-05 13:14:57

标签: python python-2.7 logging

我有一个关于如何配置我的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

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:5)

将您的代码包裹在try:except Exception:块中并致电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()函数是上面的例子,不包括在内。