Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: can I modify the log contents before logging into a file?

Tags:

python

logging

Is there a way to mask the 'SECRET' information in the log with 'xxxxxxx' without changing the last line of code in below.

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('sample.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

logger.info("Information contains SECRET stuff.")

If I run above code, I will get below log content: 2019-08-21 09:47:12,845:main:Information contains SECRET stuff.

Without changing the last line of code: logger.info("Information contains SECRET stuff"), is there a way to generate expected log as below: 2019-08-21 09:47:12,845:main:Information contains xxxxxxxx stuff.

like image 358
Zhuzhu Avatar asked Oct 25 '25 05:10

Zhuzhu


1 Answers

You could inherit from the 'logging.Logger' class and provide your own 'info' method. Note the addition of the 'setLoggerClass' call to switch to the custom class.

import logging

class secretLogger(logging.Logger):

    def __init__(self,name,level=logging.NOTSET):
        super(secretLogger,self).__init__(name,level)

    def info(self,msg,*args,**kwargs):
        secretMsg = msg.replace('SECRET','xxxxxxxx')
        super(secretLogger,self).info(secretMsg,*args,**kwargs)

logging.setLoggerClass(secretLogger)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('sample.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

logger.info("Information contains SECRET stuff.")
like image 108
bonafidegeek Avatar answered Oct 26 '25 18:10

bonafidegeek