How to log only one level with log4j2?

I am using log4j2 in my application.

What I want is all it takes for "debugging" to go to the console, everything before "info" to go to myapp.log and ONLY "info" to go to "myapp-audit.log".

The reason is that INFO mostly consists of successful data modifications (eg, "user", "updated user", "user deleted", etc.). If it really is a data change audit trail.

But I cannot figure out how to do this.

How do I get ONLY the "myapp-audit.log" login "info"? Here's my current config ...

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />

        <File name="LogFile" fileName="myapp.log">
                pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />

        <File name="AuditFile" fileName="myapp-audit.log">
                pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />

        <root level="debug">
            <appender-ref ref="Console" level="debug" />
            <appender-ref ref="LogFile" level="info" />
            <appender-ref ref="AuditFile" level="info" /> <!-- I want ONLY 'info' here -->



source to share

2 answers

If you specify INFO in appender-ref, the application will receive INFO, WARN, ERROR and FATAL. You can limit only INFO by filtering out WARN, ERROR and FATAL events:

<File name="AuditFile" fileName="myapp-audit.log">
       pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%nZ" />

        <!-- First deny warn, error and fatal messages -->
        <ThresholdFilter level="warn"  onMatch="DENY" onMismatch="NEUTRAL"/>
        <ThresholdFilter level="error" onMatch="DENY" onMismatch="NEUTRAL"/>
        <ThresholdFilter level="fatal" onMatch="DENY" onMismatch="NEUTRAL"/>

        <!-- Then accept info, warn, error, fatal and deny debug/trace -->
        <ThresholdFilter level="info"  onMatch="ACCEPT" onMismatch="DENY"/>




You cannot do this directly, since the level info

includes everything "above" - ​​warning, error, fatal. You can create a separate audit trail.

in the class:

Logger log = LogManager.getLogger("audit");


in xml:

<Logger name="audit" level="info">
   <Appender-ref ref="AuditFile" level="info" />


Or you can use RoutingAppender (you can use something other than ThreadContext


ThreadContext.put("ROUTINGFLAG", "audit");"...");


in xml:

    <Routing name="Routing">
        <Routes pattern="$${ctx:ROUTINGFLAG}">
            <Route AppenderRef="LogFile"/>              
            <Route AppenderRef="AuditFile" key="audit"/>                  
    <Root level="debug">
        <Appender-ref ref="Console" level="debug"/>
        <AppenderRef ref="Routing" level="info"/>




All Articles