3

I'm using Logback and I want to log some strings to a log file and let it gzip the file when I'm done.

I was following the example of:

Programmatically configure LogBack appender

But haven't figured out how to, when I finish logging, tell it to gzip the file. All the examples show to use fileNamePattern. The examples I've seen show to to define this in logback.xml, but I'm trying to do this by code.

Would appreciate some pointers / examples for this :)

svarog
  • 9,477
  • 4
  • 61
  • 77
Guy Wald
  • 599
  • 1
  • 10
  • 25
  • Define "done". When do you need to gzip the file - what's the trigger? – Boris the Spider Jan 29 '14 at 10:03
  • I'm doing some operations on a file and when these operations fail I want to log the rest of the file. Once the file is finished I'm Done logging - The log file should be gzipped at this point. – Guy Wald Jan 29 '14 at 13:17
  • 1
    So am I right in thinking you define the appender on the fly when the processing fails? In which case just close the appender and zip the file yourself when you're done... – Boris the Spider Jan 29 '14 at 14:15

1 Answers1

4
<!-- Time and Size based: Roll every day and split big file in smaller peaces -->
<appender name="ROOT" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_HOME}/root.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${LOG_HOME}/root-%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
        <maxHistory>10</maxHistory>
    </rollingPolicy>
    <encoder>
        <pattern>%date %-5level [%thread] - %mdc{loginName} - [%logger]- %msg%n</pattern>
    </encoder>
</appender>

Notice the ".gz": this indicates that the logfile will be compressed. Replace this with .zip to use a zip-file.

There are some limitations, but is basically the easiest flow. The docs state.

Just like FixedWindowRollingPolicy, TimeBasedRollingPolicy supports automatic file compression. This feature is enabled if the value of the fileNamePattern option ends with .gz or .zip.

Dimitri Dewaele
  • 10,311
  • 21
  • 80
  • 127