Syntax highlighter header

Saturday, 5 September 2020

Configuring Log4j 2

In this post I am going to explain configuring Log4J 2 to log high severity log messages to console and file both and lower severity messages only to log file. This way console is not cluttered with unnecessary messages and detail information is available for debugging in log file.

I will define two appenders A and R. The appender A has a threshold filter applied to it which accepts only log messages with severity level ERROR and higher. The appender R don't have any filter attached to it, so it will log all messages.

The location of log4j2.xml need to be provided using system property log4j.configurationFile, for example -Dlog4j.configurationFile=/my/path/log4j2.xml

 Please note that system property log4j.configuration is used for Log4J 1.2 which has different syntax.



<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
        <Appenders>
                <Console name="A" target="SYSTEM_OUT">
                        <PatternLayout pattern="%d [%t] %-5p {%F:%L} %x - %m%n" />
                        <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
                </Console>

                <RollingFile name="R"
                        fileName="/home/tomcat/logs/tomcat-log4j2.log" filePattern="/home/tomcat/logs/tomcat-log4j2-%d{yyyy-MM-dd}.log">
                        <PatternLayout pattern="%d [%t] %-5p {%F:%L} %x - %m%n" />
                        <Policies>
                                <TimeBasedTriggeringPolicy interval="1" />
                        </Policies>
                </RollingFile>
        </Appenders>


        <Loggers>
                <Logger name="org.apache" level="trace"/>
                <Root level="ERROR">
                        <AppenderRef ref="A" />
                        <AppenderRef ref="R" />
                </Root>
        </Loggers>
</Configuration>

No comments:

Post a Comment