pythonloggingpython-loggingpprint

Use logging print the output of pprint


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.

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

Solution

  • 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))