Ezra
Ezra

Reputation: 1481

How to add a prefix to an existing python logging formatter

In my code I get a logger from my client, then I do stuff and log my analysis to the logger.

I want to add my own prefix to the logger but I don't want to create my own formatter, just to add my prefix to the existing one.

In addition I want to remove my prefix once my code is done.

From looking at the documentation I could only find ways to create new formatter but not to modify an existing one. Is there a way to do so?

Upvotes: 14

Views: 26120

Answers (3)

timfjord
timfjord

Reputation: 1839

This can be achieved with logging.LoggerAdapter

import logging    


class CustomAdapter(logging.LoggerAdapter):
    def process(self, msg, kwargs):
        return f"[my prefix] {msg}", kwargs


logger = CustomAdapter(logging.getLogger(__name__))

Please note that only the message will be affected. But this technique can be used for more complicated cases

Upvotes: 15

user3885927
user3885927

Reputation: 3503

You are correct. As per Python 3 and Python 2 documentation there is no way to reset your format on the existing formatter object and you do need to create a new logging.Formatter object. However, looking at the object at runtime there is _fmt method to get the existing format and it seems tweaking it will work. I tried in 2.7 and it works. Below is the example.

Example code for python 2.7:

import logging
logger = logging.getLogger('something')
myFormatter = logging.Formatter('%(asctime)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(myFormatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.info("log statement here")

#Tweak the formatter
myFormatter._fmt = "My PREFIX -- " + myFormatter._fmt
logger.info("another log statement here")

Output:

2015-03-11 12:51:36,605 - log statement here
My PREFIX -- 2015-03-11 12:51:36,605 - another log statement here

Upvotes: 14

Wenyu
Wenyu

Reputation: 51

You can actually set the format through the 'basicConfig', it is mentioned in the Python document: https://docs.python.org/2/howto/logging-cookbook.html#context-info

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')

Upvotes: 5

Related Questions