Friday, April 12, 2013

use SLF4J with Logback


It's recommend to use SLF4J with Logback.

1. Better performance
2. Better integration to SLF4J (marker for example)
3. By default using BasicConfigurator so that there's no pain to begin
4. logback-test.xml is easier to test
logback.groovy -> logback-test.xml -> logback.xml -> BasicConfigurator
5. Easier to track (below or <configuration debug="true">)
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    // print logback's internal status
    StatusPrinter.print(lc);
6. You may specify the location of the default configuration file with a system property named "logback.configurationFile"

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.Marker; import org.slf4j.MarkerFactory; public class HelloLogback { private static final Logger logger = LoggerFactory.getLogger(HelloLogback.class); static Marker SMTP_TRIGGER = MarkerFactory.getMarker("SMTP_TRIGGER"); public static void main(String[] args) { logger.info("test 2"); logger.error("just another test 2"); logger.info(SMTP_TRIGGER,"ended"); } }



<configuration debug="true">
  <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />
  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>myApp.log</file>
<append>true</append>
    <encoder>
      <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    </encoder>
  </appender>
  
  <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    <smtpHost>smtp.gmail.com</smtpHost>
    <smtpPort>465</smtpPort>
    <SSL>true</SSL>
    <username>xxxxxxxxx@gmail.com</username>
    <password>xxxxxxxx</password>

    <to>xxxxxxxxxxx@gmail.com</to>
    <from>xxxxxxxxxxxxxxxxxx@gmail.com</from>
    <subject>TESTING: %logger{20} - %m</subject>
    <layout class="ch.qos.logback.classic.PatternLayout">
      <pattern>%date %-5level %logger{35} - %message%n</pattern>
    </layout>       
    <cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTrackerImpl">
      <!-- send just one log entry per email -->
      <bufferSize>10</bufferSize>
    </cyclicBufferTracker>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="debug">
    <appender-ref ref="FILE" />
    <appender-ref ref="EMAIL" />
    <appender-ref ref="STDOUT" />
  </root>
  
</configuration>

No comments:

Post a Comment