Home / Python logging / Chapter 5

Chapter 5: Handler Formatter

Aug 22, 2024
5 of 11

A handler’s output can customized by setting a Formatter. A formatter can be created by adding a formatting string to logging.Formatter. This can contain normal text and predefined fields, such as time and loglevel.

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

You can also create a fully custom formatter by extending the logging.Formatter class and implementing the format method. This allows you to do whatever you want, such as logging as json.

class JsonFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        return json.dumps({
            "time": record.asctime,
            "name": record.name,
            "level": record.levelname,
            "message": record.getMessage(),
        })

handler.setFormatter(JsonFormatter())