Search code examples
javaloggingconfigurationlog4jlog4j2

My log4j2 log file always have double output of each line. How can I stop the duplication please?


My log4j2 log file always has double output of each line. How can I stop the duplication please?

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <properties>
        <property name="name">CernerPharmacyWebApp</property>
        <property name="pattern">%d %-5p %C{2} (%F:%L) - %m%n</property>
    </properties>
    <Appenders>
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout>
                <pattern>${pattern}</pattern>
            </PatternLayout>
        </Console>
        <RollingFile name="ROLLING_FILE" fileName="..\logs\${name}.log"
                     filePattern="..\logs\${name}-%d{yyyy-MM-dd}-%i.log">
            <PatternLayout>
                <pattern>${pattern}</pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy/><!-- Rotated everyday -->
                    <SizeBasedTriggeringPolicy size="50 MB"/> <!-- Or every 50 MB -->
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="error">
            <!-- <AppenderRef ref="CONSOLE"/> -->
            <AppenderRef ref="ROLLING_FILE"/>
        </Root>
        <!-- Controls packages -->
        <Logger name="com.jarmel.pharmacy.controls.BarCodeOrderServlet" level="trace">
            <!-- <AppenderRef ref="CONSOLE"/> -->
            <AppenderRef ref="ROLLING_FILE"/>
        </Logger>
        <Logger name="com.jarmel.pharmacy.controls.GetCodeValues" level="error">
            <!-- <AppenderRef ref="CONSOLE"/> -->
            <AppenderRef ref="ROLLING_FILE"/>
        </Logger>
        <Logger name="com.jarmel.pharmacy.controls.GetPersonnelServlet" level="error">
            <!-- <AppenderRef ref="CONSOLE"/> -->
            <AppenderRef ref="ROLLING_FILE"/>
        </Logger>
   </Loggers>
</Configuration>

Blockquote


Solution

  • Both your root logger and your named loggers are referring to the same appender. Each active logger will send an event to its appender, so the appender will receive the event multiple times, once for each logger. (The root logger will get all events, the named loggers will only get the events emitted by the Logger in your code with a matching name.)

    This is called Additivity. See http://logging.apache.org/log4j/2.x/manual/configuration.html#Additivity

    You can set additivity="false" in the named logger config.