Sunday, March 16, 2014

Best Logging for Java - Logback with SLF4J



If you're looking for good logging mechanism for Java I suggest you to use SLF4J Facade with Logback. For my opinion it's the best combination for logging in Java. Today I will show how to configure your Java project in order to use SLF4J Logback logging framework to print logs to console and file output.

Logback with SLF4J

First, download SLF4J files and Logback files.
Add these files to your CLASSPATH:
  • slf4j-api-X.X.X.jar
  • logback-core-X.X.X.jar
  • logback-classic-X.X.X.jar

Now look how simple is to use Logback! In the code all you need is this:

public class LogbackFun {
  final static Logger logback = LoggerFactory.getLogger(LogbackFun.class);

  public static void main(String[] args) {
    logback.info("Test info");
    logback.debug("Test debug");
    logback.trace("Test trace");
    logback.warn("Test warn");
    logback.error("Test error");
  }
}

Ok, how to configure the log settings? Very simple! When the program starts this what's going on:
  1. Logback tries to find a file called logback.groovy in the CLASSPATH
  2. If no such file is found, Logback looking for file called logback-test.xml in the CLASSPATH
  3. If no such file is found, it checks for the file logback.xml in the CLASSPATH
  4. If neither file is found, Logback configures itself automatically using the BasicConfigurator which will print logs to the console
So, we create logback.xml file and put it in CLASSPATH directory (src folder). Now let's take a look on the file content:
<configuration>
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs/mylog.log</file>
      <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
          <fileNamePattern>logs/mylog.%i.log.zip</fileNamePattern>
          <minIndex>1</minIndex>
          <maxIndex>3</maxIndex>
      </rollingPolicy>

      <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
          <maxFileSize>5MB</maxFileSize>
      </triggeringPolicy>
    <encoder>
      <pattern>%date{YYYY-MM-dd HH:mm:ss} %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%msg%n</pattern>
    </encoder>
  </appender>

  <root level="trace">
    <appender-ref ref="FILE" />
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
Simply brilliant stuff! Appender tells where to print the log and contains its configurations. Here we have two appenders. One is for printing logs to a file and the second one is for printing into console. We can also set the pattern of the message, the log level set to trace here. RollingPolicy allows to control the file behavior - maximum file size, naming convention etc. 
This is it! As simple as that! 
If you have any questions please don't hesitate to ask in the comments section. Good luck!

3 comments:

  1. hi, but this is not add error and exception in log file any suggestion plz...

    ReplyDelete
    Replies
    1. Just insert exception message into logback call:

      catch (Exception e) {
      logback.error(e.getMessage());
      }

      Delete
  2. Hi,

    Can we configure/limit the size of each event logged ? Like 1000 characters per event ?

    Thanks

    ReplyDelete