Sunday, June 10, 2012

Spring Framework and SL4J Integration

The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time.

slf4j is actually not a logging library - it's just a facade. You choose a logging framework by yourself. We use slf4j and logback that implements the slf4j API natively.

The SLF4J project has similar goals to commons-logging. It uses quite a different approach, however, which has both benefits and drawbacks. Future versions of commons-logging may adopt some of the concepts of SLF4J.

Spring uses Jakarta Common Library(JCL) and java.util.logging,SL4J has advantages over JCL as it does not suffer
from class loader problem and Memory Leak Problem.SLFJ for logging in java use parametrized version of various log methods they are faster as compared to normal method.


Lests Demonstrate the Integration of SL4J to String framework,in this example we are using SL4J with logback framework

Step 1: Create Java Project.
Step 2: Add Spring Library,SL4J jars and Logback jars in build path as shown





Step 3: Create a class which includes logger as fallows
package com.main;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloSl4j {
 
 private static final Logger logger = LoggerFactory.getLogger(HelloSl4j.class);
 
 public void sayHello(){
  logger.info("Inside the sayHello Method");
  System.out.println("Say Hello To Spring SL4J Integration");
 }
}




Step 4: create the spring.xml for your application context as shown


 

 



Step 5: create your logger.xml to configure logging as fallows
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
 
 <appender name="STDOUT"
            class="ch.qos.logback.core.ConsoleAppender">
 
    <!-- encoders are assigned by default the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
    <encoder>
   <pattern>
    %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
   </pattern>
    </encoder>
  </appender>
 
 <root level="INFO">
  <appender-ref ref="STDOUT" />
 </root>
 
</configuration>

Step 6: Create your main class fallows

package com.test;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.main.HelloSl4j;

public class HelloSl4jTest {

 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
  HelloSl4j helloSl4j = (HelloSl4j) ctx.getBean("helloSl4j");
  helloSl4j.sayHello();
 }

}


Here is the Logging Console





No comments: