Spring Logging with Log4J

Logging is very important for any application its give us insider information about application about its background and what happens in the application at debug and run time. It helps us understand what is happening inside the engine by recording parameters silently and provides vital information. It helps in providing system related information like health status, debugging and provides critical support during production trouble shooting and unexplained failure.

Popular Spring Tutorials
  1. Spring Tutorial
  2. Spring MVC Web Tutorial
  3. Spring Boot Tutorial
  4. Spring JDBC Tutorial
  5. Spring AOP Tutorial
  6. Spring Security Tutorial
Understanding for Log4J Logger Tool:-
Log4j logger contains three main components namely logger, appender and layout. Logger takes care of the logging mechanism and deals with level of logging. Log4j provides five standard levels of logging. There are two more special levels given by log4j. Above all these, log4j allows you to create custom levels. 

Five standard log4j levels:-
1. DEBUG Level - This log4j level helps developer to debug application. Level of message logged will be focused on providing support to a application developer.

2. INFO Level - This log4j level gives the progress and chosen state information. This level will be generally useful for end user. This level is one level higher than DEBUG.

3. WARN Level - This log4j level gives a warning about an unexpected event to the user. The messages coming out of this level may not halt the progress of the system.

4. ERROR Level - This log4j level gives information about a serious error which needs to be addressed and may result in unstable state. This level is one level higher than WARN.

5. FATAL Level - This log4j level is straightforward and you don’t get it quite often. Once you get this level and it indicates application death.

Two special log4j levels :-
ALL Level-
This log4j level is used to turn on all levels of logging. Once this is configured and the levels are not considered.

OFF Level-
This log4j level is opposite to ALL level. It turns off all the logging.

This is very easy to use Log4J functionality inside Spring MVC applications. The following example will take you through simple steps to explain the simple integration between Log4J and Spring or Spring MVC.

Step 1: Log4j library(log4j-x.y.z.jar):-  Download the Log4j library from the official website,

Step 2: log4j.properties:- Create a Log4j properties file (log4j.properties), put it into the project class path.

Define how log4j handling the logged message, in this example, it will redirect all the logged messages into a text file named "C:\\logging.out".
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\logging.out
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 
# Root logger option
log4j.rootLogger=debug, file, stdout
Spring Logging with Log4J

Step 3:-In Java class, call Logger.getLogger to return the Log4j handler to handle the logging task.
HelloLoggingController.java

package com.dineshonjava.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Dinesh Rajput
 *
 */
@Controller
public class HelloLoggingController {
 //get log4j handler
 private static final Logger logger = Logger.getLogger(HelloLoggingController.class);
 
 @RequestMapping("/hello")
 public ModelAndView sayLogiingHello(){
  //log it via log4j
  if(logger.isDebugEnabled()){
   logger.debug("Start debug");
  }
  logger.info("Going to run HelloLoggingController class");
  Map model = new HashMap();
  model.put("message", "Hello world Example with Logging");
  model.put("author", "Dinesh on Java");
  logger.info("Exiting the program");
  return new ModelAndView("helloWorld", model);
 }
}

Step 4: You can generate debug and error message similar way as we have generated info messages. Now let us see the content of sdnext-servlet.xml file:

<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

   <mvc:annotation-driven></mvc:annotation-driven>
 
   <context:component-scan base-package="com.dineshonjava.controller">
</context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="jspViewResolver">
     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
     <property name="prefix" value="/WEB-INF/views/"></property>
     <property name="suffix" value=".jsp"></property>
</bean> 
 
</beans>

web.xml
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet>
 <servlet-name>sdnext</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
            <param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-param>
        <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>sdnext</servlet-name>
  <url-pattern>*.html</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>
</web-app>

helloWorld.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>


Welcome message : ${message}

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this we will get the following message in browser:


Spring Logging with Log4J Example

Same time if you will check your C:\\ drive then you should find your log file logging.out with various log messages, something as follows:
------
Going to run HelloLoggingController class
Exiting the program
Invoking afterPropertiesSet() on bean with name 'helloWorld'
Rendering view [org.springframework.web.servlet.view.JstlView: name 'helloWorld'; URL [/WEB-INF/views/helloWorld.jsp]] in DispatcherServlet with name 'sdnext'
Added model object 'message' of type [java.lang.String] to request in view with name 'helloWorld'
Added model object 'author' of type [java.lang.String] to request in view with name 'helloWorld'
Forwarding to resource [/WEB-INF/views/helloWorld.jsp] in InternalResourceView 'helloWorld'
Successfully completed request
----

Jakarta Commons Logging (JCL) API
Alternatively you can use Jakarta Commons Logging (JCL) API to generate log in your Spring application. JCL can be downloaded from the http://jakarta.apache.org/commons/logging/. The only file we technically need out of this package is the commons-logging-x.y.z.jar file, which needs to be placed in your class-path similar way as you had put log4j-x.y.z.jar in the above example.
To use the logging functionality you need a org.apache.commons.logging.Log object and then you can call one of the following methods as per your requirement:
  • fatal(Object message)
  • error(Object message)
  • warn(Object message)
  • info(Object message)
  • debug(Object message)
  • trace(Object message)
Below is the replacement of HelloLoggingController.java which makes use of JCL API:
package com.dineshonjava.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Dinesh Rajput
 *
 */
@Controller
public class HelloLoggingController {

 static Log log = LogFactory.getLog(HelloLoggingController.class.getName());

 @RequestMapping("/hello")
 public ModelAndView sayLogiingHello(){
  //log it via log4j
  if(logger.isDebugEnabled()){
   logger.debug("Start debug");
  }
  logger.info("Going to run HelloLoggingController class");
  Map model = new HashMap();
  model.put("message", "Hello world Example with Logging");
  model.put("author", "Dinesh on Java");
  logger.info("Exiting the program");
  return new ModelAndView("helloWorld", model);
 }
}
You have make sure that you included commons-logging-x.y.z.jar file in your project before deploying the program.

Now keeping rest of the configuration and content unchanged in the above example, if you deploye your application you will get similar result what you got using Log4J API.

Download SourceCode+Libs
Spring3LoggingApp.zip

No comments:

Post a Comment