Log4j in java

This is the basic tutorial for Log4j in java .
log4j is a reliable, fast and flexible logging framework which is Java based logging utility,
which is distributed under the Apache Software License.
log4j is highly configurable through external configuration files at runtime.

Two things are very good to know when you start learn Log4j.x

1. Log4j has three main components

    1.1  loggers: Responsible for capturing logging information.

    1.2  appenders: Responsible for publishing logging information to various preferred destinations.

    1.3  layouts: Responsible for formatting logging information in different styles.


2. Log4j Log levels.

Level Description
OFF The highest possible rank and is intended to turn off logging.
FATAL Severe errors that cause premature termination. Expect these to be immediately visible on a status console.
ERROR Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.
WARN Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.
INFO Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.
DEBUG Detailed information on the flow through the system. Expect these to be written to logs only.
TRACE Most detailed information. Expect these to be written to logs only

Log4j Code.

package logger;

import org.apache.log4j.AsyncAppender; // required Jar
import org.apache.log4j.Logger; // required Jar
import org.apache.log4j.xml.DOMConfigurator; // required Jar



public class loger {    
  
    private static final int type = 0;
    private static Logger logger = Logger.getLogger(loger.class
            .getPackage().getName());
    //@SuppressWarnings("unused")
    private AsyncAppender asyncAppender = null;
    private static loger instance = null;
  
    private loger() {
  
        try {
            //DOMConfigurator.configure(Properties.getProperty("LOG_PATH"));
            DOMConfigurator.configure("your directory path/log4j.xml");
            logger.setAdditivity(false);
            asyncAppender = (AsyncAppender) Logger.getRootLogger().getAppender(
                    "ASYNC");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static loger getInstance() {
        if (instance == null) {
            instance = new loger();
        }
        return instance;
    }

    public void doLog(int type, String className,String methodName,String description,String ipAddress,String macAddress,String loginId) {

        StringBuffer strMessage = new StringBuffer();
        strMessage.append(className).append(" || ");
        strMessage.append(methodName).append(" || ");
        strMessage.append(description).append(" || ");
        strMessage.append(ipAddress).append(" || ");
        strMessage.append(macAddress).append(" || ");
        strMessage.append(loginId).append(" || ");
      
        logger.info(strMessage.toString());
        logger.warn(strMessage.toString());
        logger.error(strMessage.toString());
        logger.debug(strMessage.toString());
        logger.trace(strMessage.toString());
      
      
      
    }
    private  static final   loger log=loger.getInstance();
    public static final String Name = "knowledge Hunt";
 public static void main(String arg[]){
    
     System.out.println("This Is My"+ Name);
     logger.warn("This is warn : " + Name);
     logger.error("This is error : " + Name);
     logger.fatal("This is fatal : " + Name);
         
     log.doLog(1, "Knowledge", "Hunt","called","12.12.34.66", "", "Cheers Up");

      
 }
 }
This is log4j.XML file you should put anywhere in your directory.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="ASYNC" >
        <param name="BufferSize" value="256"/>
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="DROLLFILE" />
    </appender>
    <appender name="CONSOLE" >
        <layout >
            <param name="ConversionPattern"
                value="%d{yyyy/MM/dd HH:mm:ss,SSS} %-5p %c %x - %m %n" />
        </layout>
    </appender>
    <appender name="DROLLFILE" >
        <param name="File" value="D:/javadcbbank/Log/vttrnadminlog.log"/>
        <param name="warn" value="DEBUG"/>
        <param name="Append" value="true"/>
        <param name="datePattern" value="'.'yyyy-MM-dd" />
        <layout >
            <param name="ConversionPattern" value="%d{yyyy/MM/dd HH:mm:ss,SSS} %-5p %c %x - %m %n"/>
        </layout>
</appender>
    <logger name="logger" additivity="false">
        <level value="debug" />
        <appender-ref ref="ASYNC" />
    </logger>
    <root>
        <priority value="info" />
        <appender-ref ref="ASYNC" />
    </root>
</log4j:configuration>
Cheers up 

Comments