Saturday, March 23, 2013

Logger in Spring web application

The logging API is designed to let a Java program, servlet, applet, EJB, etc. produce messages of interest to end users, system administrators, field engineers, and software developers. Especially in production situations, where things can't be run in a debugger, or if doing so masks the problem that is occurring (because it is timing related, for example), such logs are frequently the greatest (and sometimes the only) source of information about a running program.

Step by Step implementing Logger in Spring Web Application:-

  1. Download log4j jar and put to application build path / put to WEB-INF lib folder.
    Download JAR link
  2. Create a file name
  3. log4j.rootCategory=INFO,S,rollingFile
    log4j.appender.S =org.apache.log4j.ConsoleAppender
    log4j.appender.S.layout =org.apache.log4j.PatternLayout
    log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
    log4j.appender.rollingFile = org.apache.log4j.DailyRollingFileAppender
    #provide path to your location where you want logs created. For now its logs folder of tomcat.
    log4j.appender.rollingFile.File = ${catalina.home}/logs/loggerDemo.log
    log4j.appender.rollingFile.Append = true
    log4j.appender.rollingFile.Threshold = ALL
    log4j.appender.rollingFile.DatePattern = '.'yyy-MM-dd
    log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout
    log4j.appender.rollingFile.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n
      Here ${catalina.home} :- The Tomcat Web container uses a file system directory, called the catalina home directory, to hold files that are common to the entire container.
      You can also give other path for generating log file.
  4. Entry in web.xml file
  6. JAVA Code for logger.
  7. import org.apache.log4j.Logger;
    public class LoggerController {
    	private static final Logger LOGGER = Logger.getLogger(LoggerDemo.class);
    	@RequestMapping(method=RequestMethod.GET, value="/login/{id}")
    	@ResponseBody public void getUserName(@PathVariable String id) {"Calling service User authentication" + id);
  8. Enjoy :)

No comments:

Post a Comment