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">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="LogFile" fileName="myapp.log">
<PatternLayout
pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
<File name="AuditFile" fileName="myapp-audit.log">
<PatternLayout
pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
</appenders>
<loggers>
<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 -->
</root>
</loggers>
</configuration>
source to share
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">
<PatternLayout
pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%nZ" />
<Filters>
<!-- 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"/>
</Filters>
</File>
source to share
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" />
</Logger>
Or you can use RoutingAppender (you can use something other than ThreadContext
):
ThreadContext.put("ROUTINGFLAG", "audit");
log.info("...");
ThreadContext.remove("ROUTINGFLAG");
in xml:
...
<Routing name="Routing">
<Routes pattern="$${ctx:ROUTINGFLAG}">
<Route AppenderRef="LogFile"/>
<Route AppenderRef="AuditFile" key="audit"/>
</Routes>
</Routing>
</Appenders>
<Loggers>
<Root level="debug">
<Appender-ref ref="Console" level="debug"/>
<AppenderRef ref="Routing" level="info"/>
</Root>
</Loggers>
source to share