Monday, September 12, 2011


Reasons to prefer Logback over Log4j:


·         Gradle dependency:

compile("ch.qos.logback:logback-classic:0.9.29")  // transitively includes"ch.qos.logback:logback-core:0.9.29" and"org.slf4j:slf4j-api:1.6.2"

·         Add logback.groovy to classpath (e.g. src/main/resources)

import ch.qos.logback.classic.encoder.PatternLayoutEncoder

import ch.qos.logback.core.status.OnConsoleStatusListener


import static ch.qos.logback.classic.Level.DEBUG


// We highly recommended that you always add a status listener just after the last import statement and before all other statements



def bySecond = timestamp("yyyyMMdd'T'HHmmss")


appender("FILE", FileAppender) {

  file = "log-${bySecond}.txt"

  encoder(PatternLayoutEncoder) {

    pattern = "%logger{35} - %msg%n"



root(DEBUG, ["FILE"])

·         If Groovy is not available in the current classpath, logback will have this error:ERROR in ch.qos.logback.classic.LoggerContext[default] - Groovy classes are not available on the class path. ABORTING INITIALIZATION.

o   (found by doing: logger.getLoggerContext().getStatusManager().getCopyOfStatusList())

·         Or, use logback.xml

<configuration scan="true">

    <!-- OPTIONAL: If logging is playing up, enable this and look for ch.qos.logback.* WARN/ERROR -->

    <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener"/>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">

        <!-- See -->

        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">



        <!-- Prudent mode provides safety when multiple JVMs are writing to the log file at the same time.

             See -->



            <!-- For pattern syntax see -->

            <pattern>%level %date [%thread] %logger{40} [%file:%line] %msg%n</pattern>



    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">


            <pattern>%level %date [%thread] %logger{40} %msg%n</pattern>



    <root level="debug">

        <appender-ref ref="FILE"/>

        <appender-ref ref="STDOUT"/>



·         If logback-test.xml exists it will be used instead of logback.xml (logback.groovy takes precedence over all xml)