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