我有一个Web服务(詹金斯)处理用户的请求,我希望能够动态地追加请求会话ID,每个日志行,而无需实际变量添加到每个日志动作。
我使用log4j2与SLF4J实现,我使用初始化与org.apache.logging.log4j.core.config.Configurator
外部配置文件中的记录,我用每创建每个会话记录器的实例
final Logger logger = LoggerFactory.getLogger(MyClass.class);
我有一个例子:
logger.debug("received new request");
...
logger.debug("added something");
我想加入到每行的用户会话ID,而无需将其添加自己喜欢:
logger.debug("{} received new request",session.getId());
...
logger.debug("{} added something",session.getId());
我log4j2.xml文件是:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Configuration status="INFO">
<Properties>
<Property name="logPath">...</Property>
<Property name="rollingFileName">...</Property>
</Properties>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
</Console>
<RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
<PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
<Policies>
<!-- Causes a rollover if the log file is older than the current JVM's start time -->
<OnStartupTriggeringPolicy />
<!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="com.project" level="debug" additivity="false">
<AppenderRef ref="console"/>
<AppenderRef ref="rollingFile"/>
</Logger>
</Loggers>
</Configuration>
从当前日志文件实际结果:
[[36mDEBUG[m] 2019-02-05 16:42:09,794 SpellCheck.getResult() - start
[[36mDEBUG[m] 2019-02-05 16:42:10,420 SpellCheck.getResult() - Spelling correction returned no results.
[[36mDEBUG[m] 2019-02-05 16:42:10,420 SpellCheck.getResult() - end
我想达到的目标:
[[36mDEBUG[m] 2019-02-05 16:42:09,794 SpellCheck.getResult() - 1234 - start
[[36mDEBUG[m] 2019-02-05 16:42:10,420 SpellCheck.getResult() - 1234 - Spelling correction returned no results.
[[36mDEBUG[m] 2019-02-05 16:42:10,420 SpellCheck.getResult() - 1234 - end
其中1234是例如会话ID。
谢谢。
我想通了,比我想象的要容易得多。
基本上添加%X {usersessionid在}到
<PatternLayout pattern= ... />
排在log4j2.xml。并在代码中添加
HttpSession session = request.getSession();
org.apache.logging.log4j.ThreadContext.put("userSessionId", session.getId());