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 instance, while developing I just want to log to the console, in test and production I may want to write to a file and in production I may want to send email for the most severe events.
Right now what I am doing looks like this:
import org.apache.log4j.Logger
import org.apache.log4j.PropertyConfigurator
class BaseClass {
protected config
static Logger logger = Logger.getLogger(BaseClient.class)
def BaseClass(env) {
def configFilePath = // whatever
config = new JsonSlurper().parseText(configFile.text)[options.env]
def logConfigFilePath = ['somelogdir', config.log_file].join(File.separator)
PropertyConfigurator.configure(logConfigFilePath)
}
}
and then all my classes that need to do logging inherit from BaseClass.
In this way, I can specify a different filename for each environment, and I get to read the logging configuratio from there. But it seems a lot of boilerplate, and forces me to use a hierarchy that may not be ideal.
On the other hand, here I see that I can obtain a logger with a simple annotation.
Is there a way to get different loggers depending on the environment – which may be set at runtime?
Building on tim_yates’s answer, use a groovy file to configure log4j. For example:
Then make your script use it:
And finally, launch your program with the environment in a system property: