Groovy Script and log4j

前端 未结 2 1814
长发绾君心
长发绾君心 2021-02-04 02:42

Been searching here and there looking for a working example of log4j logging to file in a Groovy script.

No explicit class (it\'s just a script). No grails. Not to conso

2条回答
  •  旧时难觅i
    2021-02-04 03:26

    Here's a simple example using @Grab to pull in the log4j lib, then using the inbuilt Groovy's @Log4j annotation to wire in a log variable.

    You can then configure your logger in the script and add a FileAppender

    @Grab('log4j:log4j:1.2.17')
    
    import org.apache.log4j.*
    import groovy.util.logging.*
    
    @Log4j
    class HelloWorld{
        def execute() {
            // Need to set log level as described here: 
            // http://groovy.329449.n5.nabble.com/log4j-annotation-not-working-td4368806.html
            log.level = Level.INFO
            // add an appender to log to file
            log.addAppender(new FileAppender(new TTCCLayout(), 'myscript.log'));
    
            // this will NOT print/write as the loglevel is info
            log.debug 'Execute HelloWorld.'
            // this will print
            log.info 'Simple sample to show log field is injected.'
        }
    }
    
    def helloWorld = new HelloWorld()
    helloWorld.execute()
    

    When run you'll see this in your myscript.log

        11 [main] INFO HelloWorld - Simple sample to show log field is injected.
    

    Unfortunately, the config.groovy file logger configuration is specific to Grails. Since you aren't in Grails, the DSL isn't there to interpret the log4j stuff. However take a look at ConfigSlurper in Groovy that looks like it will provide you a similar DSL to bring in your config.

提交回复
热议问题