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.
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.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With