簡體   English   中英

在Python中配置日志記錄

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM