Eastsun
Eastsun

Reputation: 18869

How to make log4j2 create a different log file each time I restart jvm

I want to create a different log file each time when I run the java application. I have the following configuration. I expected it would create a log file named rf-yyyyMMdd-HHmmss.log which the yyyyMMdd-HHmmss is the time I start the java application. However it doesn't work. Any help would be appreciated!

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="DEBUG">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <RollingFile name="RF" filename="/home/sxd/rfjq/rf.log" immediateFlush="false" append="false" filePattern="/home/sxd/r\ q/rf-%d{yyyyMMdd-HHmmss}.log">
            <PatternLayout pattern="[%p] %m%n" />
            <Policies>
                <OnStartupTriggeringPolicy />
            </Policies>
        </RollingFile>
    </appenders>
    <loggers>
        <Logger name="model.ModelRF" level="trace">
            <appender-ref ref="RF" />
        </Logger>
        <root level="trace">
            <appender-ref ref="Console" />
        </root>
    </loggers>
</configuration>

Upvotes: 4

Views: 8070

Answers (4)

        <Policies>
            <TimeBasedTriggeringPolicy interval="10" modulate="true"/>
            **<OnStartupTriggeringPolicy minSize="0"/>**
        </Policies>

in FileAppender worked fine for me.

Upvotes: 0

Cyrax
Cyrax

Reputation: 825

Remove append="false" from RollingFile.

Upvotes: 3

Augustin Ghauratto
Augustin Ghauratto

Reputation: 1520

Notice that your file name is filename="/home/sxd/rfjq/rf.log and thus it will create file rf.log. Filename pattern will be used only for rolling strategies, if you use one. Rename your filename with date pattern, ex:

filename="/home/sxd/rfjq/rf-%d{yyyyMMdd-HHmmss}.log"

You can as well add "%i" to your filename pattern. This enables "Rollover Strategies" as in documentation, ex:

filePattern="/home/sxd/rfjq/rf-%d{yyyyMMdd-HHmmss}.%i"

along with <OnStartupTriggeringPolicy /> on application startup, would cause file to be created with pattern rf-%d{yyyyMMdd-HHmmss} but, if such file already exists it would add suffix .1 to end of file. If there is file with .1 suffix it will create another with suffix .2. You can read more about it in documentation.

Upvotes: 2

Remko Popma
Remko Popma

Reputation: 36844

You may have found a bug. I suggest raising this on the Log4j2 Jira issue tracker.


EDIT: In addition to the OnStartupTriggeringPolicy you need to specify a TimeBasedTriggeringPolicy.

Upvotes: 0

Related Questions