javalogginglog4j2rollingfileappender

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.


Solution

  • 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">