需求
需要将所有的log的出现的手机号进行打码,使用 * 代替中间的4位数
方案
应尽量减小对原油代码的影响,所以应当重写logging的核心输出模块,在重写度的过程中对数据进行处理;
实现
logging 的处理字串的核心部分为 logging.Logger._log ;因此需要在这个核心模块上增加装饰器,
python
import re
import logging
from functools import wraps
# 重写logging模块,全局生效
def override_logging():
original_log = logging.Logger._log
@wraps(original_log)
def new_log(self, level, msg, args, **kwargs):
msg = mask_sensitive_info(msg)
if isinstance(msg, str):
if args:
if isinstance(args, tuple):
args = tuple([mask_sensitive_info(text) for text in args])
return original_log(self, level, msg, args, **kwargs)
logging.Logger._log = new_log
在标记内容时
python
def mask_sensitive_info(text: str) -> str:
"""
敏感信息打码规则:
- 手机号:中间4位打码(138****5678)
"""
if not text:
return text
if type(text) != str: # 这里会有很多其他类型的,所以需要排除一下
return text
# 手机号打码
phone_pattern = re.compile(r'(1\d{10})')
text = phone_pattern.sub(lambda m: f"{m.group(1)[:3]}****{m.group(1)[7:]}", text)
return text