Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a prefix to an existing python logging formatter

Tags:

python

logging

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?

like image 587
Ezra Avatar asked Mar 11 '15 18:03

Ezra


3 Answers

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

like image 126
timfjord Avatar answered Sep 23 '22 05:09

timfjord


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
like image 25
user3885927 Avatar answered Sep 24 '22 05:09

user3885927


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')
like image 35
Wenyu Avatar answered Sep 22 '22 05:09

Wenyu