Custom Log4j Configuration Examples
You can create your own custom log4j configurations that you can use for logging instead of the default log4j2.xml file.
You can also see the official log4j wiki page for more information on log4j configurations at the Apache Log4j 2 webpage.
Following are the few example XML configurations for the some logging use cases, which you can use after overriding the default logging (see Overriding the Default Logging Mode for more information).
Multiple Log Files Using Single log4j Configuration
Define multiple FileAppender classes to create multiple logging by adding appender referense to the respective loggers as shown in the following example:
<RollingFile
name="rollingFile_Test1"
fileName="${LOG_DIR}/application.log"
filePattern="${LOG_DIR}/application.%d{dd-MMM}.log.gz"
ignoreExceptions="false">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy filePattern="${LOG_DIR}/application.%d{dd-MMM-hh}.log.gz" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile>
<RollingFile
name="rollingFile_Test2"
fileName="${LOG_DIR}/Action.log"
filePattern="${LOG_DIR}/Action.%d{dd-MMM}.log.gz"
ignoreExceptions="false">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy filePattern="${LOG_DIR}/Action.%d{dd-MMM-hh}.log.gz" />
</Policies>
<DefaultRolloverStrategy max="10" />
</RollingFile>
Rotating Log Files Based on Time
If using RollingFileAppender, then use TimeBasedRollingPolicy to specify when to roll over log files based on date time. The FileNamePattern property defines the name pattern for rolled over files. In given example, it rename the rollover log files with date-month in log file name. For example, pattern {yyyy-MM-dd-HH}
rollover log file every hour.
The .gz
file extension is used so that log4j compresses the log file automatically.
<RollingFile
name="rollingFile"
fileName="${LOG_DIR}/application.log"
filePattern="${LOG_DIR}/application.%d{dd-MMM}.log.gz"
ignoreExceptions="false">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy filePattern="${LOG_DIR}/application.%d{dd-MMM-hh}.log.gz" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile>
The following tables displays the example values of the DatePattern parameter which defines the time when to roll over the logs.
Time | Value |
---|---|
Minutely | .%d{yyyy-MM-dd-HH-mm} |
Hourly | .%d{yyyy-MM-dd-HH} |
Half-daily | .%d{yyyy-MM-dd-a} |
Daily | .%d{yyyy-MM-dd} |
Weekly | .%d{yyyy-ww} |
Monthly | .%d{yyyy-MM} |