如何在Azure Monitor Application Insights Java日志中掩码多实例敏感数据
Azure Application Insights日志中可变数量敏感数据的掩码实现
问题背景
需要为发送至Azure Application Insights的日志实现敏感数据掩码,目标是处理日志中数量不固定的userId(格式如A12345678Y、B23456789Z),每个日志里的userId实例可能多达数十个。官方提供的单实例掩码方法无法满足多实例的需求。
尝试过的方法及问题
曾在JSON配置的rules中添加两次正则规则".*(?<redactedUserId>[A|B][0-9]{8}[Y|Z]).*",配置如下:
{ "connectionString": "InstrumentationKey=00000000-0000-0000-0000-000000000000", "preview": { "processors": [ { "type": "log", "body": { "toAttributes": { "rules": [ ".*(?<redactedUserId>[A|B][0-9]{8}[Y|Z]).*", ".*(?<redactedUserId>[A|B][0-9]{8}[Y|Z]).*" ] } } }, { "type": "attribute", "actions": [ { "key": "redactedUserId", "action": "delete" } ] } ] } }
该配置仅能掩码2个userId实例,效果如下:
- 掩码前日志:
"User A12345678Y has friended User B23456789Z, and User A12345678Y has 20 mutual friends with User B23456789Z" - 掩码后日志:
"User A12345678Y has friended User B23456789Z, and User {redactedUserId} has 20 mutual friends with User {redactedUserId}"
硬编码多条规则显然不适用于数量可变的场景,需要更通用的实现方式。
解决方案
已解决该问题,同时支持将脱敏标记替换为自定义内容,具体步骤如下:
- 第一个
log处理器:将包含userId的完整日志消息转换为名为LogMessage的单个属性; - 第二个
attribute处理器:用正则匹配userId模式,将其替换为自定义内容(如**已脱敏**),此时LogMessage属性值为脱敏后的日志; - 第三个
log处理器:将LogMessage属性值转回日志内容; - 第四个
attribute处理器:删除日志中的LogMessage属性,清理自定义属性。
对应的JSON配置:
"processors": [ { "type": "log", "body": { "toAttributes": { "rules": [ "(?<LogMessage>.*[A|B][0-9]{8}[Y|Z].*)" ] } } }, { "type": "attribute", "actions": [ { "key": "LogMessage", "pattern": "[A|B][0-9]{8}[Y|Z]", "replace": "**已脱敏**", "action": "mask" } ] }, { "type": "log", "body": { "fromAttributes": [ "LogMessage" ] } }, { "type": "attribute", "actions": [ { "key": "LogMessage", "action": "delete" } ] } ]
内容的提问来源于stack exchange,提问作者piplup
相关产品推荐
相关产品推荐

