【问题标题】:Configure logging in Python在 Python 中配置日志记录
【发布时间】:2013-09-05 13:14:57
【问题描述】:

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

非常感谢您的帮助。

【问题讨论】:

    标签: python python-2.7 logging


    【解决方案1】:

    将您的代码包装在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()函数是上面的例子不包括在内。

    【讨论】:

    • 我认为这不是我想要的,因为我没有得到任何提示,这个错误真的是。在我的原始代码中,控制台中的错误消息太长,无法完全看到,所以我认为这不是我想要的。
    • @swot:完整的回溯记录到您的日志文件中。我的示例异常很短,是什么让您认为这是截断的回溯?
    • 实际上,如果我有 def somefunction(): print a 我没有在我的日志文件中获得完整的回溯。有什么建议吗?
    • @swot:你在哪里发现了异常?在程序的入口点或somefunction()? 内部
    • create logger &lt;/br&gt; somefuntion() &lt;/br&gt; try:somefunction &lt;/br&gt; except Exception: &lt;/br&gt; logger.exception("oops) 这是我设置的方式。这有帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2011-04-27
    • 1970-01-01
    • 2018-07-02
    • 2013-09-11
    • 1970-01-01
    相关资源
    最近更新 更多