(See Show Notes Below ↓)

comments powered by Disqus

Find a copy of the companion source code for this episode here:

https://github.com/upgradingdave/javajing/tree/master/slf4j

In case you're viewing this in github, please find the Episode here:

http://javajing.com/2012/06/08/slf4j.html

Steps to use Slf4j

  • Add slf4j-api jar as a dependency to your app
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.6.1</version>
    </dependency>
    
  • Include Logger and LoggerFactory interfaces:
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
  • Create a Logger at the top of each class your write
    public class MyClass {
    
        Logger log = LoggerFactory.getLogger(HelloWorld.class);
    ...
    
  • That's it! Use the logger anywhere you need to.
    public void anyFunction() {
    log.info("About to return Hello, World");
    }
      public class MyClass {
    
          Logger log = LoggerFactory.getLogger(HelloWorld.class);
      ...
    
  • At this point, you can compile run your code. Anyone who uses your code as a dependency can use the log framework of their choice.
  • To actually see log statements, you'll need to add a library (a slf4 binding) that actually implements the slf4j logging interface api.
  • Pick an implementation, in this demo, we'll use log4j. Add corresponding slf4j "binding" dependency
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.6.1</version>
      <scope>runtime</scope>
    </dependency>
    
  • Since I chose to use Log4j, it's also necessary to add a log4j.properties file to the classpath so that log4j knows where and how to write logs
  • Run the app again and now you should see log statements