MVC

Spring MVC using Log4j Example

Log4j is a popular and widely-used logging framework for the Java development. It’s pretty easy to setup and use the Log4j mechanism in a Spring Mvc application. In this tutorial, I will show you how to implement the logging functionality with the Spring Mvc framework.
 
 
 
 
 
 
 

1. Introduction

1.1 Spring Framework

  • Spring is an open-source framework created to address the complexity of an enterprise application development
  • One of the chief advantages of the Spring framework is its layered architecture, which allows developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
  • Spring framework provides support and integration to various technologies for e.g.:
    • Support for Transaction Management
    • Support for interaction with the different databases
    • Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
    • Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
    • Support for REST style web-services

1.1.1 Spring Mvc Framework

Model-View-Controller (Mvc) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:

  • Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a POJO class which encapsulates the application data given by the controller
  • View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the JSP templates written with Java Standard Tag Library (JSTL)
  • Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In spring framework, the controller part is played by the Dispatcher Servlet

Fig. 1: Model View Controller (MVC) Overview
Fig. 1: Model View Controller (MVC) Overview

1.2 What is Log4j?

Log4j is a simple, flexible, and fast Java-based logging framework. It is thread-safe and supports internationalization. We mainly have 3 components to work with Log4j:

  • Logger: It is used to log the messages
  • Appender: It is used to publish the logging information to the destination like file, database, console etc
  • Layout: It is used to format logging information in different styles

1.2.1 Log4j Logger Class

Logger class provides the methods for the logging process. We can use the getLogger() method to get the Logger object. The syntax is given below:

static Logger log = Logger.getLogger(YourClassName.class);

Logger class has 5 logging methods which are used to print the status of an application:

DescriptionMethod Syntax
debug(Object message)It is used to print the message with the level org.apache.log4j.Level.DEBUG.public void debug(Object message)
error(Object message)It is used to print the message with the level org.apache.log4j.Level.ERROR.public void error(Object message)
info(Object message)It is used to print the message with the level org.apache.log4j.Level.INFO.public void info(Object message)
fatal(Object message)It is used to print the message with the level org.apache.log4j.Level.FATAL.public void fatal(Object message)
warn(Object message)It is used to print the message with the level org.apache.log4j.Level.WARN.public void warn(Object message)
trace(Object message)It is used to print the message with the level org.apache.log4j.Level.TRACE.public void trace(Object message)

To summarize, the priority level is given below.

Trace < Debug < Info < Warn < Error < Fatal

Where org.apache.log4j.Level.FATAL has the highest priority and org.apache.log4j.Level.Trace the lowest.

1.2.2 Log4j Appender Interface

Appender is an interface which is primarily responsible for printing the logging messages to the different destinations such as console, files, sockets, database etc. In Log4j we have different types of Appender implementation classes:

Fig. 2: Log4j Appenders
Fig. 2: Log4j Appenders

1.2.3 Log4j Layout Class

Layout component specifies the format in which the log statements are written into the destination repository by the Appender. In Log4j we have different types of Layout implementation classes:

Fig. 3: Log4j Layout
Fig. 3: Log4j Layout

Now, open up the Eclipse Ide and let’s start building the application!

2. Spring Mvc using Log4j Example

Below are the steps involved in developing this application.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 4: Application Project Structure
Fig. 4: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 5: Create Maven Project
Fig. 5: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 6: Project Details
Fig. 6: Project Details

Select the Maven Web App Archetype from the list of options and click next.

Fig. 7: Archetype Selection
Fig. 7: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 8: Archetype Parameters
Fig. 8: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Log4jSpringMvcEx</groupId>
	<artifactId>Log4jSpringMvcEx</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Log4j, Junit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

In this example, we are using the most stable Log4j version in order to set-up the logging framework. The updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Log4jSpringMvcEx</groupId>
	<artifactId>Log4jSpringMvcEx</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Log4jSpringMvcEx Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<!-- Servlet API Dependency -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
		</dependency>
		<!-- Spring Framework Dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>
		<!-- Log4J Dependency -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 9: Java Package Creation
