Daniel Díez
Daniel Díez

Reputation: 143

Formatting the message in Python logging

I would like to understand if it's possible and how is it possible, to modify the message part of a log message, using the Python logging module.

So basically, you can format a complete log as:

format = '{"timestamp": "%(asctime)s", "logger_level": "%(levelname)s", "log_message": %(message)s}'

However, I would like to make sure the message part is always in json format. Is there any way I can modify the format of only the message part, maybe with a custom logging.Formatter?

Thank you.

Upvotes: 0

Views: 2185

Answers (2)

Vinay Sajip
Vinay Sajip

Reputation: 99355

There's an example in the Logging Cookbook which shows one way of doing this.Basically:

import json
import logging

class StructuredMessage:
    def __init__(self, message, /, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        return '%s >>> %s' % (self.message, json.dumps(self.kwargs))

_ = StructuredMessage   # optional, to improve readability

logging.basicConfig(level=logging.INFO, format='%(message)s')
logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))

Of course, you can adapt this basic idea to do something closer to what you want/need.

Update: The formatting only happens if the message is actually output. Also, it won't apply to logging from third-party libraries. You would need to subclass Logger before importing any other modules which import logging to achieve that, but it's a documented approach.

Upvotes: 1

alexis
alexis

Reputation: 50190

The format specification %(message)s tells Python you want to format a string. Try it with %(message)r and it should do the job:

>>> logging.error('{"log_message": %r}', {"a": 55})
ERROR:root:{"log_message": {'a': 55}}

Upvotes: 1

Related Questions