一直在到处搜索,寻找一个在 Groovy 脚本中记录到文件的 log4j 工作示例。
没有明确的类(它只是一个脚本)。没有圣杯。不要安慰……要归档。
只是一个带有 log4j 的普通 groovy 脚本。
log4j 最适合这个(groovy)还是其他日志库更好?
有人可以指点我一个例子或演示这是如何完成的吗?我设法把它送到控制台,但没有归档。
如果 log4j 配置也在 config.groovy 文件中会很好,因为我正在使用配置文件来处理其他事情。
更新
感谢 neversleepz 示例,我可以很好地完成以下工作:
config.groovy 文件:
log4j {
appender.stdout = "org.apache.log4j.ConsoleAppender"
appender."stdout.layout"="org.apache.log4j.PatternLayout"
appender.scrlog = "org.apache.log4j.FileAppender"
appender."scrlog.layout"="org.apache.log4j.PatternLayout"
appender."scrlog.layout.ConversionPattern"="%d %5p %c{1}:%L - %m%n"
appender."scrlog.file"="rootscript.log"
rootLogger = "debug,scrlog,stdout"
}
还有我的脚本:
import org.apache.log4j.*
import groovy.util.logging.*
def config = new ConfigSlurper().parse(new File('config.groovy').toURL())
PropertyConfigurator.configure(config.toProperties())
Logger log = Logger.getInstance(getClass())
// Need to set log level as described here:
// http://groovy.329449.n5.nabble.com/log4j-annotation-not-working-td4368806.html
log.level = Level.INFO
// this will NOT print/write as the loglevel is info
log.debug 'Executing Script.'
// this will print
log.info 'Simple sample to show log INFO field is injected.'
log.warn 'Simple sample to show log WARN field is injected.'
log.error 'Simple sample to show log ERR field is injected.'
谢谢你!
我还为 RollingFileAppender 和 DailyRollingFileAppender 进行了配置,我也将它们放在这里:
log4j {
//
appender.stdout = "org.apache.log4j.ConsoleAppender"
appender."stdout.layout"="org.apache.log4j.PatternLayout"
//
appender.scrlog = "org.apache.log4j.DailyRollingFileAppender"
appender."scrlog.DatePattern"="'.'yyyy-MM-dd"
appender."scrlog.Append"="true"
appender."scrlog.File"="rootscript.log"
appender."scrlog.layout"="org.apache.log4j.PatternLayout"
appender."scrlog.layout.ConversionPattern"="%d %5p %c{1}:%L - %m%n"
rootLogger="debug,scrlog,stdout"
}
和
log4j {
//
appender.stdout = "org.apache.log4j.ConsoleAppender"
appender."stdout.layout"="org.apache.log4j.PatternLayout"
//
appender.scrlog = "org.apache.log4j.DailyRollingFileAppender"
appender."scrlog.DatePattern"="'.'yyyy-MM-dd"
appender."scrlog.Append"="true"
appender."scrlog.File"="rootscript.log"
appender."scrlog.layout"="org.apache.log4j.PatternLayout"
appender."scrlog.layout.ConversionPattern"="%d %5p %c{1}:%L - %m%n"
rootLogger="debug,scrlog,stdout"
logger.ProcessLogger="debug,scrlog"
}