Configure Logger using SLF4J in Spring MVC

Hello guys, Bushan here, Welcome back to B2 Tech. Today in this post, I will show you how to configure/implement Logger using SLF4J in Spring MVC/Java Application. So let’s begin,



Tools and Technologies used,

  • JDK 1.8.0_121
  • Eclipse Oxygen
  • SLF4J 1.7.12
  • Maven
  • Spring 4.2.1.RELEASE

Project Structure

Jar dependencies

Edit the pom.xml file and add slf4j dependencies in it as follows.



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>com.arpit.java2blog</groupId>
	<artifactId>SpringMVCHibernateCRUDExample</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMVCHibernateCRUDExample Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.0</version>
			<scope>provided</scope>
		</dependency>
		
		<!-- Bridge logging from JCL to SLF4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${jcl.slf4j.version}</version>
		</dependency>

		<!-- logback -->
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringMVCHibernateCRUDExample</finalName>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>

	</build>
	<properties>
		<spring.version>4.2.1.RELEASE</spring.version>
		<jdk.version>1.7</jdk.version>
		<logback.version>1.1.3</logback.version>
		<jcl.slf4j.version>1.7.12</jcl.slf4j.version>
	</properties>
</project>

XML configuration file for SLF4J

Create a logback.xml file under the src/main/resources source folder and write the following code in it.



logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<property name="LOG_HOME" value="D:/Logs/" />
	<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<Pattern>%date %level [%thread] %logger %msg%n</Pattern>
		</encoder>
	</appender> 
	<appender name="FILE"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<File>${LOG_HOME}/logger.log</File>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<FileNamePattern>
				${LOG_HOME}/apitracker-%d.%i.log.gz
			</FileNamePattern>
			<TimeBasedFileNamingAndTriggeringPolicy
				class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<MaxFileSize>10MB</MaxFileSize>
			</TimeBasedFileNamingAndTriggeringPolicy>
		</rollingPolicy>
		<encoder>
			<Pattern>%date %level [%thread] %logger %msg%n</Pattern>
		</encoder>
	</appender>

	<!-- By default, the level of the root level is set to DEBUG -->
	<root level="DEBUG">
		<appender-ref ref="CONSOLE" />
		<appender-ref ref="FILE" />
	</root>
</configuration>

Console Appender – Writes the logs to either System.out or System.err
File Appender – Writes the logs to the File named in the <File> tag.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
	version="3.0">
	<display-name>Archetype Created Web Application</display-name>

<servlet>
	<servlet-name>spring</servlet-name>
 	<servlet-class>
  		org.springframework.web.servlet.DispatcherServlet
 	</servlet-class>
 	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>spring</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	<annotation-driven />

	<resources mapping="/resources/**" location="/resources/" />

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

	<context:component-scan base-package="in.bushansirgur" />

</beans:beans>



HomeController.java

package in.bushansirgur.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@RequestMapping("/")
	public String homePage() {
		logger.info("This is logger info::::::");
		logger.debug("This is logger debug:::::");
		logger.error("This is logger error");
		return "home";
	}
}

home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h1>This is home page</h1>
</body>
</html>

After running the application the console output and file D:/Logs/logger.log will look like as follows.



2018-10-28 11:52:26,130 DEBUG [http-nio-8037-exec-2] org.springframework.web.servlet.DispatcherServlet DispatcherServlet with name 'spring' processing GET request for [/SpringMVCHibernateCRUDExample/]
2018-10-28 11:52:26,140 DEBUG [http-nio-8037-exec-2] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping Looking up handler method for path /
2018-10-28 11:52:26,152 DEBUG [http-nio-8037-exec-2] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping Returning handler method [public java.lang.String in.bushansirgur.controller.HomeController.homePage()]
2018-10-28 11:52:26,153 DEBUG [http-nio-8037-exec-2] org.springframework.beans.factory.support.DefaultListableBeanFactory Returning cached instance of singleton bean 'homeController'
2018-10-28 11:52:26,157 DEBUG [http-nio-8037-exec-2] org.springframework.web.servlet.DispatcherServlet Last-Modified value for [/SpringMVCHibernateCRUDExample/] is: -1
2018-10-28 11:52:26,227 INFO [http-nio-8037-exec-2] in.bushansirgur.controller.HomeController This is logger info::::::
2018-10-28 11:52:26,227 DEBUG [http-nio-8037-exec-2] in.bushansirgur.controller.HomeController This is logger debug:::::
2018-10-28 11:52:26,227 ERROR [http-nio-8037-exec-2] in.bushansirgur.controller.HomeController This is logger error
Love this post?


Help me to buy a cup of coffee/Support us by donating.
All the donations will be going to the website maintenance/improvement.

Pay Now



About the author

Bushan Sirgur

Well, I am Bushan Sirgur from Banglore, India. Currently, I am working as a Software Developer in a Service Base Company. I am interested in JAVA/J2EE, Angular 2, JavaScript, jQuery, MongoDB.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *