Friday 5 October 2012

Controlling what Log4J logs to a file

To control what goes into a log file, we can use the filtering mechanism that is provided by Log4J.

Filters operate in a stack, with a logging event being passed to the first filter in the stack. Each filter can deny (discard the event), accept (log the event) or remain neutral in which case the event is passed to the next filter in the stack.

Knowning this we can devise a filter stack that only logs events with specific keywords to a file, and all else is discarded.

 <appender name="PERFORMANCE" class="org.apache.log4j.FileAppender">  
      <param name="File" value="${xsp.log.dir}/performance-metrics.log"/>  
      <param name="Append" value="true"/>  
      <param name="Threshold" value="DEBUG"/>  
      <layout class="org.apache.log4j.PatternLayout">  
           <param name="ConversionPattern" value="%d{DATE} %-5p [%t] [%c{1}] %m%n"/>  
      </layout>  
      <filter class="org.apache.log4j.varia.StringMatchFilter">  
           <param name="StringToMatch" value="PERF" />  
           <param name="AcceptOnMatch" value="true"/>  
      </filter>  
      <filter class="org.apache.log4j.varia.DenyAllFilter" />  
 </appender>  

This appender will look for the keyword PERF and log only those events to a file called performance-metrics.log.

No comments:

Post a Comment