[英]How to configure python's logging module to use the formatter for multiline output?
我已将日志记录模块配置为使用以下格式格式化日志消息:
...
'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
您无需配置即可执行此操作。 使用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
中写入Logger
正在写入的类似文件的对象。
(有趣的是logging.Formatter
类的方法formatException
使用默认值traceback.print_exception
。)
我认为你可以使用json模块
import json
a = {"a": 1, "b": 2}
print json.dumps(a, indent=4)
输出:
{
"a": 1,
"b": 2
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.