Skip to content

Log4j2 Rolling File Appender

In Log4j2, a Rolling File Appender is responsible for writing log messages to a file while managing the archival of old log data based on specific triggers, such as file size or time^[600-developer-java-3-party-java-log4j2.md].

Configuration

The Rolling File Appender is defined within the <Appenders> section of the log4j2.xml configuration file^[600-developer-java-3-party-java-log4j2.md]. A typical declaration includes the appender name, the target file name, and the naming pattern for archived files.

<RollingFile name="main" 
             fileName="C:/logs/main.log"
             filePattern="C:/logs/main-%d{yyyy-MM-dd}-%i.log">
    <!-- Policies and Layout -->
</RollingFile>
  • name: A unique identifier used to reference the appender in logger configurations^[600-developer-java-3-party-java-log4j2.md].
  • fileName: The path to the current active log file^[600-developer-java-3-party-java-log4j2.md].
  • filePattern: The pattern used for naming archived files when a rollover occurs. This pattern supports date specifiers (e.g., %d{yyyy-MM-dd}) and an integer index (e.g., %i) to distinguish between multiple archives from the same period^[600-developer-java-3-party-java-log4j2.md].

Policies

Rollover conditions are defined within the <Policies> tag^[600-developer-java-3-party-java-log4j2.md].

  • SizeBasedTriggeringPolicy: Triggers a rollover when the active log file reaches a specified size^[600-developer-java-3-party-java-log4j2.md]. In the provided example, the policy is set to 19500KB^[600-developer-java-3-party-java-log4j2.md].
<Policies>
    <SizeBasedTriggeringPolicy size="19500KB"/>
</Policies>

Rollover Strategy

The DefaultRolloverStrategy determines how archived files are handled during the rollover process^[600-developer-java-3-party-java-log4j2.md].

  • max attribute: Specifies the maximum number of archived files to keep^[600-developer-java-3-party-java-log4j2.md]. In the example configuration, max="10" ensures that only the 10 most recent archives are retained, with older files being deleted automatically^[600-developer-java-3-party-java-log4j2.md].

Layout

The log message format is controlled by the <PatternLayout> element^[600-developer-java-3-party-java-log4j2.md]. A common pattern includes the log level, timestamp, thread, logger name, and the message itself^[600-developer-java-3-party-java-log4j2.md].

<PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"/>

Sources

  • 600-developer-java-3-party-java-log4j2.md