1

我正在尝试使用 log4j 2 来改进我的项目中的日志记录。我正在使用一个每天创建一个日志文件的 RollingFile appender。

<Configuration status="DEBUG">
<Properties>
    <Property name="log-path">D:/logs/</Property>
</Properties>
<Appenders>
    <RollingFile name="RollingFile" fileName="${log-path}/daily.log"
                 filePattern="${log-path}/daily_%d{yyyy-MM-dd}.log" >
        <PatternLayout>
            <pattern>%-5level: %d{HH:mm:ss,SSS} - %c{1}::%M -  [%X{username}] %m [%r]%n</pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1"/>
        </Policies>
    </RollingFile>
    <Console name="STDOUT" target="SYSTEM_OUT">
        <PatternLayout pattern="%-5level: %d{HH:mm:ss,SSS} - %c{1}::%M - [%X{username}] %m [%r]%n"/>
    </Console>
</Appenders>
<Loggers>
    <Logger name="root" level="debug" additivity="false">
        <appender-ref ref="RollingFile" level="debug"/>
    </Logger>
    <!-- Change logging level below. Accepted values: error, warning, info, debug, trace -->
    <Root level="debug" additivity="false">
        <AppenderRef ref="RollingFile"/>
        <AppenderRef ref="STDOUT"/>
    </Root>
</Loggers>
</Configuration>

现在我有一个关于 %r 模式的问题。这应该表示从构建布局到创建日志事件所经过的毫秒数。

当我运行它时,我注意到毫秒数太高了,只是数量增加了。这与 Java 应用程序服务器(在我的例子中为 Payara 4.1)对线程的重用有关。

有什么办法可以让我获得请求本身的毫秒数吗?

4

1 回答 1

1

%r represents the number of milliseconds since the JVM started, not necessarily when the Layout was created. The value is calculated by calling ManagementFactory.getRuntimeMXBean().getStartTime(); when the pattern converter is created and then subtracting the event timestamp from the start time value for each event. Given that the start time never changes this value should grow over time as you are describing.

Log4j doesn't have any way to get the time the request was started. You could capture that in a ThreadContext value and then create your own pattern converter to use that value as the value to subtract from the current system time.

于 2016-02-01T17:16:34.463 回答