Spring MVC + log4j example

In this post, we will see how to integrate Spring MVC with log4j.

Spring MVC tutorial:

Logging is essential part of programming. It helps developer to track code workflow and fix bugs efficiently. If we get any issue in the code, we check logs for that workflow or functionality.
Log4j is fast , reliable logging framework and can be easily integrated with the code.

We will extend Spring MVC hello world example and enable log4j logging into it.If you are wondering how to use log4j in maven project, you can follow log4j maven integration example.
You only need to follow below steps to enable log4j in Spring MVC.

  • Put log4j jar in classpath and you can use maven to do it for you by adding dependency to pom.xml.
  • Create log4j.properties and put it in the classpath (resource folder in maven)

Project structure:


Step 1:

Add log4j dependency in pom.xml for maven project. For non maven project , put log4j.jar in Web-INF/lib folder.

Your pom.xml will look as below:

Step 2: 
Create log4j.properties as below and put it in the java/main/resources folder.

Step 3:
Change HelloWorldController.java as below:

Step 4:
When you run the project, you will get below screen.

When you click on the link, you will get below screen.

When you will see logs, you will get below entries.

As you can see, logging is enable for our Spring MVC project.

Add Comment