Configuring Logback

At startup Logback checks if there is a configuration file in the application classpath. First choice is logback.groovy, logback-test.xml and logback.xml are the fallback options. If none of these files is available, a default configuration is used, and the output is sent to standard console.

Here is an XML configuration file that would give a result close to the default.:
<configuration>
    <appender name="CApp" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{12}: %msg%n</pattern>
        </encoder>
    </appender>
    <root level="trace">
        <appender-ref ref="CApp" />
    </root>
</configuration>
The appender element describes a logging destination. Here the standard output console is used.
In the appender element is defined its associated encoder, where we define the pattern we want to use in the log generation.
The pattern describes a string where the first field is the time of current log line generation, the second is the thread name where the log was generated, the third is the log level, fourth is the logger name (with the max number of significative character that should be used - twelve is unreasonable low, but it could make sense in such a silly test). Finally we have the log message itself and a newline. The resulting pattern is very close to the default one.
The root element describes the root logger, that has a log level set to trace (instead of the default debug). The appender element inside root is where we can specify which appender (here CApp) should be used in this context.

It is easy to rewrite the same configuration with Groovy:
appender("CApp", ch.qos.logback.core.ConsoleAppender) {
    encoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) {
        pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{12}: %msg%n"
    }
}
root(ch.qos.logback.classic.Level.TRACE, ["CApp"])
Similar structure, less verbose, and much more flexibility. The only issue is that we need Groovy in the application classpath.

No comments:

Post a Comment