简体   繁体   中英

log4j - RollingFileAppender - datepattern and MaxFileSize

I'm using log4j 1.x (with slf4j). I want to create rolling files when the MaxFileSize reaches 100KB or every minute, whichever comes first. However, with the following code, DatePattern is not working and it is not creating files every minute.

 <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
    <param name="File" value="${catalina.home}/logs/RollingFileAppender.log"/>
    <param name="Append" value="true"/>
    <param name="MaxBackupIndex" value="2"/>
    <param name="MaxFileSize" value="100KB"/>  
    <param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm"/>
    <param name="ConversionPattern" value="%d{yyyy-MM-dd}-%t-%x-%-5p-%-10c:%m%n" />
  </appender>

I even tried this, but in this scenario, it is not even creating any file. -

  <appender name="fileAppender" class="org.apache.log4j.rolling.RollingFileAppender">
    <rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
        <param name="ActiveFileName" value="${catalina.home}/logs/RollingFileAppender.log" />
        <param name="FileNamePattern" value="${catalina.home}/logs/RollingFileAppender.%d{dd-MMM}.log.gz" />
    </rollingPolicy>
    <triggeringPolicy
        class="org.apache.log4j.rolling.SizeBasedTriggeringPolicy">
        <param name="MaxFileSize" value="100KB" />
    </triggeringPolicy>
    <param name="ConversionPattern" value="%d{yyyy-MM-dd}-%t-%x-%-5p-%-10c:%m%n" />
</appender>

What would be the right way to fix this issue?

Seems like your XML file is incomplete, you need to attach your appender at the root tag with the desired logging level

<log4j:configuration debug="true"
    xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="fileAppender" class="org.apache.log4j.DailyRollingFileAppender">
       <param name="append" value="false" />
       <param name="maxFileSize" value="1000KB" />
       <param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm" />
       <param name="maxBackupIndex" value="2" />
       <param name="file" value="${catalina.home}/logs/RollingFileAppender.log" />
       <layout class="org.apache.log4j.PatternLayout">
           <param name="ConversionPattern" 
               value="%d{yyyy-MM-dd} %-5p %c{1}:%L - %m%n" />
       </layout>
    </appender>

    <root>
        <level value="ERROR" />
        <appender-ref ref="fileAppender" />
    </root>

</log4j:configuration>

I think what you are looking for is the DailyRollingFileAppender implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM