...
Below is an example of how you could configure Log4j with a ConfigSlurper script:
| Code Block |
|---|
log4j.appender.stdout = "org.apache.log4j.ConsoleAppender"
log4j.appender."stdout.layout"="org.apache.log4j.PatternLayout"
log4j.rootLogger="error,stdout"
log4j.logger.org.springframework="info,stdout"
log4j.additivity.org.springframework=false
|
To load this into a readable config you can do:
| Code Block |
|---|
def config = new ConfigSlurper().parse(new File('myconfig.groovy').toURL())
assert "info,stdout" == config.log4j.logger.org.springframework
assert false == config.log4j.additivity.org.springframework
|
...
You can also use scoping in config scripts to avoid repeating yourself. So the above config could also be written as:
| Code Block |
|---|
log4j {
appender.stdout = "org.apache.log4j.ConsoleAppender"
appender."stdout.layout"="org.apache.log4j.PatternLayout"
rootLogger="error,stdout"
logger {
org.springframework="info,stdout"
}
additivity {
org.springframework=false
}
}
|
...
You can convert ConfigSlurper configs to and from Java properties files. For example:
| Code Block |
|---|
java.util.Properties props = // load from somewhere
def config = new ConfigSlurper().parse(props)
props = config.toProperties()
|
...
You can merge config objects so if you have multiple config files and want to create one central config object you can do:
| Code Block |
|---|
def config1 = new ConfigSlurper().parse(..)
def config2 = new ConfigSlurper().parse(..)
config1 = config1.merge(config2)
|
...
You can serialize a config object to disk. Each config object implements the groovy.lang.Writable interface that allows you to write out the config to any java.io.Writer:
| Code Block |
|---|
def config = new ConfigSlurper().parse(..)
new File("..").withWriter { writer ->
config.writeTo(writer)
}
|
...
Given this groovy property file:
| Code Block | ||||||
|---|---|---|---|---|---|---|
|
| |||||
sample {
foofoo = "default_foo"
barbar = "default_bar"
}
environments {
developmentdevelopment {
sample {
foo foo = "dev_foo"
}
}
testtest {
sample {
bar bar = "test_bar"
}
}
}
|
Here is the demo code that exercises this configuration:
| Code Block |
|---|
def config = new ConfigSlurper("development").parse(new File('Sample.groovy').toURL())
assert config.sample.foo == "dev_foo"
assert config.sample.bar == "default_bar"
config = new ConfigSlurper("test").parse(new File('Sample.groovy').toURL())
assert config.sample.foo == "default_foo"
assert config.sample.bar == "test_bar"
|
...
The value of the environment constructor is also available in the configuration file, allowing you to build the configuration like this:
| Code Block |
|---|
switch (environment) {
case 'development':
baseUrl = "devServer/"
break
case 'test':
baseUrl = "testServer/"
break
default:
baseUrl = "localhost/"
}
|
...