Rolling log Files & removing old log files

user2377755 picture user2377755 · May 13, 2013 · Viewed 39.6k times · Source

I am working on a Java SOAP based webservice application where I am writing stdout to a text file as log for our reference. That file is growing enormously, so I need to check for the size of the file... For example if the file size crosses 10 Mb, I have to create another file.

Like this, I have to create 10 files, rotating one after the other until ten files. After reaching ten files, I have to delete the starting files and start creating again...

How can I delete files after the no. of files will become 10?

Answer

Robert H picture Robert H · May 13, 2013

I use logback to do this. The example below is a time based rolling policy. Depending upon how much data your outputting during your logs, this may work for you as-is.

Also, as a bonus, my config file tosses the log into HTML to make it easy to view for management types who want to look though the log file.

Relevant part of the config file:

 <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs\logFile.html</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <!-- daily rollover -- >
        <fileNamePattern>logs\logFile.%d{yyyy-MM-dd}.%i.html</fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy
            class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <!-- or whenever the file size reaches 10MB -- >
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
        <!-- keep 10 days' worth of history -- >
        <maxHistory>10</maxHistory>
    </rollingPolicy>

    <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
        <charset>UTF-8</charset>
        <layout class="ch.qos.logback.classic.html.HTMLLayout">
            <pattern>%d{HH:mm:ss.SSS}%thread%level%logger%line%msg</pattern>
        </layout>           
    </encoder>
</appender> 

<root level="DEBUG">
    <appender-ref ref="STDOUT" />
    <appender-ref ref="FILE" />
</root>

relevant Maven dependancies:

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.0.12</version>
    </dependency>

    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.0.12</version>
    </dependency>