如何避免使用 log4j2 重复记录唯一 ID

How to avoid repetitive logging of unique ID using log4j2

在我运行了数千行代码的应用程序中,我看到人们在每个日志语句中记录一个唯一的 ID(假设是请求 ID)。考虑到多线程的性质和多个请求,我确实明白为什么在开始时只记录一次这个请求 ID 是行不通的。由于其他请求可能介于两者之间,因此日志将被混淆。

是否有使用 log4j2 执行此操作的更简洁的方法。

查看映射诊断上下文 (MDC)。基本上是 ThreadLocal 附加到同一线程记录的所有消息。您必须将其包含在模式中。也不要忘记清除 MDC。

在 Web 应用程序中,通常由 Filter 完成。

这是一个常见问题,在 Log4j2 中您可以使用 ThreadContext 映射来解决它。

当请求进入您的代码时,在 ThreadContext 中设置一个唯一 ID:

ThreadContext.put("id", uniqueID());

从现在开始,在同一线程中发生的所有日志记录都将有一个以 "id" 作为键和您指定的值的映射。您可以将其用于 filtering, routing, and you can make the map appear in the log file with the %X conversation pattern. If you only want a specific key (e.g., "id"), use %X{id} in your pattern layout

完成后,使用 ThreadContext.remove("id") 删除密钥。

最近 Log4j2 添加了 CloseableThreadContext,它会在您使用完后自动删除 key-value 对。