Pretty print logging in Python


Posted:

From the Python logging documentation, we can send an arbitrary object into a log message call.

import pprint

class PrettyLog():
    def __init__(self, obj):
        self.obj = obj
    def __repr__(self):
        return pprint.pformat(self.obj)

Then, in the code, we can use it with logging.

import logging

# ...

logging.debug(PrettyLog(obj))

The string isn't created until it is needed, so if the logging level is not high enough, the only method call is the creation of the PrettyLog object.