Showing posts with label log4j API. Show all posts
Showing posts with label log4j API. Show all posts

Log4j Multiple Appender Example

Apache Software Foundation

In one of our earlier tutorial we have seen about Using Log4j API Logger. In this tutorial we will about how to use Multiple Appender using Log4j API with examples. First lets see about package level appenders and next multiple appenders in same class. 

What is package level appenders?
Basically in our application we will write modules or packages according to our project needs. For examples lets take some online shopping application which will have Billing, Items listing, Registration, Test Cases etc., So if we thought of keeping separate loggers for each package or module then it can be achieved by Log4j Multiple Appender. In below log4j.properties file we have mentioned the package path each appenders separately which will take care of all logs to log into appropriate loggers which we have mapped.

log4j.logger.com.jd.billing=DEBUG,FIRST_APPENDER 
log4j.logger.com.jd.listing=DEBUG,SECOND_APPENDER 

Lets see simple log4j.properties file along with 2 different package and sample java code. 

log4j.properties file:


log4j.rootCategory=DEBUG

log4j.category.your.category.name=WARN

# FIRST_APPENDER - used to log messages in the admin-logs.log file.
log4j.logger.FIRST_APPENDER=DEBUG, FIRST_APPENDER
log4j.appender.FIRST_APPENDER=org.apache.log4j.RollingFileAppender
log4j.appender.FIRST_APPENDER.maxFileSize=10MB
log4j.appender.FIRST_APPENDER.MaxBackupIndex=2
log4j.appender.FIRST_APPENDER.layout=org.apache.log4j.PatternLayout
log4j.appender.FIRST_APPENDER.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x(%F:%L) - %m%n
log4j.appender.FIRST_APPENDER.File=D://logs/first.log

# SECOND_APPENDER - used to log messages in the report-logs.log file.
log4j.logger.SECOND_APPENDER=DEBUG, SECOND_APPENDER
log4j.appender.SECOND_APPENDER=org.apache.log4j.RollingFileAppender
log4j.appender.SECOND_APPENDER.maxFileSize=10MB
log4j.appender.SECOND_APPENDER.MaxBackupIndex=2
log4j.appender.SECOND_APPENDER.layout=org.apache.log4j.PatternLayout
log4j.appender.SECOND_APPENDER.layout.ConversionPattern=[%d{ISO8601}]%5p%6.6r[%t]%x(%F:%L) - %m%n
log4j.appender.SECOND_APPENDER.File=D://logs/second.log

# Mentions the package path to write logs separately
log4j.logger.com.jd.billing=DEBUG,FIRST_APPENDER 
log4j.logger.com.jd.listing=DEBUG,SECOND_APPENDER 


package com.jd.billing;

import org.apache.log4j.Logger;

public class ByBillingClass {

 public static Logger logger = Logger.getLogger(ByBillingClass.class);
 
 public static void main(String[] args) {
  
  logger.info("My billing starts ...");
  
  logger.info("My billing process ...");
  
  logger.info("My billing ends ...");  
 }
}


package com.jd.listing;

import org.apache.log4j.Logger;

public class MyListingClass {

 public static Logger logger = Logger.getLogger(MyListingClass.class);
 
 public static void main(String[] args) {
  
  logger.info("My listing starts ...");
  
  logger.info("My listing process ...");
  
  logger.info("My listing ends ...");  
 }
}


OUTPUT:

first.log file:


[2013-10-04 11:51:33,188] INFO     0[main](ByBillingClass.java:11) - My billing starts ...
[2013-10-04 11:51:33,193] INFO     5[main](ByBillingClass.java:13) - My billing process ...
[2013-10-04 11:51:33,193] INFO     5[main](ByBillingClass.java:15) - My billing ends ...


second.log file: 


[2013-10-04 11:51:38,031] INFO     0[main](MyListingClass.java:11) - My listing starts ...
[2013-10-04 11:51:38,035] INFO     4[main](MyListingClass.java:13) - My listing process ...
[2013-10-04 11:51:38,035] INFO     4[main](MyListingClass.java:15) - My listing ends ...


What is  multiple appender in same class?
Above we have seen about package level appender and its work. Suppose if we need multiple logger in same java file then we can create Logger instance specific to appenders which we have mentioned in log4j.properties file. Lets see simple example for using multiple logger in single java code. For this lets same log4j.properties file which we have used above. 


