3. Configuration

It may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now, but since what configuration there is typically a one off, it is best to get it out the way.

With Grails' default settings you can actually develop and application without doing any configuration whatsoever. Grails ships with an embedded container and in-memory HSQLDB meaning there isn't even a database to set-up.

However, typically you want to set-up a real database at some point and the way you do that is described in the following section.

3.1 Basic Configuration

For general configuration Grails provides a file called grails-app/conf/Config.groovy. This file uses Groovy's ConfigSlurper which is very similar to Java properties files except it is pure Groovy hence you can re-use variables and use proper Java types!

You can add your own configuration in here, for example:

foo.bar.hello = "world"

Then later in your application you can access these settings in one of two ways. The most common is via the GrailsApplication object, which is available as a variable in controllers and tag libraries:

assert "world" == grailsApplication.config.foo.bar.hello

The other way involves getting a reference to the ConfigurationHolder class that holds a reference to the configuration object:

import org.codehaus.groovy.grails.commons.*
def config = ConfigurationHolder.config
assert "world" == config.foo.bar.hello

3.1.1 Built in options

Grails also provides the following configuration options:

War generation

For more information on using these options, see the section on deployment

3.1.2 Logging

Logging Basics

Grails uses its common configuration mechanism to configure the underlying Log4j log system. To configure logging you must modify the file Config.groovy located in the grails-app/conf directory.

This single Config.groovy file allows you to specify separate logging configurations for development, test, and production environments. Grails processes the Config.groovy and configures Log4j appropriately.

Since 1.1 Grails provides a Log4j DSL, that you can use to configure Log4j an example of which can be seen below:

log4j = {
    error  'org.codehaus.groovy.grails.web.servlet',  //  controllers
	       'org.codehaus.groovy.grails.web.pages' //  GSP

warn 'org.mortbay.log' }

Essentially, each method translates into a log level and you can pass the names of the packages you want to log at that level as arguments to the method.

Some useful loggers include:

The Root Logger

The Root logger is the logger that all other loggers inherit from. You can configure the Root logger using the root method:

