Groovy +将日志写入文件+使用注释注入日志

编程入门 行业动态 更新时间:2024-10-07 07:35:30
本文介绍了Groovy +将日志写入文件+使用注释注入日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建以下groovy脚本,以展示如何通过简单的注释将日志字段注入我们的类中

I create the following groovy script in order to show how to inject a log field into our classes with a simple annotation

// 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上)

when I run the groovy script I get the following results ( on 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脚本中才能启用它?

please advice how we can print the results to a log file in the WIN machine , and what need to add to my groovy script in order to enable that?

例如:

日志文件

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

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 +将日志写入文件+使用注释注入日志

本文发布于:2023-11-23 21:46:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622940.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:日志   注释   文件   Groovy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!