GROOVY + Slf4j +旋转和备份日志文件

时间:2014-06-26 16:58:18

标签: java groovy slf4j logback

以下groovy脚本通过 Slf4j

生成 C:\ tmp \ groovy.log 日志文件 每次我们使用log.info/log.debug等时,

groovy脚本工作正常,日志增加

但问题是当日志文件容量巨大且每天日志变得更大时

我想知道如何在我的脚本中添加旋转机制的功能

例如我需要的是当日志文件变为100K时,然后日志将像zip文件一样备份(它会将容量减少到例如10K)

有可能吗?

如果是,请建议如何更改groovy脚本以提供备份功能

@Grab('org.slf4j:slf4j-api:1.6.1')
@Grab('ch.qos.logback:logback-classic:0.9.28')

import org.slf4j.*
import groovy.util.logging.Slf4j
import ch.qos.logback.core.*
import ch.qos.logback.classic.encoder.*

// Use annotation to inject log field into the class.
@Slf4j
class Family {
    static {
        new FileAppender().with {
            name = 'file appender'
            file = 'C:\\tmp\\groovy.log'
            context = LoggerFactory.getILoggerFactory()
            encoder = new PatternLayoutEncoder().with {
                context = LoggerFactory.getILoggerFactory()
                pattern = "%date{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n"
                start()
                it
            }
            start()
            log.addAppender(it)
        }
    }

    def father() {
        log.debug 'car engine is hot'
        log.error 'my car is stuck'
    }

    def mother() {
        log.debug 'dont have a water in the kitchen'
        log.error 'Cant make a cake'
    }
}

def helloWorld = new Family()
helloWorld.father()
helloWorld.mother()

1 个答案:

答案 0 :(得分:0)

您可以尝试使用RollingFileAppender代替FileAppender并设置所需的RollingPolicy。即你可以尝试:

...
@Slf4j
class Family {
    static {
        new RollingFileAppender().with {
            name = 'file appender'
            file = 'C:\\tmp\\groovy.log'
            // the policy to roll files
            rollingPolicy = new TimeBasedRollingPolicy().with{
                context = LoggerFactory.getILoggerFactory()
                // file name pattern for the rolled files
                fileNamePattern = 'C:\\tmp\\groovy.%date{yyyy-MM-dd}.%i.log'
                // the maximum number of files to be keeped.
                maxHistory = 10
                timeBasedFileNamingAndTriggeringPolicy = new SizeAndTimeBasedFNATP().with{
                    context = LoggerFactory.getILoggerFactory()
                    // the max size of each rolled file
                    maxFileSize = '3MB'
                }
            }
            context = LoggerFactory.getILoggerFactory()
            encoder = new PatternLayoutEncoder().with {
                context = LoggerFactory.getILoggerFactory()
                pattern = "%date{HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n"
                start()
                it
            }
            start()
            log.addAppender(it)
        }
    }

...

希望这有帮助,