作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在使用库“日志记录”在我的脚本中记录信息和警告消息,无论如何我可以在打印到 stdout 时过滤掉密码(我有多个密码并希望将它们替换为星号) ?
最佳答案
为了从 stdout
流中过滤掉密码列表中包含的特定单词(这是 logging.DEBUG
和 logging.INFO
消息)和 stderr
流(这是 logging.WARNING
、logging.ERROR
和 logging.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/
我是一名优秀的程序员,十分优秀!