Spring Core

Spring Logging with Log4J Example

Spring Logging is very important for any application its give us insider information about application about its background and what happens in the application at debugging 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 troubleshooting and unexplained failure.

Spring Logging

Let’s see the Spring logging options as below:

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 the 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 the developer to debug the application. Level of message logged will be focused on providing support to an application developer.

2. INFO Level – This log4j level gives the progress and chosen state information. This level will be generally useful for the 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 an 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 classpath.

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


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 the 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 the browser:

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
----

Spring logging with Jakarta Commons Logging (JCL) API

Alternatively, you can use Jakarta Commons Logging (JCL) API to generate a log in your Spring logging 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 an 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 to 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 deploy your application you will get the similar result what you got using Log4J API.

Download SourceCode+Libs
SpringLoggingApp.zip

Spring Related Topics you may like
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago