I’m not sure if there is a better way to handle script logging.
The annotations is for classes and you cannot apply it to your script class.
Another  disadvantage is that I don’t think you can use the logger in static 
methods.

What you can do is ‘override’ the groovy Script class (the class that your 
script is an instance of, kindof) by use the BaseScript annotation
Example:
Define your wrapper like this…

-bash-4.1$ cat MyScript.groovy
abstract class MyScript extends Script {
    java.util.logging.Logger log
    @Override def run () {
        log = java.util.logging.Logger.getLogger('')
        // any other startup stuff here….
        runMyScript()
      // any other shutdown stuff here…
    }
    abstract def runMyScript()
}

Note that I have added a script variable called log that you can then use in 
your script.

Then in your script do something like this…

@groovy.transform.BaseScript(MyScript)
import groovy.util.*
log.info 'hello'
log.severe 'hello'

sample run….

-bash-4.1$ groovy -Djava.util.logging.config.file=logging.properties test.groovy
Jan 8, 2016 11:53:04 AM java.util.logging.LogManager$RootLogger log
INFO: hello
Jan 8, 2016 11:53:04 AM java.util.logging.LogManager$RootLogger log
SEVERE: hello

The advantage here is that you can now add any other startup and shutdown code 
in the base script class’s run method.

From: Gerald Wiltse [mailto:[email protected]]
Sent: Friday, January 08, 2016 11:01 AM
To: [email protected]
Subject: @Log annotation inside Groovy Script

I just got @Log to work in some test classes, then learned that  @Log 
annotations do not work in scripts. Is this true? If so, is there some 
workaround that exists?  I assume this is true for all @annotations and 
scripts, so it seems pretty sad if there's no way to do it.

I'm basing that conclusion on this post, and my own error.
http://stackoverflow.com/questions/15981182/logging-in-groovy-script<https://urldefense.proofpoint.com/v2/url?u=http-3A__stackoverflow.com_questions_15981182_logging-2Din-2Dgroovy-2Dscript&d=BQMFaQ&c=_8VcuiJ--MukFqz6Sy5gel64o52_IbhiNdatg8Zb5Gs&r=X18JEC7WoH6AE_Xb-Yc-vOlw3Sre-zHIm9sFtf9hiJM&m=elRpgOr6t4A7M6hufAu_wLHNWUXEqqQZNu0dcjkJ7yg&s=VPldU_7pX8ccleusYK_YJ2P_Z9duECJ6fmtuy498rn8&e=>

If that is the case, maybe someone can help me with a solution :

Our use case is this:

Our scripts are launched on a scheduled basis by the JVM
Several class files are called throughout the execution of each script
For each execution, we want the script and any called classes to share one log
This means all logging configuration would have to be programmatic / dynamic

The hope is that the script can define the log based on variables at execution 
time, and then the classes will somehow "Inherit" the variable from the script 
that called it.

Does this seem possible?

Regards,
Jerry

Reply via email to