root {
    additivity = true

The above example configures the root logger to log messages at the error level and above to the default standard out appender. You can also configure the root logger to log to one or more named appenders:

appenders {
	file name:'file', file:'/var/logs/mylog.log'
root {
    debug 'stdout', 'file'
    additivity = true

Here the root logger will log to two appenders - the default 'stdout' appender and a 'file' appender.

You can also configure the root logger from the argument passed into the Log4J closure:

log4j = { root ->
    root.level = org.apache.log4j.Level.DEBUG
The closure argument "root" is an instance of org.apache.log4j.Logger , so refer to the API documentation for Log4J to find out what properties and methods are available to you.

Custom Appenders

Using the Log4j you can define custom appenders. The following appenders are available by default:

For example to configure a rolling file appender you can do:

log4j = {
	appenders {
		rollingFile name:"myAppender", maxFileSize:1024, fileName:"/tmp/logs/myApp.log"

Each argument passed to the appender maps to a property of underlying Appender class. The example above sets the name, maxFileSize and fileName properties of the RollingFileAppender class.

If you prefer to simply create the appender programmatically yourself, or you have your own appender implementation then you can simply call the appender method and appender instance:

import org.apache.log4j.*

log4j = { appenders { appender new RollingFileAppender(name:"myAppender", maxFileSize:1024, fileName:"/tmp/logs/myApp.log") } }

You can then log to a particular appender by passing the name as a key to one of the log level methods from the previous section:

error myAppender:"org.codehaus.groovy.grails.commons"

Custom Layouts

By default the Log4j DSL assumes that you want to use a PatternLayout. However, there are other layouts available including:

You can specify custom patterns to an appender using the layout setting:

log4j = {
	appenders {
        console name:'customAppender', layout:pattern(conversionPattern: '%c{2} %m%n')

This also works for the built-in appender "stdout", which logs to the console:

log4j = {
    appenders {
        console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')

Full stacktraces

When exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals. Grails filters these typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.

When this happens, the full trace is always written to the StackTrace logger. This logs to a file called stacktrace.log - but you can change this in your Config.groovy to do anything you like. For example if you prefer full stack traces to go to standard out you can add this line:

error stdout:"StackTrace"

You can completely disable stacktrace filtering by setting the grails.full.stacktrace VM property to true:

grails -Dgrails.full.stacktrace=true run-app

Logging by Convention

All application artefacts have a dynamically added log property. This includes domain classes, controllers, tag libraries and so on. Below is an example of its usage:

def foo = "bar"
log.debug "The value of foo is $foo"

Logs are named using the convention grails.app.<artefactType>.ClassName. Below is an example of how to configure logs for different Grails artefacts:

log4j = {
	// Set level for all application artefacts
	info "grails.app"
	// Set for a specific controller
	debug "grails.app.controller.YourController"
	// Set for a specific domain class
	debug "grails.app.domain.Book"
	// Set for all taglibs
	info "grails.app.tagLib"


The artefacts names are dictated by convention, some of the common ones are listed below:

3.2 Environments

Per Environment Configuration

Grails supports the concept of per environment configuration. Both the Config.groovy file and the DataSource.groovy file within the grails-app/conf directory can take advantage of per environment configuration using the syntax provided by ConfigSlurper As an example consider the following default DataSource definition provided by Grails:

dataSource {
    pooled = false                          
    driverClassName = "org.hsqldb.jdbcDriver"	
    username = "sa"
    password = ""				
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'createeate-drop','update'
            url = "jdbc:hsqldb:mem:devDB"
    test {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:mem:testDb"
    production {
        dataSource {
            dbCreate = "update"
            url = "jdbc:hsqldb:file:prodDb;shutdown=true"

Notice how the common configuration is provided at the top level and then an environments block specifies per environment settings for the dbCreate and url properties of the DataSource. This syntax can also be used within Config.groovy.

Packaging and Running for Different Environments

Grails' command line has built in capabilities to execute any command within the context of a specific environment. The format is:

grails [environment] [command name]

In addition, there are 3 preset environments known to Grails: dev, prod, and test for development, production and test. For example to create a WAR for the test environment you could do:

grails test war

If you have other environments that you need to target you can pass a grails.env variable to any command:

grails -Dgrails.env=UAT run-app

Programmatic Environment Detection

Within your code, such as in a Gant script or a bootstrap class you can detect the environment using the Environment class:

import grails.util.Environment


switch(Environment.current) { case Environment.DEVELOPMENT: configureForDevelopment() break case Environment.PRODUCTION: configureForProduction() break }

3.3 The DataSource

Since Grails is built on Java technology to set-up a data source requires some knowledge of JDBC (the technology that doesn't stand for Java Database Connectivity).

Essentially, if you are using another database other than HSQLDB you need to have a JDBC driver. For example for MySQL you would need Connector/J

Drivers typically come in the form of a JAR archive. Drop the JAR into your projects lib directory.

Once you have the JAR in place you need to get familiar Grails' DataSource descriptor file located at grails-app/conf/DataSource.groovy. This file contains the dataSource definition which includes the following settings:

A typical configuration for MySQL may be something like:

dataSource {
	pooled = true
	dbCreate = "update"
	url = "jdbc:mysql://localhost/yourDB"
	driverClassName = "com.mysql.jdbc.Driver"
	username = "yourUser"
	password = "yourPassword"	

When configuring the DataSource do not include the type or the def keyword before any of the configuration settings as Groovy will treat these as local variable definitions and they will not be processed. For example the following is invalid:

dataSource {
	boolean pooled = true // type declaration results in local variable

3.3.1 DataSources and Environments

The previous example configuration assumes you want the same config for all environments: production, test, development etc.

Grails' DataSource definition is "environment aware", however, so you can do:

dataSource {
	// common settings here
environments {
  production {
     dataSource {
          url = "jdbc:mysql://liveip.com/liveDb"					

3.3.2 JNDI DataSources

Since many Java EE containers typically supply DataSource instances via the Java Naming and Directory Interface (JNDI). Sometimes you are required to look-up a DataSource via JNDI.

Grails supports the definition of JNDI data sources as follows:

dataSource {
    jndiName = "java:comp/env/myDataSource"

The format on the JNDI name may vary from container to container, but the way you define the DataSource remains the same.

3.3.3 Automatic Database Migration

The dbCreate property of the DataSource definition is important as it dictates what Grails should do at runtime with regards to automatically generating the database tables from GORM classes. The options are:

Both create-drop and create will destroy all existing data hence use with caution!

In development mode dbCreate is by default set to "create-drop":

dataSource {
	dbCreate = "create-drop" // one of 'create', 'create-drop','update'

What this does is automatically drop and re-create the database tables on each restart of the application. Obviously this may not be what you want in production.

Although Grails does not currently support Rails-style Migrations out of the box, there are currently three plugins that provide similar capabilities to Grails: Autobase (http://wiki.github.com/RobertFischer/autobase), The LiquiBase plugin and the DbMigrate plugin both of which are available via the grails list-plugins command

3.4 Externalized Configuration

The default configuration file Config.groovy in grails-app/conf is fine in the majority of cases, but there may be circumstances where you want to maintain the configuration in a file outside the main application structure. For example if you are deploying to a WAR some administrators prefer the configuration of the application to be externalized to avoid having to re-package the WAR due to a change of configuration.

In order to support deployment scenarios such as these the configuration can be externalized. To do so you need to point Grails at the locations of the configuration files Grails should be using by adding a grails.config.locations setting in Config.groovy:

grails.config.locations = [ "classpath:${appName}-config.properties",

In the above example we're loading configuration files (both Java properties files and ConfigSlurper configurations) from different places on the classpath and files located in USER_HOME.

Ultimately all configuration files get merged into the config property of the GrailsApplication object and are hence obtainable from there.

Grails also supports the concept of property place holders and property override configurers as defined in Spring For more information on these see the section on Grails and Spring

3.5 Versioning

Versioning Basics

Grails has built in support for application versioning. When you first create an application with the create-app command the version of the application is set to 0.1. The version is stored in the application meta data file called application.properties in the root of the project.

To change the version of your application you can run the set-version command:

grails set-version 0.2

The version is used in various commands including the war command which will append the application version to the end of the created WAR file.

Detecting Versions at Runtime

You can detect the application version using Grails' support for application metadata using the GrailsApplication class. For example within controllers there is an implicit grailsApplication variable that can be used:

def version = grailsApplication.metadata['app.version']

If it is the version of Grails you need you can use:

def grailsVersion = grailsApplication.metadata['app.grails.version']

or the GrailsUtil class:

import grails.util.*
def grailsVersion = GrailsUtil.grailsVersion