Monday, March 21, 2011

LOG4j(Logging for java)

Need of Logging:To keep Track of Flow of Execution Related to an Application
Logging, or writing the state of a program at various stages of its execution to some repository such as a log file, is an age-old method used for debugging and monitoring applications.
                              As of now we print log messages in console only by using System.out.println().By using Log4j we can print log messages in console,files,htmlpages,jsp pages.........etc.
(Note:   Alternative to System.out.println())

Type : Logging for java
(LoggingAPI to generate log messages)
Vendor : ApacheFoundation
Opensource s/w
Jar file that represents Log4jAPI : log4j-version.jar

Logically, log4j can be viewed as being comprised of three main components:     
            
             logger-------------> Logger            (step1)
             appender ---------->Appender          (step2)   
             layout ----------------->Layout             (step3)


sample progarme 1:(note:add log4j.jar in the CLASSPATH before running this programme.)
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

public class LogExample {

    public LogExample() {
    }
  

    public static void main(String argsp[]) {
       
//crete logger object(step1)
        Logger log = Logger.getLogger(LogExample.class);
//createLayout object(step2)
        Layout lay=new SimpleLayout();
//create Appender objevt(Step3)
        Appender ap=new ConsoleAppender(lay);

        log.addAppender(ap);
        log.setLevel(Level.WARN);         //default logger level is"DEBUG"
        log.debug("projectname-modulename-Class-method-Here is some DEBUG");
        log.info("projectname-modulename-Class-method-Here is some INFO");
        log.warn("projectname-modulename-Class-method-Here is some WARN");
        log.error("projectname-modulename-Class-method-Here is some ERROR");
        log.fatal("projectname-modulename-Class-method-Here is some FATAL");
      
     
   }
}

sample programme 2:(printing log messages in a file)

//FileAppender

public class Example2  {
   
    public static void main(String a[])
    {
        Logger l=Logger.getLogger(Example2.class);
          try{
    Layout lay=new SimpleLayout();
    FileAppender ap=new FileAppender(lay,"hklwurjrk2.txt",true);
    l.addAppender(ap);
    l.setLevel(Level.DEBUG);
          }catch(Exception d)
          {
              l.debug("log4j stmts problem");
          }
    try{
    Class.forName("oracle.jdbc.driver.OracleDriver");
    l.debug("driver loaded......");
    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.214:1521:XE","kiran","kiran");
    l.info("connection established successfully..........");
   
      }catch(Exception e)
      {
          l.fatal("Db Problem");
          e.printStackTrace();
      }
       
    }
}


sample programe:(using properties file)

prop.properties:(each time comment one execute(# symble used here for commeting))
     
#log4j.rootLogger=debug, 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=%t %-5p %c{2} - %m%n




#log4j.rootLogger=debug, stdout
#log4j.appender.stdout=org.apache.log4j.FileAppender
#log4j.appender.stdout.File=src/logs/msg2.txt
#log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%r  [%t]  %p  %c  %m  %d  %n             




#log4j.rootLogger=debug, stdout
#log4j.appender.stdout=org.apache.log4j.FileAppender
#log4j.appender.stdout.File=msg1.html
#log4j.appender.stdout.layout=org.apache.log4j.HTMLLayout




#log4j.rootLogger=debug, stdout
#log4j.appender.stdout=org.apache.log4j.RollingFileAppender
#log4j.appender.stdout.File=src/logs/rollfile666666.txt
#log4j.appender.stdout.MaxFileSize=2kb
#log4j.appender.stdout.MaxBackupIndex=5
#log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%r  [%t]  %p  %c  %m  %d  %n       




log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.File=logs/dailyrollfile3333.txt
log4j.appender.stdout.DatePattern='.'yyyy-MM-dd-HH-mm
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%r  [%t]  %p  %c  %m  %d  %n                   




Example2.java:
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public class Example2  {
   
    public static void main(String a[])
    {
        Logger l=Logger.getLogger(Example2.class);
   
        PropertyConfigurator.configure("src/prop.properties");
        
          l.setLevel(Level.DEBUG);
          l.debug("Myprojectname-modulename-Class-method-ok executedddddddddddddd");
          l.info("projectname-modulename-Class-method-some infoooooooooo");
          l.warn("projectname-modulename-Class-method-warn msg");
          l.error("projectname-modulename-Class-method-error msg......");
          l.fatal("projectname-modulename-Class-method-this is some fatal errrrrrrr");
    }
}

No comments:

Post a Comment