Jamila Ben Yamoune
Jamila Ben Yamoune

Reputation: 41

log4j2 not writing in the log files

I want to use log4j2 for needs of my application. I'm using RollingAppender with variables in the ThreadContext.

Here is my log4j2.xml

<Configuration>
<Appenders>
    <Routing name="RoutingAppender">
       <Routes pattern="$${ctx:FlowName}">
            <Route>
               <RollingFile name="Audit-${ctx:FlowName}"
                            fileName="logs/Audit-${ctx:FlowName}.log"
                            filePattern="logs/Audit-${ctx:FlowName}.%i.log.gz"
                            immediateFlush="true">
                  <PatternLayout>
                        <pattern>"%m%n"<pattern/>
                  </PatternLayout>

               <Policies>
                  <TimeBasedTriggeringPolicy interval="6" modulate="true" />
                  <SizeBasedTriggeringPolicy size="10 MB" />
               </Policies>
              </RollingFile>
            </Route>
        </Routes>
      </Routing>
</Appenders>
<Loggers>
    <Root level="trace">
       <appender-ref ref="RoutingAppender" level="info"/>
    </Root>
    <Logger name="AuditNippin" level="info" >
        <AppenderRef ref="myRoutingAppender"/>
    </Logger>
</Loggers>
</Configuration>

Here is the java code:

package be.myApp;
public class myClass{
    private static final org.apache.logging.log4j.core.Logger AUDITLOGGER =  
            (org.apache.logging.log4j.core.Logger) org.apache.logging.log4j.LogManager.getLogger("myRoutingAppender");

    public void doSomething(){
        ThreadContext.put("FlowName", "MyFlow");
        AUDITLOGGER.info("coucou");
        ThreadContext.remove("FlowName");
    }
}

This creates the file correctly depending on the context. But write nothing in the log file.

Upvotes: 3

Views: 2228

Answers (1)

D.B.
D.B.

Reputation: 4713

First of all you have syntax issues in your log4j2 XML:

<pattern />

This should be </pattern>

<AppenderRef ref="myRoutingAppender" />

This should be: <AppenderRef ref="RoutingAppender" />

Also, since you're using a TimeBased Triggering Policy you must have a date pattern in your filePattern of your RollingFile appender. See the documentation for RollingFileAppender.

Finally, you probably do not want quotations in your pattern of your PatternLayout:

<pattern>"%m%n"<pattern/>

You probably meant: <pattern>%m%n<pattern/>

After fixing all of the above you should see logs in your log file, but only because it will get the root logger when the following code runs:

LogManager.getLogger("myRoutingAppender");

Since you have no logger with that name it's getting the root logger which will use the routing appender and write to the log file. My guess is you intended to call getLogger("AuditNippin") since that is the only named logger you specified in your config file.

Upvotes: 1

Related Questions