How to use SizeBasedTriggeringPolicy with TimeBasedRollingPolicy in Log4j?

Samurai picture Samurai · Sep 4, 2012 · Viewed 21.9k times · Source

Hi I am using Log4j for logging. Below is my configuration.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
xmlns:log4j='http://jakarta.apache.org/log4j/'>

<appender name="FileAppender_Comp3" class="org.apache.log4j.rolling.RollingFileAppender"> 

<rollingPolicy name="file" class="org.apache.log4j.rolling.TimeBasedRollingPolicy"> 
<param name="FileNamePattern" value="log/Comp3_%d{dd-MM-yyyy HH-mm-ss}.log" />
</rollingPolicy> 

<triggeringPolicy class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
<param name="MaxFileSize" value="3kb"/>
</triggeringPolicy>

<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %5p [%t] %c (%F:%L) - %m%n"/>
</layout>

</appender>

But when I am running file it is throwing below error.

log4j:WARN Failed to set property [maxFileSize] to value "3kb". 

How can I fix this. Please help me.

Answer

krishnakumarp picture krishnakumarp · Jul 3, 2015

If you are using Log4j 2, you can specify the size in KB or MB.

Relevant XML below.

<Policies>
    <!-- Starts a new log on tomcat start -->
    <OnStartupTriggeringPolicy /> 
    <!--  Starts a new file when size reaches threshold -->
    <SizeBasedTriggeringPolicy size="10 MB" /> 
    <!-- causes a rollover once the date/time pattern no longer 
       applies to the active file -->
    <TimeBasedTriggeringPolicy /> 
</Policies

Please see https://logging.apache.org/log4j/2.x/manual/appenders.html for more details.