Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Wednesday, 8 May 2013

Logging in Spring Framework using Log4j - Part (3/3) Log4j Configuration using Property file and XML

In previous tutorials of LOG4J tutorial series we came across Basics of Logging in Java and Architecture of LOG4J. We came across how to implement log4j in java. In this particular blog we would finalize the whole process by providing a quick introduction to LOG4J configuration files. An step by step explanation on how to use log4j in Java.

LOG4J configuration with Spring - Part 1 : Logging Introduction
LOG4J configuration with Spring - Part 2 : LOG4J architecture and levels
LOG4J configuration with Spring - part 3 : Log4J configuration with spring

In this part of discussion we will cover LOG4J configuration with spring step by step process. We will also look into LOG4J configurations using property files and XML files and difference between them. Lets start with configuration :

LOG4J Configuration in Spring

In spring, LOG4J can be configured in one of the following two ways : either

Through an xml file or a property file. These files includes properties that tells the framework about log levels  and decided what logs are to be executed and what are to be skipped. Example for these configuration files are given below :

LOG4J Configuration in Spring using a property file

LOG4J configuration can be done in many ways and there are a number of properties that can be used according to needs. Here are some general purpose examples of property files.

LOG4J property file to display output on console only.

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
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

LOG4J property file to write output on log file only.

# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\logingFile.log
log4j.appender.file.MaxFileSize=2MB
log4j.appender.file.MaxBackupIndex=1
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

LOG4J property file to write output on log file and show on console as well

# Root logger option
log4j.rootLogger=INFO, file, stdout # Direct log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=C:\\logingFile.log log4j.appender.file.MaxFileSize=1MB log4j.appender.file.MaxBackupIndex=1 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 # Direct log messages to stdout 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

LOG4J configuration fiel in xml format to write output on log file and show on console as well .

In case of xml configuration file for LOG4J , we only need to add an appropriate appender entry as per the need.
<?xml version="1.0" encoding="UTF-8"?>
<!--<span class="hiddenSpellError" pre=""-->DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

xmlns:log4j=
              "http://jakarta.apache.org/log4j/"
               debug="false">

   <appender name="consoleAppender"
      class="org.apache.log4j.ConsoleAppender">
      <param name="Threshold" value="INFO" />
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d
             %-5p  [%c{1}] %m %n" />
      </layout>
   </appender>

   <appender name="fileAppender"
           class="org.apache.log4j.RollingFileAppender">
      <param name="Threshold" value="INFO" />
      <param name="File" value="sample.log"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d
                %-5p  [%c{1}] %m %n" />
      </layout>
   </appender>

   <logger name="javabeat.net.log4j" additivity="false" >

      <level value="INFO" />
      <appender-ref ref="consoleAppender"/>
      <appender-ref ref="fileAppender"/>
   </logger>

</log4j:configuration>

Write logging code in Java Classes.

At last the only work is to add logging code in actual java code of your application this can be done as shown below :

Home.java - Example Class

package com.beingjavaguys.controller;

import org.apache.log4j.BasicConfigurator;
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 Home {

User user = new User();

static final Logger logger = Logger.getLogger(Home.class);

@RequestMapping("/hello")
public ModelAndView hello(){

BasicConfigurator.configure();
logger.debug("Debug..");
logger.info("Info.."+user);
logger.error("Error.."+user);
logger.fatal("Fatal"+user);
logger.trace("trace");

return new ModelAndView("hello","message","HelloWorld");
}
}
The output of logging will look something like the picture shown below :


Step by Step configuration of LOG4J in Spring Application.

Till now we have discussed all important aspects and concepts related to LOG4J. Lets review all steps required to implement logging in Spring.

1) Download log4j.x.x.x.jar and copy it in lib folder of your project. If you are using Maven than add log4j dependency to your pom.xml like this.
<dependencies>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </dependency>
  </dependencies>
2) Add one of the configuration file either property file or xml file to your project and make sure the file is included in classpath.

3) Add required logging code to your project classes where you want to enable logging and store activities.
static final Logger logger = Logger.getLogger(Home.class); // register class with logger
logger.debug("Debug..");  // implement required logging method

Here we are done with our whole series of log4j tutorial and a detailed explanation on LOG4J in Java and its integration in Spring MVC applications. In upcoming blogs we will see more about Spring and other Java Technologies.









Thanks for reading !
Being Java Guys Team




0 comments:

Post a Comment

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft