javalogginglog4jlog4j2

How to use policies on dynamic log file name?


I'm using Log4j2 and I need my logs to:

  1. Include the current date and process idin the active log file name (e.g., logname.529628.27-04-2025.log)
  2. create new log based on file size (for example, every 10MB)
  3. Keep only a maximum number of old files (like 10 backups)

this is what i have now :

<?xml version="1.0" encoding="UTF-8"?>
<Properties>
    <Property name="LOG_PATTERN">
        %-40.40c{1.} : %notEmpty{%m}%n%ex
    </Property>
    <Property name="PID">${sys:PID}</Property>
    <Property name="FS">${sys:file.separator}</Property>
    <Property name="log-path">log${sys:file.separator}</Property>
    <Property name="log-pattern">%d{yyyy-MM-dd HH:mm:ss,SSS} PID:${sys:PID} %-2p [T@%tid-%t] [%F:%L] %notEmpty{%marker} %m%n</Property>
</Properties>

<Appenders>
    <Routing name="Routing">
        <Routes pattern="$${sys:logName}">
            <Route key="testlog">
                <RollingFile name="ArchiveLog" fileName="${log-path}logname.${sys:PID}.${date:dd-MM-yyyy}.log"
                             filePattern="${log-path}logname.${sys:PID}.${date:dd-MM-yyyy}.%i.log">
                    <PatternLayout pattern="${log-pattern}"/>
                    <Policies>
                        <SizeBasedTriggeringPolicy size="10MB"/>
                    </Policies>
                    <DefaultRolloverStrategy max="10">
                    </DefaultRolloverStrategy>
                </RollingFile>
            </Route>
        </Routes>
    </Routing>
</Appenders>

<Loggers>
    <Logger name="logname" level="trace" additivity="false">
        <AppenderRef ref="Routing" />
    </Logger>
    <Root level="info">
        <AppenderRef ref="Routing"/>
    </Root>
</Loggers>

But it seems rotation by size is not working correctly on dynamic file name. any ideas?

thanks!


Solution

  • The rotation isn’t working because Log4j2’s RollingFile appender needs the active fileName to stay static, adding ${date} there confuses the rollover.

    To fix it, keep fileName simple and static, and use the %d pattern only in filePattern so Log4j2 can handle size-based rotation and backups properly.

    Replace your <RollingFile> with this:

    <RollingFile name="ArchiveLog"
                 fileName="${log-path}logname.${sys:PID}.current.log"
                 filePattern="${log-path}logname.${sys:PID}.%d{dd-MM-yyyy}.%i.log">
        <PatternLayout pattern="${log-pattern}"/>
        <Policies>
            <SizeBasedTriggeringPolicy size="10MB"/>
        </Policies>
        <DefaultRolloverStrategy max="10"/>
    </RollingFile>