Paul Draper
Paul Draper

Reputation: 83323

Best way to add custom information to for logging

I've been reading the Python logging documentation, and its certainly has a lot of functionality...for everything.

The problem I'm facing is that I'm not Dutch and so I'm not sure what the right way to do this is.

I am running events in a simulator, and I would like to prefix every log message with the timestamp of the simulated time (probably with a length formatter too, just to keep it looking good). I could change this in a subclass of Logger or Handler, but I don't think that is the right way.

I think the right way is to use a LoggerAdapter or a Filter. Is this right, and if so, which one should I prefer?

Upvotes: 1

Views: 472

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99425

Surely if you just need to prefix every log message with the timestamp, all you need to do is provide an appropriate format string for a formatter? As mentioned here in the documentation.

Update: A LoggerAdapter would be more appropriate for situations where contextual information is moderately long-lived. For example, in a network server application which handles multiple client connections, the connection details (e.g. client IP address) might be useful context, so you would create a LoggerAdapter instance when a new client connection was created. This doesn't sound like your simulation scenario.

A Filter, on the other hand, could be used if you could use it to get the simulation time, e.g.

class SimulationFilter(logging.Filter):
    def __init__(self, context):
        """
        Set up with context passed in which allows access
        to simulation times.
        """
        self.context = context

    def filter(self, record):
        "Add sim_time field to record, formatted as you wish"
        record.sim_time = '%s' % self.context.get_sim_time()
        return True

and then add %(sim_time)s in your Formatter's format string.

Alternatively, if you know the simulation time whenever you make a logging call, you could just do e.g.

logger.debug('Message with %s', arguments, extra={'sim_time': sim_time})

and likewise have %(sim_time)s in your Formatter's format string.

Upvotes: 2

Related Questions