package com;

import org.apache.log4j.Logger;

public class MyMultileLoggerTesting {
 
 // First logger instance
 public static Logger fLogger = Logger.getLogger("FIRST_APPENDER");
 
 // Second logger instance
 public static Logger sLogger = Logger.getLogger("SECOND_APPENDER");

 public static void main(String[] args) {
  
  fLogger.info(" *** Logging messages for FIRST LOGGER *** ");
  
  sLogger.info(" *** Logging messages for SECOND LOGGER *** ");
 }
}

OUTPUT:

first.log file:


[2013-10-04 11:51:33,188] INFO     0[main](ByBillingClass.java:11) - My billing starts ...
[2013-10-04 11:51:33,193] INFO     5[main](ByBillingClass.java:13) - My billing process ...
[2013-10-04 11:51:33,193] INFO     5[main](ByBillingClass.java:15) - My billing ends ...
[2013-10-04 11:51:42,953] INFO     0[main](MyMultileLoggerTesting.java:15) -  *** Logging messages for FIRST LOGGER *** 


second.log file: 


[2013-10-04 11:51:38,031] INFO     0[main](MyListingClass.java:11) - My listing starts ...
[2013-10-04 11:51:38,035] INFO     4[main](MyListingClass.java:13) - My listing process ...
[2013-10-04 11:51:38,035] INFO     4[main](MyListingClass.java:15) - My listing ends ...
[2013-10-04 11:51:42,957] INFO     4[main](MyMultileLoggerTesting.java:17) -  *** Logging messages for SECOND LOGGER *** 


Using log4j API Logger


In each and every applications we will be seen logger to record the different types of logs like error, information, debug etc., In this tutorial we will see how to use Logger log4j API in our application and its usage. 



There are mainly 3 components like loggers, appenders and layouts. All these 3 components work together to enable developers to log messages according to message type and level and to control at run-time as how these messages are formatted and where they are stored. All these appender or logger settings will be made in the file called log4j.properties file. 

The advantage of using logger over System.out.print is to disable certain log statements while allowing others to print unhindered. This capability assumes that the logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria. Loggers are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule ie., "A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger." as example given below


log4j.rootCategory=DEBUG, CONSOLE, TESTING 

log4j.logger.org.apache.commons.validator=DEBUG, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=WARN
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %-5p %m%n

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=/user/local/logFile.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.Threshold=DEBUG
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%15.15t] %-5p %c %x - %m%n

log4j.appender.TESTING=org.apache.log4j.RollingFileAppender
log4j.appender.TESTING.File=/user/local/application.log
log4j.appender.TESTING.Append=true
log4j.appender.TESTING.MaxFileSize=1024KB
log4j.appender.TESTING.MaxBackupIndex=10
log4j.appender.TESTING.layout=org.apache.log4j.PatternLayout
log4j.appender.TESTING.layout.ConversionPattern=[%d{EEE MMM d HH:mm:ss yyyy}] [%-5p] %c{1}.java(): %m%n


Set of possible logger levels are:
TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL

For more appenders and how to inclide in our project we can get it from the following link - http://logging.apache.org/log4j/1.2/manual.html

Now lets see simple example for how to start with the log4j API in our application with simple example to redirect all logs to a specified log file. For that first we need log4j.jar file (can use any latest version). I have used log4j-1.2.13.jar and we need to create log4j.properties file under classes directory.


log4j.rootLogger=INFO, file
 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\logs\\application.log
log4j.appender.file.MaxFileSize=1MB
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



import java.util.Date;
import org.apache.log4j.Logger;

public class LogTest {

 static Logger logger = Logger.getLogger(LogTest.class.getName());
 
 public static void main(String[] args) {
  logger.info("Application starts .....................");
  
  long stime = new Date().getTime();
  
  try{
   logger.info("Process Started !!!");
   Thread.sleep(5300);
   logger.info("Process completed !!!");
  }catch (Exception e) {
   logger.error("Exception Occured : "+e.getMessage());
  }
  
  long etime = new Date().getTime();
  float diff = (float)(etime - stime)/1000;
  logger.info("Total time to complete ::: "+ diff +" second(s)");
  
  logger.info("Application Ends .......................");
 } 
}


OUTPUT:


log4j API Logger