Skip to content
Advertisement

Apache Log4j2 package specific logging using log4j2.xml

I am using log4j2. But the problem that I am facing is that it logs all logs. I want to … log from specific package to a specific file & other package to another file. I am using log4j2.xml for configuration. Please can someone help?

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>

<Loggers>
    <Root level="DEBUG" additivity="false">
        <AppenderRef level="DEBUG" ref="CONSOLE" />
        <AppenderRef level="DEBUG" ref="fileAppender" />
    </Root>
    <Logger name="com.pkg.test.logging.method" level="DEBUG"
        additivity="false">
        <Appender-ref ref="fileAppender" level="DEBUG" />
    </Logger>

</Loggers>

<Appenders>

    <Console name="CONSOLE" target="SYSTEM_OUT">
        <PatternLayout
            pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n%throwable}" />
    </Console>

    <RollingFile name="fileAppender" fileName="./log.log"
        filePattern="./log-%d{yyyy-MM-dd}.log">
        <PatternLayout
            pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n}" />
        <Policies>
            <TimeBasedTriggeringPolicy interval="1"
                modulate="true" />
        </Policies>
    </RollingFile>
</Appenders>

Advertisement

Answer

Just answered the question.

log4j2.xml

    <?xml version="1.0" encoding="UTF-8"?>
<Loggers>
    <Root level="DEBUG" additivity="false">
        <AppenderRef level="DEBUG" ref="CONSOLE" />
     </Root>
    <Logger name="com.pkg.test.logging.method" level="DEBUG"
        additivity="false">
        <Appender-ref ref="fileAppender" level="DEBUG" />
    </Logger>

</Loggers>

<Appenders>

    <Console name="CONSOLE" target="SYSTEM_OUT">
        <PatternLayout
            pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n%throwable}" />
    </Console>

    <RollingFile name="fileAppender" fileName="./log.log"
        filePattern="./log-%d{yyyy-MM-dd}.log">
        <PatternLayout
            pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n}" />
        <Policies>
            <TimeBasedTriggeringPolicy interval="1"
                modulate="true" />
        </Policies>
    </RollingFile>
</Appenders>

Removed the <AppenderRef level="DEBUG" ref="fileAppender" /> from root logger. Thus it started logging logs based on packages.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement