I am writing a simple Groovy application that needs to do some logging. The actual properties of how things are logged will depend on the particular environment. For instanc
Building on tim_yates's answer, use a groovy file to configure log4j. For example:
// log4j.groovy
log4j {
rootLogger="DEBUG, A1"
appender.A1 = "org.apache.log4j.ConsoleAppender"
appender.'A1.layout' = "org.apache.log4j.PatternLayout"
if (System.properties['env'] == 'prod') {
appender.'A1.layout.ConversionPattern'="prod %-4r [%t] %-5p %c %x - %m%n"
} else {
appender.'A1.layout.ConversionPattern'="dev %-4r [%t] %-5p %c %x - %m%n"
}
}
Then make your script use it:
@GrabConfig(systemClassLoader=true)
@Grab(group='log4j', module='log4j', version='1.2.17')
import groovy.util.logging.Log4j
import org.apache.log4j.PropertyConfigurator
@Log4j
class Test {
def dosome() {
log.info('Logging!')
}
static main( args ) {
def config = new ConfigSlurper().parse(new File('log4j.groovy').toURL())
PropertyConfigurator.configure(config.toProperties())
new Test().dosome()
}
}
And finally, launch your program with the environment in a system property:
groovy -Denv=prod Test.groovy
You should be able to simply put a log4j.properties
file on your classpath.
Given this test script:
@groovy.util.logging.Log4j
class Test {
def dosome() {
log.info( 'Logging!' )
}
static main( args ) {
new Test().dosome()
}
}
If I run it from the command line:
groovy -cp log4j-1.2.17.jar Test.groovy
it doesn't print anything as it isn't set up to log INFO messages by default.
However, if I write a log4j.properties file (taken from the docs for log4j and altered to log ):
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
# Print the date in ISO 8601 format
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
Then run it again with this properties file in the classpath:
groovy -cp log4j.properties:log4j-1.2.17.jar Test.groovy
We get:
2012-07-16 16:08:47,524 [main] INFO Test - Logging!