Hi normally in Log4j priority levels are as follows
Can we change this priority levels. My requirement is I need to log only details which have priority level INFO and FATAL. Logs with priority level DEBUG, WARN and ERROR shouldn't log. If I can change the priority levels as
it is possible. Or is there any other way to do that. Pls help..
I was never needed to do this, but since I have once read Log4J - The Complete Manual, I hope these pointers will help.
Write following logic in decide
if(event.getLevel() == Level.INFO || event.getLevel() == Level.FATAL)
return ACCEPT;
return DENY;
This filter will accept all the logs that are either INFO or FATAL. You may get more creative.
Please note that I have not tested this code. This is just a guideline, hope this helps
Edit: on a bit search, I found something that might be easier. I guess, You can use LevelMatchFilter, this way
<filter class="org.apache.log4j.varia.LevelMatchFilter">
<param name="LevelToMatch" value="info" />
<param name="AcceptOnMatch" value="true" />
</filter>
<filter class="org.apache.log4j.varia.LevelMatchFilter">
<param name="LevelToMatch" value="fatal" />
<param name="AcceptOnMatch" value="true" />
</filter>
<filter class="org.apache.log4j.varia.DenyAllFilter"/>
refer: http://wiki.apache.org/logging-log4j/Log4jXmlFormat for XML configurarion. There is a section on Filter Configuration
I don't know what stops OP in accepting this answer. I've just tested, it works:
Here is the XML.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="util" class="org.apache.log4j.FileAppender">
<param name="File" value="D:/util.log" />
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%t %-5p %c{2} - %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelMatchFilter">
<param name="LevelToMatch" value="info" />
<param name="AcceptOnMatch" value="true" />
</filter>
<filter class="org.apache.log4j.varia.LevelMatchFilter">
<param name="LevelToMatch" value="fatal" />
<param name="AcceptOnMatch" value="true" />
</filter>
<filter class="org.apache.log4j.varia.DenyAllFilter"/>
</appender>
<root>
<priority value ="debug" />
<appender-ref ref="util" />
</root>
</log4j:configuration>
Here is the Java code
DOMConfigurator.configure("log4j.xml");
Logger log = Logger.getLogger(Test.class);
log.debug("DEBUG");
log.info("INFO");
log.warn("WARN");
log.error("ERROR");
log.fatal("FATAL");
Here is the output in (as configured) D:/util.log
main INFO test.Test - INFO
main FATAL test.Test - FATAL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With