Chapter 12: Groovy Configuration

It is better to be a human being dissatisfied than a pig satisfied; better to be a Socrates dissatisfied than a fool satisfied. And if the fool or the pig thinks otherwise, it is because they have no experience of the better part.

—JOHN STUART MILL, Utilitarianism

Domains-specific languages are rather pervasive. The XML-based logback configuration can be viewed as an example DSL. By the very nature of XML, XML-based configuration files are quite verbose and bulky. Moreover, a relatively large body of code in logback, namely Joran, is dedicated to processes these XML-based configuration files. Joran supports nifty features such as variable substitution, conditional processing and on-the-fly extensibility. However, not only Joran is a complex beast, the user-experience it provides can be described as unsatisfactory or at the very least unintuitive.

The Groovy-based DSL described in this chapter aims to be consistent, intuitive, and powerful. Everything you can do XML in configuration files, you can do in Groovy with a much shorter syntax. To help you migrate to Groovy style configuration, we have developped a tool to automatically migrate your logback.xml files to logback.groovy.

General philosophy

As a general rule, logback.groovy files are groovy programs. And since groovy is a super-set of Java, whatever configuration actions you can perform in Java, you can do the same within a logback.groovy file. However, since configuring logback progammatically using Java syntax can be very cumbersome, we added a few logback-specific extensions to make your life easier. We limited the number of such logback-specific extensions to an absolute minimum. If you are already familiar with groovy, you should be able to read, understand and even write your own logback.groovy files with great ease. Those unfamiliar with Groovy should still find logback.groovy syntax much more comfortable to use than logback.xml.

Logback.groovy syntax consists of 6 methods described next in their customary order of appearance. Strictly speaking the order of invocation of the methods does matter except that appenders MUST be defined before they can be attached to a logger.

scan(String scanPeriodStr = null) method

Invoking the scan() method instructs logback to periodically scan the logback.groovy file for changes. Whenever a change is detected, the logback.groovy file is reloaded.

statusListener(Class listenerClass)

conversionRule(String conversionWord, Class converterClass)

root(Level level, List appenderNames = [])

logger(String name, Level level, List appenderNames = [], Boolean additivity = null)

appender(String name, Class clazz, Closure closure = null)