Monday, September 12, 2011

Logback

Reasons to prefer Logback over Log4j:http://logback.qos.ch/reasonsToSwitch.html

 

·         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 clover.org.apache.log4j.FileAppender

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

statusListener(OnConsoleStatusListener)

 

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">

        <!-- Seehttp://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy -->

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

            <FileNamePattern>log.%d{yyyy-MM-dd}.log</FileNamePattern>

        </rollingPolicy>

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

             Seehttp://logback.qos.ch/manual/appenders.html#prudentWithRolling -->

        <prudent>true</prudent>

        <encoder>

            <!-- For pattern syntax seehttp://logback.qos.ch/manual/layouts.html#conversionWord -->

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

        </encoder>

    </appender>

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

        <encoder>

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

        </encoder>

    </appender>

    <root level="debug">

        <appender-ref ref="FILE"/>

        <appender-ref ref="STDOUT"/>

    </root>

</configuration>

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