groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Nelson, Erick [HDS]" <>
Subject RE: @Log annotation inside Groovy Script
Date Fri, 08 Jan 2016 19:55:45 GMT
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
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….
      // 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…

import groovy.util.* 'hello'
log.severe 'hello'

sample run….

-bash-4.1$ groovy 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 []
Sent: Friday, January 08, 2016 11:01 AM
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.<>

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?


View raw message