The below configuration configures two appenders (log output). The first logs to standard system output (console) and the other logs to file. In this example, the location of the file can be set statically in configuration (appender file
) or dynamically via maven filtering feature (<Property name="APPENDER">
). The logs in file will be packed by day. The log line format Conversion Pattern
is set as a variable.
<?xml version="1.0" encoding="UTF-8"?>
<!-- 'status' sets log level for parsing configuration file itself -->
<Configuration status="INFO">
<Properties>
<!-- Sets variable PID, if it's not present in log4j context will take value as below: -->
<Property name="PID">????</Property>
<!-- Sets variable 'LOG_PATTERN', defining how log line will look like -->
<Property name="LOG_PATTERN">%clr{%d{yyyy-MM-dd HH:mm:ss.SSS}}{faint} %clr{%5p} %clr{${sys:PID}}{magenta} %clr{%X{usr}}{green} %clr{---}{faint}%clr{[%15.15t]}{faint} %clr{%-40.40c{1.}:%l}{cyan} %clr{:}{faint} %m%n%wEx</Property>
<!-- LOG_DIR may be set by maven filtering feature: -->
<Property name="LOG_DIR">@logging.path@</Property>
<!-- APPENDER may be set by maven filtering feature, to set 'console' or 'file' appender: -->
<Property name="APPENDER">@logging.default.appender@</Property>
</Properties>
<Appenders>
<!-- Sets console output: -->
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
<!-- Sets output to file, and names it 'file' -->
<RollingRandomAccessFile append="true" fileName="${LOG_DIR}/log4j2.log"
filePattern = "${LOG_DIR}/log4j2.%d{yyyy-MM-dd}.nr%i.log.gz" name="file">
<PatternLayout>
<Pattern>${LOG_PATTERN}</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<!-- Sets debug for Class 'com.example.package.Clazz', and attaches to file 'file' -->
<Logger name="com.example.package.Clazz" level="debug">
<AppenderRef ref="file"/>
</Logger>
<!-- Sets 'info' for package 'org.springframework' -->
<Logger name="org.springframework" level="info" />
<Root level="WARN">
<AppenderRef ref="${APPENDER}"/>
</Root>
</Loggers>
</Configuration>