Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Integrating Log4j + Spring MVC

In this article we will see how to implement an integration between Java most popular log library, Log4J, and Spring MVC framework

When you are en route to developing Web-based applications, one of the vital aspects of the process is logging. Usually, logging helps us identify errors and bugs in the written code, and accordingly, rectify them as may be necessary.

Now, every language generally has an in-built mechanism that allows one to implement logging at a more or less good level. However, the use of external frameworks for logging has also been a very thorough trend among developers, as they offer certain extra features. This tutorial has been designed to help one in the integration of Log4j with Spring MVC.

Why do we require logging?

As mentioned earlier, logging is a very important part in the development of any application. Logging of code allows for easy debugging and maintenance, besides also allowing the structured storage of the runtime information of any application.

However, logging can practically slow down an application as well. Hence, we require the use of logging frameworks in our application such that they are fast, but at the same time, also reliable in terms of the results produced.

Requirements for tutorial

What is Log4j?

Now, that we know how logging plays an important hand in identifying bugs and errors in the code, and also that there are external frameworks that can assist with the process, let us take a dive into what Log4j is.

Written in Java, Log4j happens to be a fast, flexible and reliable logging framework. It bears an Apache Software License and is distributed under it. Log4j has become incredibly popular among developers and, as a result, has been ported to many other languages such as C, C#, C++, Ruby, Perl, Eiffel and Python.

Log4j also happens to highly configurable by means of external configuration files at runtime. It offers direct logging mechanisms to destinations such as file, database, console, etc. and also views the entire process in terms of priorities.

There are three main components in Log4j, which are –

Loggers - These are basically used for the capturing of logging information.

Appenders – These publish logged information to various destinations as may be necessary.

Layouts – Layouts help in the arrangement and formatting of logging information as per certain styles.

Features and advantages of Log4j

Log4j boasts of certain very good features and advantages, which we shall take a look into.

  • Thread-safe.
  • Optimization has been done for speed.
  • A named logged hierarchy forms the basis.
  • Multiple output Appenders are supported per logger.
  • Internationalization support available.
  • There are no predefined sets of facilities.
  • Runtime setting of logging behavior possible.
  • Can handle Java Exception from start.
  • Multiple levels are supported, such as ALL, DEBUG, TRACE, WARN, FATAL, INFO, and ERROR.

What is Spring MVC?

Spring MVC happens to be the Web component of Spring, which is but a framework. With rich functionalities for the development of robust Web applications, the Spring MVC offers the model-view-controller architecture. Flexible and loosely coupled applications can be well developed by means of this. It is also largely possible to be integrated with frameworks such as Java Server Faces, Struts, Web Work, Tapestry, etc.

The MVC aspect separates the different features offered by the application, like input, business and interface logic, but at the same time offers loose coupling.

  • Model basically encapsulates the application data.
  • The View renders the models data. It generates the HTML code that is interpreted by the client’s browser.
  • The Controller processes the requests from the user, builds appropriate model and passes for rendering.

Integration of Log4j

To carry out the integration process of Log4j, you will need to –

  • Place the log4j.jar file in the project classpath.
  • The, create a log4j.properties or a log4j.xml file. This should be done in the project root classpath. For Maven standard structured directory, it will necessarily be the resources folder.

A point to note would be that by default, spring makes use of JCL (commons-logging) to carry out logging. It is also equipped with the ability to find out the presence of other logging frameworks in other place on the classpath, by means of a runtime discovery algorithm.

Adding log4j library jar file

As we know Log4j is the most popular logging framework for java and j2ee based applications. Spring MVC is another widely used MVC framework used in java based application development. So the integration of log4j and spring framework is important before we start the application development and used logging. First, you need to download log4j, then extract the jar file and put it in the WEB-INF\lib directory of your web application. Following screen shot shows you the exact location where the file should be kept.

Figure 1: Showing directory structure

Directory of the project

A good step before you begin is to ensure and review the final structure of the project.

Dependencies of the project

The XML file defines the project dependencies. It will act as a dependency xml file to support log4j and spring framework.

Listing 1: This is depend.xml file

<properties>
                   <spring.version>4.1.6.RELEASE</spring.version>
                   <log4j.version>1.2.17</log4j.version>
           </properties>
   
           <dependencies>
   
                    <!-- Spring -->
                   <dependency>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-webmvc</artifactId>
                            <version>${spring.version}</version>
                   </dependency>
   
                   <!-- Log4j -->
                   <dependency>
                            <groupId>log4j</groupId>
                            <artifactId>log4j</artifactId>
                            <version>${log4j.version}</version>
                   </dependency>
   
           </dependencies>

Log4j.properties file

You need to create a log4j.properties file and then put it in the folder named resources. This is the properties file to include all properties definition used in the logging system

Listing 2: This is the log4j.properties file

# Root logger option
log4j.rootLogger=DEBUG, stdout, file
 
# Redirect log messages to console
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{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
 
# Redirect log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
#outputs to Tomcat home
log4j.appender.file.File=${catalina.home}/logs/myapp.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Spring MVC Controller with Message Logging

Here is a simple controller that returns a welcome page. This will also serve a basis on which you can learn how to implement logging using Log4j.

Listing 3: WelCtrl.java controller file

package com.demo.common.controller;
 
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 Welcomecontroller {
 
         private static final Logger logr = Logger.getLogger(Welcomecontroller.class);
         @RequestMapping(value = "/", method = RequestMethod.GET)
         public ModelAndView getwelcome() {
 
                 //logs debug message
                 if(logr.isDebugEnabled()){
                          logr.debug("getwelcome method is executed!");
                 }
                 //logs for exception
                 logr.error("This is an error message", new Exception("Testing"));
                 
                 ModelAndView model = new ModelAndView("Welcome");
                 model.addObject("message", "Hello! This is Spring MVC and Log4j");
                 return model;
         }
}

Figure 2: Showing the output

Demo of the code

Logging messages that will be displayed in the console, when you run the above code, are shown below.

log4j.properties

# Redirect log messages to console
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{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Jetty console

2015-09-29 19:10:35 DEBUG Welcomecontroller:19 - getwelcome method is executed!
2015-09-29 19:10:35 ERROR Welcomecontroller:23 - This is an error message
java.lang.Exception: Testing
        at co.demo.common.controller.WelCtrl.getwelcome(WelCtrl.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)

Conclusion

Logging is a very important process in the development of Web applications and it allows us to capture and sort out errors and structures. As a result, the use of Log4j, which is one of the most popular logging frameworks available, happens to be of great use as well.

The above tutorial shows how one can integrate Log4j framework with Spring MVC for the development of applications. Also, a complete demo, with the output code should be sufficient to help you learn how logging can be implemented.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login