Loggging using log4j API


1. Add the dependencies in the POM.xml file like as follows:

 
<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>1.2.12</version>
 </dependency>

2. Make a log4j.properties file under the root folder of the project having the following data :
# 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

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

3. Use the Logger class in which you want to access the logs:

package com;

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.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/")
public class MailController {
	
	private static final Logger logger  = Logger.getLogger(MailController.class);
	
	@RequestMapping(value = "/getVersion", method = RequestMethod.GET)
	public @ResponseBody Response  getVersion(){
		Response response = new Response();
		response.setSpecVersion("34c");
		Status status = new Status();
		status.setCode(100);
		status.setMnemo("OK");
		response.setStatus(status);
		if(logger.isDebugEnabled()){
			logger.debug("getVersion method executed");
		}
		/*Student student = new Student();
		student.setId(123);
		student.setName("Rahul Thakur");*/
		return response;
	}
	
	/**
	 * Send mail method for 
	 * @return
	 */
	public Response sendMail(){
		return new Response();
	}
	
	
}

This entry was posted in Spring and tagged on by .
Rahul Thakur

About Rahul Thakur

Hi, this is Rahul working as Software Engineer at Orange Business Services. Responsible for Requirement analysis, design ,development, deployment, and testing. Working on Agile methodology and Scrum Experience on UML, OOAD, OOPS, Design patterns, Java / J2ee technologies, ORM, performance and load tests, code review and lot of SDLC activities.