如何使用模式布局 log4j2 将数据放入日志中

How to put data in logs using pattern layout log4j2

我正在 log4j2-spring.xml 中定义 log4j2 配置。在此我将模式布局定义如下:

        <Property name="LOG_PATTERN" value="%d [%thread] [%-5level] 
               [Content-Id:%X{CID}] [SessionId:%X{sessionId}] 
 [CustomerId:%X{customerId}] [%c{1.}] - %msg%n" />

现在我想在客户 ID 中动态添加数据,但我不知道该怎么做。

感谢任何帮助。

如您在 log4j2 documentation 中所见,将 customerId 放入 ThreadContext

ThreadContext.put("customerId", <your customerID>); 

并且占位符将被 log4j2 替换