如何配置python的日志记录模块以使用格式化程序进行多行输出?

时间:2014-02-12 14:27:51

标签: python

我已将日志记录模块配置为使用以下内容格式化日志消息:

...
    'formatters': {
        'verbose': {
            'format': '%(asctime)s [%(levelname)s] '
                      '(%(name)s:pid=%(process)d) %(module)s(%(lineno)d): '
                      '%(message)s'
        },
    },
...

但是,当它打印异常时,它会显示如下:

2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105): Catchall exception at top level.
Traceback (most recent call last):
  File "build/bdist.linux-x86_64/egg/argh/dispatching.py", line 228, in dispatch_command
    dispatch(parser, *args, **kwargs)
  File "build/bdist.linux-x86_64/egg/argh/dispatching.py", line 124, in dispatch
    for line in lines:
  File "build/bdist.linux-x86_64/egg/argh/dispatching.py", line 200, in _execute_command
    for line in result:
  ...,
NameError: global name 'sftp' is not defined

是否可以通过格式化程序运行每一行?例如。所以它会输出类似的东西:

2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105): Catchall exception at top level.
2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105): Traceback (most recent call last):
2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105):   File "build/bdist.linux-x86_64/egg/argh/dispatching.py", line 228, in dispatch_command
2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105):     dispatch(parser, *args, **kwargs)
2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105):   File "build/bdist.linux-x86_64/egg/argh/dispatching.py", line 124, in dispatch
2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105):     for line in lines:
2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105):   File "build/bdist.linux-x86_64/egg/argh/dispatching.py", line 200, in _execute_command
2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105):     for line in result:
2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105):   ...,
2014-02-12 14:16:20,454 [ERROR] (app:pid=1930) main(105): NameError: global name 'sftp' is not defined

2 个答案:

答案 0 :(得分:0)

您无需配置即可完成此操作。使用traceback.format_exec将堆栈跟踪作为字符串,然后拆分行并单独记录每一行。

import logging
import traceback

logger = logging.Logger(__name__) # or whatever namespace you so please
# do any other Logger configuration you want

try:
    do_some_stuff()
except Exception as e:
    for line in traceback.format_exec().split('\n'):
        logger.error(line)

然而,这不是常见的做法。如果您使用Logger.exception(),则可以记录异常。它将在一个日志记录行上,但它将在多行上写入Logger正在写入的类文件对象。

(值得关注的是,logging.Formatter类'方法formatException使用traceback.print_exception作为其默认实现。)

答案 1 :(得分:-3)

我认为你可以使用json模块

import json

a = {"a": 1, "b": 2}

print json.dumps(a, indent=4)

输出:

{
    "a": 1, 
    "b": 2
}