在日志文件中动态填充变量

时间:2019-02-06 08:48:10

标签: dynamic log4j2 slf4j

我有一个处理用户请求的Web服务(Jenkins),并且我希望能够将请求会话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。

谢谢。

1 个答案:

答案 0 :(得分:0)

我发现了,比我想象的要容易得多。

基本将%X {userSessionId}添加到了

<PatternLayout pattern= ... /> 

在log4j2.xml中行。 并在添加的代码中

HttpSession session = request.getSession();
org.apache.logging.log4j.ThreadContext.put("userSessionId", session.getId());