使用日志打印pprint的输出

时间:2022-10-09 18:05:28

I want to use pprint's output to show a complex data structure, but I would like to output it using the logging module rather than stdout.

我想使用pprint的输出来显示一个复杂的数据结构,但是我想使用日志模块而不是stdout输出它。

ds = [{'hello': 'there'}]
logging.debug( pprint.pprint(ds) ) # outputs as STDOUT

2 个解决方案

#1


111  

Use pprint.pformat to get a string, and then send it to your logging framework.

使用pprint。pformat获取一个字符串,然后将其发送到日志框架。

from pprint import pprint, pformat
ds = [{'hello': 'there'}]
logging.debug(pformat(ds))

#2


9  

The solution above didn't quite cut it for me because I'm also using a formatter to add name and levelname when logging. It looks a little untidy:

上面的解决方案对我来说并不是很好,因为我还在使用格式化程序在日志记录时添加名称和级别。看起来有点不整洁:

__main__    : DEBUG   : ['aaaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbb',
'cccccccccccccccccccc',
'dddddddddddddddddddd']
__main__    : DEBUG   : Some other logging text

There may be a more elegant solution, but this:

或许有一个更优雅的解决方案,但以下是:

for line in pprint.pformat(ds).split('\n'):
    logging.debug(line)

produces something a little nicer:

做一些更好的事情:

__main__    : DEBUG   : ['aaaaaaaaaaaaaaaaaaaa',
__main__    : DEBUG   :  'bbbbbbbbbbbbbbbbbbbb',
__main__    : DEBUG   :  'cccccccccccccccccccc',
__main__    : DEBUG   :  'dddddddddddddddddddd']
__main__    : DEBUG   : Some other logging text

#1


111  

Use pprint.pformat to get a string, and then send it to your logging framework.

使用pprint。pformat获取一个字符串,然后将其发送到日志框架。

from pprint import pprint, pformat
ds = [{'hello': 'there'}]
logging.debug(pformat(ds))

#2


9  

The solution above didn't quite cut it for me because I'm also using a formatter to add name and levelname when logging. It looks a little untidy:

上面的解决方案对我来说并不是很好,因为我还在使用格式化程序在日志记录时添加名称和级别。看起来有点不整洁:

__main__    : DEBUG   : ['aaaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbb',
'cccccccccccccccccccc',
'dddddddddddddddddddd']
__main__    : DEBUG   : Some other logging text

There may be a more elegant solution, but this:

或许有一个更优雅的解决方案,但以下是:

for line in pprint.pformat(ds).split('\n'):
    logging.debug(line)

produces something a little nicer:

做一些更好的事情:

__main__    : DEBUG   : ['aaaaaaaaaaaaaaaaaaaa',
__main__    : DEBUG   :  'bbbbbbbbbbbbbbbbbbbb',
__main__    : DEBUG   :  'cccccccccccccccccccc',
__main__    : DEBUG   :  'dddddddddddddddddddd']
__main__    : DEBUG   : Some other logging text