Groovy Script and log4j

前端 未结 2 1813
长发绾君心
长发绾君心 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条回答
  • 2021-02-04 03:12

    Another way to do this would be to use Groovy's logging package. You can use the same easily my importing the util logging and using the @Log annotation like in this example

    import groovy.util.logging.*
    
    @Log
    class Test{
        public class() {
            log.debug "Logging"
        }
    }
    

    However, since the annotation works on a class, you would need to create your groovy script inside a class. Free form scripts don't get the logger access this way.

    Hope this helps.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题