Fig. 9: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.spring.log4j.

Fig. 10: Java Package Name (com.jcg.spring.log4j)
Fig. 10: Java Package Name (com.jcg.spring.log4j)

Once the package is created, we will need to create the implementation class. Right-click on the newly created package, New -> Class.

Fig. 11: Java Class Creation
Fig. 11: Java Class Creation

A new pop window will open and enter the file name as: TestController. The implementation class will be created inside the package: com.jcg.spring.log4j.

Fig. 12: Java Class (TestController.java)
Fig. 12: Java Class (TestController.java)

3.2.1 Implementation of Utility Class

Let’s write a quick Java program in the spring controller class to use the Log4j framework. Add the following code to it.

TestController.java

package com.jcg.spring.log4j;

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

@Controller
public class TestController {

	private Logger logger = Logger.getLogger(TestController.class);

	@RequestMapping(value = {"/", "hello"}, method = RequestMethod.GET)
	public ModelAndView helloWorld() {

		ModelAndView model = new ModelAndView("helloWorld");
		logger.info("This Is An Info Log Entry ......!");
		logger.error("This Is An Error Log Entry ......!");
		return model;
	}
}

3.3 Configuration Files

Let’s write all the configuration files involved in this application.

3.3.1 Log4j Configuration File

Log4j will be usually configured using a properties file or an XML file. So once the log statements are in place developers can easily control them using the external configuration file without modifying the source code. The log4j.xml file is a Log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.xml in the CLASSPATH.

To configure the logging framework, we need to implement a configuration file i.e. log4j.xml and put it into the src/main/resources folder. Add the following code to it:

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM 
          "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
	<appender name="Appender1" class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-7p %d [%t] %c %x - %m%n" />
		</layout>
	</appender>
	<appender name="Appender2" class="org.apache.log4j.FileAppender">
		<param name="File" value="./Log4jSpringMvcEx/logs/springmvc.log" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-7p %d [%t] %c %x - %m%n" />
		</layout>
	</appender>
	<root>
		<level value="INFO" />
		<appender-ref ref="Appender1" />
		<appender-ref ref="Appender2" />
	</root>
</log4j:configuration>

3.3.2 Spring Configuration File

To configure the spring framework, we need to implement a bean configuration file i.e. spring-servlet.xml which provide an interface between the basic Java class and the outside world. Put this XML file in the Log4jSpringMvcEx/src/main/webapp/WEB-INF folder and add the following code to it:

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	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">

	<context:component-scan base-package="com.jcg.spring.log4j" />

	<!-- Resolves Views Selected For Rendering by @Controllers to *.jsp Resources 
		in the /WEB-INF/ Folder -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

3.3.3 Web Deployment Descriptor

The web.xml file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests and specifies the default page when accessing the application. Dispatcher servlet here acts as a front controller. Add the following code to it:

web.xml

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

	<!-- Spring Configuration - Processes Application Requests -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 13: How to Deploy Application on Tomcat
Fig. 13: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8085/Log4jSpringMvcEx/

Server name (localhost) and port (8085) may vary as per your tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 14: Application Output
Fig. 14: Application Output

And notice some Log entries are appended to the server’s console as follows:

INFO    2017-11-19 14:39:24,801 [http-bio-8085-exec-3] com.jcg.spring.log4j.TestController  - This Is An Info Log Entry ......!
ERROR   2017-11-19 14:39:24,801 [http-bio-8085-exec-3] com.jcg.spring.log4j.TestController  - This Is An Error Log Entry ......!

That’s all for this post. Happy Learning!!

6. Conclusion

That’s all for getting the developers started with the Log4j example, we will look into more features in the next posts. I hope this article served you whatever you were looking for. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of Log4j example with Spring framework.

Download
You can download the full source code of this example here: Log4jSpringMvcEx

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button