所有请求和响应都记录在Web框架中,但它也在密码中记录(使用日志记录模块)(因为密码在登录请求中)。
我可以选择性地打印“XXXXXXX”以获取密码或我不想打印的任何其他字段吗?
在authentication.py中
import logging
from logging import config
logging.config.dictConfig({'version': 1, 'delete_existing_loggers': False, 'handlers': '.....'})
LOGGER = logging.getLogger(__name__)
##code to get variables from http request packet (like method, parameters)(for example, methods, params can be: [authentication.login, username, password], [authentication.change_password, username, old_password, new_password], [authentication.generate_validation_code, username]),
LOGGER.info('method %s with %s parameters called', method, params)
所以我想要,对于特定的方法,一些变量应该是'xxxxx'而不是原始值,特别是如果方法是'authentication.login'我想在参数中打印'xxxx'作为第二个参数。
感谢。
答案 0 :(得分:2)
是的,这是可能的。看看logging.Filter
class。您需要对其进行子类化,然后将其注册到记录器。
示例:
class PasswordLoggingFilter(logging.Filter):
def filter(self, record):
# Modify record, especially record.msg and/or record.args.
if want_to_keep_record:
return True
else:
return False
logger.addFilter(PasswordLoggingFilter())
有关record
对象的详细信息,请documented here。
答案 1 :(得分:0)
除了Christian提供的解决方案之外,如果处理程序在dictConfig或fileConfig中传递,则处理程序类应该是子类,并且需要添加过滤器。
代码取自以下网页: http://streamhacker.com/2010/04/08/python-logging-filters/
class InfoFilter(logging.Filter):
def filter(self, rec):
return rec.levelno == logging.INFO
class InfoHandler(logging.StreamHandler):
def __init__(self, *args, **kwargs):
StreamHandler.__init__(self, *args, **kwargs)
self.addFilter(InfoFilter())
此外,如果想要更改记录的arg字段,则必须将其置于列表中然后进行更改并重新分配。