[英]Configure logging in Python
我對如何配置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
非常感謝你的幫助。
將代碼包裝在try:
, except Exception:
塊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
模塊logging
,而不是由我的交互式Python會話記錄的。
追溯從try
塊引向異常; spam()
函數是上面的示例,不包括在內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.