gpt4 book ai didi

python - 如何在 python 日志记录中过滤标准输出

转载 作者:太空狗 更新时间:2023-10-30 02:58:11 27 4
gpt4 key购买 nike

我正在使用库“日志记录”在我的脚本中记录信息和警告消息,无论如何我可以在打印到 stdout 时过滤掉密码(我有多个密码并希望将它们替换为星号) ?

最佳答案

为了从 stdout 流中过滤掉密码列表中包含的特定单词(这是 logging.DEBUGlogging.INFO消息)和 stderr 流(这是 logging.WARNINGlogging.ERRORlogging.CRITICAL 消息的位置go), 你可以用一个简单的类替换原始流,在写出之前替换关键词:

class PasswordFilter(object):
def __init__(self, strings_to_filter, stream):
self.stream = stream
self.strings_to_filter = strings_to_filter

def __getattr__(self, attr_name):
return getattr(self.stream, attr_name)

def write(self, data):
for string in self.strings_to_filter:
data = re.sub(r'\b{0}\b'.format(string), '*' * len(string), data)
self.stream.write(data)
self.stream.flush()

def flush(self):
self.stream.flush()

将原始流替换为过滤后的流:

top_secret_passwords = ['do not tell me', 'I am secret', 'important', 'foo',
'foobar']
sys.stdout = PasswordFilter(top_secret_passwords, sys.stdout)
sys.stderr = PasswordFilter(top_secret_passwords, sys.stderr)

现在,设置日志记录并写入一些日志消息:

# set up your logging after activating the filter, won't work otherwise
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.debug('You cannot see me anymore: {0}'.format(top_secret_passwords[0]))
logger.info('You cannot see me anymore: {0}'.format(top_secret_passwords[1]))
logger.warning('You cannot see me anymore: {0}'.format(top_secret_passwords[2]))
logger.error('You cannot see me anymore: {0}'.format(top_secret_passwords[3]))
logger.critical('You cannot see me anymore: {0}'.format(top_secret_passwords[4]))

输出将如下所示:

DEBUG:__main__:You cannot see me anymore: **************
INFO:__main__:You cannot see me anymore: ***********
WARNING:__main__:You cannot see me anymore: *********
ERROR:__main__:You cannot see me anymore: ***
CRITICAL:__main__:You cannot see me anymore: ******

关于python - 如何在 python 日志记录中过滤标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34904946/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com