views:

988

answers:

3

I'm looking for a way to redirect output in a groovy script to stderr:

catch(Exception e) {
    println "Want this to go to stderr"
}
+3  A: 

Groovy has access to the JRE:

System.err.println("goes to stderr")

Although there may be a more Groovy-fied way...

Dan Vinton
Yep, I was hoping for a groovyish way.
timdisney
+3  A: 

Just off the top of my head couldn't you do a bit of self-wiring:

def printErr = System.err.&println
printErr("AHHH")

but that is a bit manual

codeLes
sfussenegger
A: 

If you just want something shorter to type, here are two options. First, you can import java.lang.System as anything you like, specifically something shorter like "sys":

import java.lang.System as sys
sys.err.println("ERROR Will Robinson")

Second, you can assign the System.err stream to a variable and use that variable from then on as an alias for System.err, like:

err = System.err
err.println("ERROR again Will Robinson")

This has the possible advantage that all the functions of System.err are accessible so you don't have to wire up each one individually (e.g. err.print, err.println, etc.).

Hopefully there is a standard Groovy way, because idiosyncratic renaming can be confusing to people who read your code.