Log4j:

Log4j has three main components:

loggers: It is  capturing logging information. 

appenders :It is responsible for publishing logging information to different localtions.

layouts: It is used to format logging information in different style.

Program:



package logs;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

/**
 *
 * @author trainee
 */
public class Logs {

    /**
     provide class name for getLogger(className)
     * must call the configure() method ,otherwise it gives an exception
     */
    static Logger logger = Logger.getLogger("logs.Logs");
    public static void main(String[] args) {
        // TODO code application logic here
    
        logger.debug("hai");
    }
}


Output:
Try to run Logs as follows: 
java logs.Logs




run:
log4j:WARN No appenders could be found for logger (logs.Logs).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
BUILD SUCCESSFUL (total time: 0 seconds)




·         Logs class is defined to be in the logs package. 
·         It starts by importing the org.apache.log4j.Logger class. 
·         It also defines a static final variable,
logger, of type Logger. 
The logger variable is initialized to the value returned by
Logger.getLogger("logs.Logs").


 Log4j is complaining because we have not configured it just yet. There are many
different ways for configuring log4j and calling the BasicConfigurator.configure()
method. Here

way of second approach



package logs;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

/**
 *
 * @author trainee
 */
public class Logs {

    /**
     provide class name for getLogger(className)
     * must call the configure() method ,otherwise it gives an exception
     */
    static Logger logger = Logger.getLogger("logs.Logs");
    public static void main(String[] args) {
        // TODO code application logic here
       BasicConfigurator.configure();
        logger.debug("hai");
    }}

 


output:
0 [main] DEBUG logs.Logs  - hai
BUILD SUCCESSFUL (total time: 8 seconds)

The output contains relative time, that is, the number of milliseconds that elapsed
since the start of the program until the invocation of the logging request3,
 the name of the invoking thread between brackets,
 the level of the request, 
the logger name, and finally the message. 

As you can see, incorporating log4j into your application is
rather easy. The required steps remain essentially the same, even in large applications.
Recipe for using log4j in your applications.


Use this logger instance by invoking its printing methods, namely the  
debug(),
info(),
 warn(),  
error()  
and fatal() methods or the more generic log() method. 

This will produce logging output on selected devices.





If you want to Log4j JAR File DOWNLOAD Here

0 comments:

Post a Comment