yee*_*379 84 python logging pprint
我想使用pprint的输出来显示复杂的数据结构,但我想使用日志模块而不是stdout输出它.
ds = [{'hello': 'there'}]
logging.debug( pprint.pprint(ds) ) # outputs as STDOUT
Run Code Online (Sandbox Code Playgroud)
rob*_*ert 177
使用pprint.pformat
得到一个字符串,然后将其发送到您的日志框架.
from pprint import pformat
ds = [{'hello': 'there'}]
logging.debug(pformat(ds))
Run Code Online (Sandbox Code Playgroud)
小智 16
上面的解决方案并没有完全消除它,因为我还使用格式化程序在记录时添加名称和级别名称.它看起来有点凌乱:
__main__ : DEBUG : ['aaaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbb',
'cccccccccccccccccccc',
'dddddddddddddddddddd']
__main__ : DEBUG : Some other logging text
Run Code Online (Sandbox Code Playgroud)
可能有一个更优雅的解决方案,但这个:
for line in pprint.pformat(ds).split('\n'):
logging.debug(line)
Run Code Online (Sandbox Code Playgroud)
产生一些更好的东西:
__main__ : DEBUG : ['aaaaaaaaaaaaaaaaaaaa',
__main__ : DEBUG : 'bbbbbbbbbbbbbbbbbbbb',
__main__ : DEBUG : 'cccccccccccccccccccc',
__main__ : DEBUG : 'dddddddddddddddddddd']
__main__ : DEBUG : Some other logging text
Run Code Online (Sandbox Code Playgroud)
Bri*_*lie 11
json.dumps
另一种方法是与arg 一起使用indent
。在某些情况下(取决于日志记录格式、数据大小等),它可能会为您提供更好的输出。
logging.error('Malformed input data!')
logging.error(pformat(foo))
ERROR:root:Malformed input data!
ERROR:root:{'a': 1, 'b': 2, 'c': 'womp rat', 'd': 'turd sandwich'}
Run Code Online (Sandbox Code Playgroud)
与
logging.error('Malformed input data!')
logging.error(json.dumps(foo, indent=4))
ERROR:root:Malformed input data!
ERROR:root:{
"a": 1,
"b": 2,
"c": "womp rat",
"d": "turd sandwich"
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28943 次 |
最近记录: |