Search

Dark theme | Light theme

August 26, 2015

Show Logback Configuration Status with Groovy Configuration

Logback is a SLF4J API implementation for logging messages in Java and Groovy. We can configure Logback with a Groovy configuration file. The file is a Groovy script and allows for a nice an clean way (no XML) to configure Logback. If we want to show the logging configuration and see how Logback is configured we must add a StatusListener implementation in our configuration. The StatusListener implementation prints out the configuration when our application starts. Logback provides a StatusListener for outputting the information to system out or system error streams (OnConsoleStatusListener and OnErrorConsoleStatusListener). If we want to disable any status messages we use the NopStatusListener class.

In the following example configuration file we define the status listener with the statusListener method. We use the OnConsoleStatusListener in our example:

// Add status listener, which prints out
// the Logback configuration on application
// startup.
statusListener(OnConsoleStatusListener)

appender('SystemOut', ConsoleAppender) {
    // Enable coloured output.
    withJansi = true

    encoder(PatternLayoutEncoder) {
        pattern = "%blue(%-5level) %green(%logger{35}) - %msg %n"
    }
}

root(DEBUG, ['SystemOut'])

If we run our Java or Groovy application with this configuration we get the following information in our console:

    09:31:09,143 |-INFO in ch.qos.logback.classic.gaffer.ConfigurationDelegate@3b0f5da3 - Added status listener of type [ch.qos.logback.core.status.OnConsoleStatusListener]
    09:31:09,167 |-INFO in ch.qos.logback.classic.gaffer.ConfigurationDelegate@3b0f5da3 - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]
    09:31:09,168 |-INFO in ch.qos.logback.classic.gaffer.ConfigurationDelegate@3b0f5da3 - Naming appender as [SystemOut]
    09:31:09,239 |-INFO in ch.qos.logback.classic.gaffer.ConfigurationDelegate@3b0f5da3 - Setting level of logger [ROOT] to DEBUG
    09:31:09,244 |-INFO in ch.qos.logback.classic.gaffer.ConfigurationDelegate@3b0f5da3 - Attaching appender named [SystemOut] to Logger[ROOT]

Alternatively we can use the Java system property logback.statusListenerClass when we run our application. We must provide the full class name for the StatusListener implementation. This will overrule any status listeners that are defined in configuration files.

Written with Logback 1.1.3.