Groovy + 将日志写入文件 + 使用注解注入(inject)日志

标签 groovy

我创建了以下 groovy 脚本,以展示如何使用简单的注释将日志字段注入(inject)到我们的类中

// File: LogSlf4j.groovy
// Add dependencies for Slf4j API and Logback

@Grapes([

       @Grab(group='org.slf4j', module='slf4j-api', version='1.6.1'),
       @Grab(group='ch.qos.logback', module='logback-classic', version='0.9.28')
])

 import org.slf4j.*
 import groovy.util.logging.Slf4j

 // Use annotation to inject log field into the class.
 @Slf4j

 class faimily{

 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 faimily()
 helloWorld.father()
 helloWorld.mother()

当我运行 groovy 脚本时,我得到以下结果(在 GROOVY CONSOLE 上)

 17:58:50.938 [Thread-59] DEBUG faimily - car engine is hot
 17:58:50.938 [Thread-59] ERROR faimily - my car is stuck
 17:58:50.938 [Thread-59] DEBUG faimily - dont have a water in the kitchen
 17:58:50.938 [Thread-59] ERROR faimily - Cant make a cake

请建议我们如何将结果打印到 WIN 机器的日志文件中,以及需要添加什么到我的 groovy 脚本中才能启用它?

例如:

日志文件

C:\Program Files\LOGS\my.groovy.log

(应包含结果:)

 17:58:50.938 [Thread-59] DEBUG faimily - car engine is hot
 17:58:50.938 [Thread-59] ERROR faimily - my car is stuck
 17:58:50.938 [Thread-59] DEBUG faimily - dont have a water in the kitchen
 17:58:50.938 [Thread-59] ERROR faimily - Cant make a cake

最佳答案

这对我有用:

@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()

关于Groovy + 将日志写入文件 + 使用注解注入(inject)日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24412464/

相关文章:

list - 如何获取grails中的复选框列表

Grails 配置文件返回空对象而不是字符串

groovy - 在 Groovy 中有没有办法装饰每个类以添加跟踪?

java - 当我在 groovy 中使用正则表达式替换时,如何解决 java.lang.StackOverflowError 问题?

groovy - 如何从 Gradle 0.6 引用类路径

unit-testing - Grails-表ID默认为不能为null还是可以?

performance - Grails中的交易价格如何?

groovy - Gradle - 如何将过滤器提取到单独的可重用函数?

perl - 将 CruiseControl 转换为 Hudson

groovy - Groovy 幂运算符 (**) 的结合性是否被破坏?