Learn to use log4j LevelRangeFilter
filter which returns the onMatch
result if the level in the LogEvent is in the range of the configured min
and max
levels, otherwise it returns onMismatch
value.
LevelRangeFilter Configuration
In given log4j2.xml
file, we have used to LevelRangeFilter
to filter log levels in such a way that :
- All
info
level logs will go toapplication-info.log
file. - All
debug
level logs will go toapplication-debug.log
file. - All
error
level logs will go toapplication-error.log
file.
Feel free to change the minLevel
and maxLevel
attributes according to the project needs.
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN" monitorInterval="30"> <Properties> <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property> </Properties> <Appenders> <Console name="Console" target="SYSTEM_OUT" follow="true"> <PatternLayout pattern="${LOG_PATTERN}"/> </Console> <RollingFile name="debugLog" fileName="${sys:APP_LOG_ROOT}/application-debug.log" filePattern="${sys:APP_LOG_ROOT}/application-debug-%d{yyyy-MM-dd}-%i.log"> <!-- Matches only DEBUG level --> <LevelRangeFilter minLevel="DEBUG" maxLevel="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="${LOG_PATTERN}"/> <Policies> <SizeBasedTriggeringPolicy size="19500KB" /> </Policies> <DefaultRolloverStrategy max="10"/> </RollingFile> <RollingFile name="infoLog" fileName="${sys:APP_LOG_ROOT}/application-info.log" filePattern="${sys:APP_LOG_ROOT}/application-info-%d{yyyy-MM-dd}-%i.log" > <!-- Matches only INFO level --> <LevelRangeFilter minLevel="INFO" maxLevel="INFO" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="${LOG_PATTERN}"/> <Policies> <SizeBasedTriggeringPolicy size="19500KB" /> </Policies> <DefaultRolloverStrategy max="10"/> </RollingFile> <RollingFile name="errorLog" fileName="${sys:APP_LOG_ROOT}/application-error.log" filePattern="${sys:APP_LOG_ROOT}/application-error-%d{yyyy-MM-dd}-%i.log"> <!-- Matches only ERROR level --> <LevelRangeFilter minLevel="ERROR" maxLevel="ERROR" onMatch="ACCEPT" onMismatch="DENY"/> <PatternLayout pattern="${LOG_PATTERN}"/> <Policies> <SizeBasedTriggeringPolicy size="19500KB" /> </Policies> <DefaultRolloverStrategy max="10"/> </RollingFile> </Appenders> <Loggers> <Logger name="com.howtodoinjava.app" additivity="false"> <AppenderRef ref="debugLog" /> <AppenderRef ref="infoLog" /> <AppenderRef ref="errorLog" /> <AppenderRef ref="Console" /> </Logger> <Root level="all"> <AppenderRef ref="Console"/> </Root> </Loggers> </Configuration>
Drop me your questions in comments section.
Happy Learning !!