简体   繁体   English

Python:我可以在登录文件之前修改日志内容吗?

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

Is there a way to mask the 'SECRET' information in the log with 'xxxxxxx' without changing the last line of code in below. 有没有一种方法可以用“ xxxxxxx”屏蔽日志中的“ SECRET”信息,而无需更改下面的最后一行代码。

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. 如果我运行上述代码,则将获得以下日志内容:2019-08-21 09:47:12,845: main :信息包含SECRET内容。

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. 在不更改最后一行代码的情况下:logger.info(“信息包含机密内容”),有一种方法可以生成预期的日志,如下所示:2019-08-21 09:47:12,845: main :信息包含xxxxxxxx内容。

You could inherit from the 'logging.Logger' class and provide your own 'info' method. 您可以继承'logging.Logger'类并提供自己的'info'方法。 Note the addition of the 'setLoggerClass' call to switch to the custom class. 请注意添加了“ setLoggerClass”调用以切换到自定义类。

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.")

One possibility is to define a custom LoggingAdapter class whose process method modifies the incoming message. 一种可能性是定义一个自定义LoggingAdapter类,其process方法将修改传入的消息。 This follows the recipe from the logging cookbook . 这遵循日志记录食谱中的方法

class StripSecret(logging.LoggerAdapter):
    def process(self, msg, kwargs):
        return msg.replace("SECRET", "XXXXXX"), kwargs

logger = logging.getLogger(...)
adapter = StripSecret(logger, {})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM