Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use logging print the output of pprint

People also ask

What is the use of Pprint in Python?

The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable.

How do I print a logger from the console?

Use logging Module to Print Log Message to a File in Python getLogger(name) method. There is a convention to use __name__ variable as the name of the logger. Once we have created a new logger, we should remember to log all our messages using the new logger.info() instead of the root's logging.info() method.


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

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

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