在尝试对发送到 Azure Application Insights 的日志中的敏感数据进行屏蔽时,官方文档如下: 屏蔽日志消息中的敏感数据
仅显示敏感数据的单个实例被屏蔽。我想在日志中屏蔽可变数量的敏感数据实例。假设我的敏感数据是 userId:“A12345678Y”和“B23456789Z”
我想屏蔽日志中的所有用户ID:“用户A12345678Y已与用户B23456789Z成为好友,并且用户A12345678Y与用户B23456789Z有20个共同好友”。 userId 的数量是可变的,这意味着每个日志可能有数十个 userId。
我尝试通过在
".*(?<redactedUserId>[A|B][0-9]{8}[Y|Z]).*"
JSON 配置中添加规则 "rules"
两次来屏蔽 userId 的实例。
JSON 看起来像这样:
{
"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}"
如果我有 50 个 userId 实例怎么办?还是70?我想把它们全部掩盖起来。对规则的 50 行进行硬编码似乎是不明智的。
我应该如何实现,以屏蔽可变数量的 userId 实例?
Application Insights 3.4.16 中进行了一项更改,允许您从一条规则中屏蔽每个 userId。你试过3.4.16版本吗?
我应该如何实现,以屏蔽可变数量的 userId 实例?
您可以通过在 Java 应用程序中使用自定义处理器或筛选器来实现此目的,然后再将日志发送到 Azure Application Insights。
使用循环或类似的机制来迭代日志消息。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogMasker {
public static void main(String[] args) {
String logMessage = "User A12345678Y has friended User B23456789Z, and User A12345678Y has 20 mutual friends with User B23456789Z";
// Construct a regular expression pattern to match userIds
Pattern userIdPattern = Pattern.compile("[A|B][0-9]{8}[Y|Z]");
Matcher matcher = userIdPattern.matcher(logMessage);
StringBuffer maskedLog = new StringBuffer();
while (matcher.find()) {
// Replace each userId with a placeholder
matcher.appendReplacement(maskedLog, "{redactedUserId}");
}
matcher.appendTail(maskedLog);
// Output the masked log message
System.out.println(maskedLog.toString());
}
}
您还可以使用自定义日志附加程序或过滤器。
自定义 Log4j Appender:
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
public class CustomLogMaskerAppender extends AppenderSkeleton {
private static final Logger logger = Logger.getLogger(CustomLogMaskerAppender.class);
@Override
protected void append(LoggingEvent event) {
String logMessage = event.getRenderedMessage();
// Construct a regular expression pattern to match userIds
String pattern = "[A|B][0-9]{8}[Y|Z]";
// Replace all matches with {redactedUserId}
String maskedLogMessage = logMessage.replaceAll(pattern, "{redactedUserId}");
// Log the masked message
event.setRenderedMessage(maskedLogMessage);
super.append(event);
}
@Override
public void close() {
// Cleanup, if necessary
}
@Override
public boolean requiresLayout() {
return false;
}
}