Java Developers Tool Apache Log4j

The Log4j API provide the interface that applications should code to and provide the adapter components required for implementers to create a logging implementation.
In our project Log4j will be usually configured using a properties file or xml file externally, without modifying the source code we can easily control log statement.In log4j three main components you needed to configure to obtain the result logger, appender and layout.

- Logger object is the used to log message.
- Appender is the specifies the ouput source like as console or file location.
- Layout is the specify the format in which the log message should be logged


let's see the log4j.properties file in bellow −

# Define the root logger with appender file
log = /usr/home/log4j 
log4j.rootLogger = DEBUG,FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout

log4j.appender.FILE.layout.conversionPattern=%m%n

See the sample example with Java calss is using the log4j library 

import org.apache.log4j.Logger;
public class log4jExample{
   /* Class Name to be printed on */
   static Logger log = Logger.getLogger(log4jExample.class.getName());
   public static void main(String[] args){
      log.debug("Hello this is a debug message");
      log.info("Hello this is an info message");
   }



when you will compile and run above java program. 
You would get the following result inside 

path : /usr/home/log4j/log.out file −

Hello this is a debug message
Hello this is an info message

No comments: