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.
Step 3:
Change HelloWorldController.java as below:
package org.arpit.java2blog.springmvc.controller;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloWorldController {
private static final Logger logger = Logger.getLogger(HelloWorldController.class);
@RequestMapping("/helloworld")
public ModelAndView hello() {
String helloWorldMessage = "Hello world from java2blog!";
logger.info("This is info message");
logger.error("This is error message");
return new ModelAndView("hello", "message", helloWorldMessage);
}
}
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.