🎯 今日核心问题
- Agent 的日志里必然出现用户原话、工具返回的订单详情、身份证号,哪一层可以存原文、哪一层绝对不能?
- 出了问题要能复现,但复现需要完整 Prompt,这和「不落敏感数据」矛盾吗?怎么解?
- 脱敏做在日志框架里、做在业务代码里,还是做在采集端?三种做法的漏点数差多少?
📖 精读提纲
【一】日志分三层,只有一层能碰原文
L1 链路日志(INFO):只有结构化字段——traceId、step、model、tool、latency、tokens、outcome。永远不含内容,可以长期保留、可以进第三方可观测平台。L2 内容日志(DEBUG,按需开启):Prompt 与补全的原文、工具入参出参。脱敏后写独立索引,保留 7 天,只在排障时按 traceId 精确调取。L3 审计日志(独立表,不可变):谁在什么时间调了什么工具、改了什么数据、幂等键是什么。不脱敏但加密存储,权限收紧到只有审计角色可读,保留 1-3 年。
最常见的错误是把三层混成一锅 log.info(prompt),结果链路日志被撑爆、敏感数据满地跑、合规审计还找不到该找的东西。判断标准很简单:这条日志需要被人「读内容」吗?需要就进 L2,不需要就是 L1。
【二】结构化,别拼字符串
log.info("tool {} cost {} ms for {}", name, ms, id) 是人类可读、机器不可查。用 SLF4J 的 fluent API 打 KV:log.atInfo().addKeyValue("tool", name).addKeyValue("costMs", ms).log("tool call done"),配合 Logstash encoder 输出 JSON,才能在 Kibana/Loki 里按 tool="refund" AND costMs>3000 过滤。注意:被 addKeyValue 的字段会被 MDC 打包,所以脱敏必须在这一层之前完成。
【三】脱敏要「白名单 + 正则 + 哈希」三件套
黑名单式脱敏(把 phone 字段替换掉)一定会漏,因为模型会在自然语言里复述手机号。可靠做法是三步:① 白名单决定哪些字段允许进日志(tool、model、step、latency 等),其余默认丢弃;② 对必须保留内容的字段跑正则脱敏(手机号、身份证、银行卡、邮箱、地址);③ 需要跨请求关联的值用加盐哈希(HMAC-SHA256(userId, salt))替换,既可关联又不可反推。
Prompt 原文如果要留存用于复现,正确做法是存脱敏后的 Prompt + 版本化的 Prompt 模板 ID + 变量值的哈希。复现时用模板 + 同一份变量重放,而不是把原始数据永久保存。
【四】模型输出也要脱敏:它能复述
这一点最容易被忽略:工具返回了完整地址,模型在答复里又复述了一遍,于是 L2 里出现两次。所以脱敏管线必须同时作用于「模型输入」「模型输出」「工具 I/O」三条流。另外,「不能记」的还有一类:System Prompt 原文。它是你的核心资产,写进日志等于给任何有日志权限的人一份完整设计稿。
【五】常见误区
- ❌ 用
String.replace()逐个字段手工脱敏。漏一个字段就是一次事故,且没法审计覆盖率。 - ❌ 把脱敏做在 Logback 的
PatternLayout里。这时对象已经被 toString 了,正则只能糊在整行上,性能差且容易把 JSON 结构打坏。 - ❌ 认为「内网日志无所谓」。日志会被同步到第三方 SaaS、被导出成 CSV 发给外包,出口比想象中多得多。
- ❌ 日志里打
e.printStackTrace()或log.error(e.getMessage()),丢掉堆栈。要打log.error("...", e)让框架决定。
💻 代码示例
一个可测试的脱敏器:白名单字段 + 正则 + HMAC 哈希,供 L2 内容日志使用:
@Component
public class PiiMasker {
private static final Pattern PHONE = Pattern.compile("(?<!\\d)1[3-9]\\d{9}(?!\\d)");
private static final Pattern ID_CARD = Pattern.compile("(?<!\\d)\\d{17}[\\dXx](?!\\d)");
private static final Pattern BANK = Pattern.compile("(?<!\\d)\\d{16,19}(?!\\d)");
private static final Pattern EMAIL = Pattern.compile("[\\w.+-]+@[\\w-]+\\.[\\w.]+");
/** 日志允许出现的字段白名单,其余一律丢弃 */
private static final Set<String> ALLOWED = Set.of(
"traceId", "step", "tool", "model", "latencyMs", "promptTokens",
"completionTokens", "outcome", "errorCode", "promptVersion");
private final Mac hmac;
public PiiMasker(@Value("${agent.log.hash-salt}") String salt) throws Exception {
this.hmac = Mac.getInstance("HmacSHA256");
this.hmac.init(new SecretKeySpec(salt.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
}
/** 用于跨请求关联用户:不可反推,但同一用户值稳定 */
public String hash(String raw) {
if (raw == null) return null;
byte[] d = hmac.doFinal(raw.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(d).substring(0, 16);
}
public String mask(String text) {
if (text == null || text.isBlank()) return text;
String s = ID_CARD.matcher(text).replaceAll("[ID]");
s = BANK.matcher(s).replaceAll("[BANK]");
s = PHONE.matcher(s).replaceAll(m -> m.group().substring(0, 3) + "****" + m.group().substring(7));
s = EMAIL.matcher(s).replaceAll("[EMAIL]");
return s;
}
/** 只保留白名单字段,其余值替换为长度标记,便于判断 Prompt 大小而不泄露内容 */
public Map<String, Object> sanitize(Map<String, Object> ctx) {
Map<String, Object> out = new LinkedHashMap<>();
ctx.forEach((k, v) -> {
if (ALLOWED.contains(k)) {
out.put(k, v);
} else {
out.put(k + "._len", v == null ? 0 : String.valueOf(v).length());
}
});
return out;
}
}
包装 LLM 调用,L1 只打字段、L2 按需打脱敏内容:
@Slf4j
@Component
@RequiredArgsConstructor
public class LoggedChatClient {
private final ChatModel delegate;
private final PiiMasker masker;
@Value("${agent.log.content-level:false}")
private boolean contentLogging;
public ChatResponse call(ChatRequest req, String traceId) {
long t0 = System.nanoTime();
try (MDC.MDCCloseable ignored = MDC.putCloseable("traceId", traceId);
MDC.MDCCloseable step = MDC.putCloseable("step", String.valueOf(req.step()))) {
ChatResponse resp = delegate.call(req);
log.atInfo()
.addKeyValue("model", req.model())
.addKeyValue("promptTokens", resp.usage().promptTokens())
.addKeyValue("completionTokens", resp.usage().completionTokens())
.addKeyValue("latencyMs", (System.nanoTime() - t0) / 1_000_000)
.log("gen_ai.chat");
if (contentLogging) {
log.atDebug()
.addKeyValue("prompt", masker.mask(req.promptText()))
.addKeyValue("completion", masker.mask(resp.content()))
.addKeyValue("promptVersion", req.promptVersion())
.addKeyValue("userKey", masker.hash(req.userId()))
.log("gen_ai.chat.content");
}
return resp;
} catch (RuntimeException e) {
log.atWarn()
.addKeyValue("model", req.model())
.addKeyValue("errorCode", classify(e))
.setCause(e)
.log("gen_ai.chat.failed");
throw e;
}
}
private String classify(RuntimeException e) {
if (e instanceof TimeoutException) return "TIMEOUT";
if (e instanceof RateLimitException) return "RATE_LIMIT";
return "UPSTREAM_ERROR";
}
}
Logback 侧把内容日志单独落一个文件,与主日志物理隔离,方便单独设保留期:
<appender name="CONTENT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>/var/log/agent/content.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>/var/log/agent/content.%d{yyyy-MM-dd}.log.gz</fileNamePattern>
<maxHistory>7</maxHistory>
</rollingPolicy>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<includeMdc>true</includeMdc>
</encoder>
</appender>
<logger name="gen_ai.chat.content" level="DEBUG" additivity="false">
<appender-ref ref="CONTENT"/>
</logger>
✏️ 今日动手
① 把 PiiMasker 接进 LLM 调用与工具执行两处;② 写 20 条断言用例,覆盖手机号、身份证、银行卡、邮箱、以及「模型在自然语言里复述手机号」这种场景;③ 用 jq 检查一份真实日志的字段集,确认除白名单外只有 *._len 这类长度字段。最后跑一次 git secrets 式的自查:grep -E '1[3-9][0-9]{9}' /var/log/agent/*.log 必须零命中。
🔖 明日预告
日志解决了「发生了什么」,接下来解决「花了多少钱」。明天把 token 拆成输入、输出、缓存三类分别计价,算出一次典型工单任务的真实现金成本,并给出可复算的 Java 计价模型。