Denis Rimskii
Denis Rimskii

Reputation: 33

Log4j2 creating new file with distinct filename each time the JVM starts

I need to create a new log file each time i start the JVM.

    <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <RollingFile name="roll-by-time" fileName="target/log4j2/roll-by-time/app.log"
            filePattern="target/log4j2/roll-by-time/app.%d{MM-dd-yyyy-HH-mm}.log"
            ignoreExceptions="false"
            append="false">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH:mm:ss} %p %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <OnStartupTriggeringPolicy />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="trace">
            <AppenderRef ref="Console" />
            <AppenderRef ref="roll-by-time" />
        </Root>

    </Loggers>
</Configuration>

I have tried this config, but all it does is it rewrites the file each time, but i need to make a new one with distinct filename, based on date and/or time. Tried to insert %d{MM-dd-yyyy-HH-mm} in the fileName paramater, but it didn't work out.

Upvotes: 3

Views: 2733

Answers (2)

Persik Lopa
Persik Lopa

Reputation: 37

Try the filename to specify ${runid}.log. Where runid = $${date:YYYY-MM-dd HH-mm-ss}

<Properties>
        <Property name="runid">$${date:YYYY-MM-dd HH-mm-ss}</Property>
    </Properties>
    <Appenders>
         <File name="MyFile" fileName="logs\${runid}.log"   immediateFlush="false" append="true">
            <PatternLayout pattern="%d{dd-MM-yyy HH:mm:ss.SSS} %-5level  - %msg%n"/>
        </File>

Upvotes: 2

Vikas Sachdeva
Vikas Sachdeva

Reputation: 5803

Remove append="false" from appender configuration or set to it true -

<RollingFile name="roll-by-time" fileName="target/log4j2/roll-by-time/app.log"
            filePattern="target/log4j2/roll-by-time/app.%d{MM-dd-yyyy-HH-mm}.log"
            ignoreExceptions="false"
            append="true">

Upvotes: 2

Related Questions