Showing posts with label Log. Show all posts
Showing posts with label Log. Show all posts

Friday, April 05, 2013

Logging application log to a log file(by File Appender)

To log your application log to a log file by using log4j, you have to go through the following steps:
  1. Download latest jar of log4j.jar and add it to your project classpath.
  2. Create a log4j.properties file inside your source directory to define properties of your logger.
  3. To log your application log to a log file, you need to add the following code in the log4j.properties
  4.  
    #################################################################
    #####     Application Logs to be printed in the log file    #####
    #################################################################
     
    log4j.rootLogger= WARN, FILE_APPENDER
    
    # test appender  daily rolling logs format
    log4j.appender.FILE_APPENDER=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.FILE_APPENDER.File=logs/autoLog.log
    log4j.appender.FILE_APPENDER.DatePattern='.'yyyy-MM-dd
    log4j.appender.FILE_APPENDER.layout=org.apache.log4j.PatternLayout
    log4j.appender.FILE_APPENDER.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p (%F:%M:%L) - %m%n
    
    # test appender  daily rolling logs for packages
    log4j.logger.com.myorg=DEBUG
    log4j.logger.com.myorg.core.util=FILE_APPENDER
    log4j.logger.com.myorg.core.page=FILE_APPENDER
    
  5. To know the usage of logger see the below code:
    //In ConfigUtil.java
    private static Logger log = Logger.getLogger(ConfigUtil.class);
    // The below line is called inside static block
    log.info("Properties file loaded at '" + configLoc + "'");
    
    //In BasePage.java
    protected static Logger log = Logger.getLogger(BasePage.class);
    // The below line is called inside setTimeout() method
    log.info("The timeout value is set to " + timeoutSeconds + " seconds.");
    
    //In DriverManager.java
    private static Logger log = Logger.getLogger(DriverManager.class);
    // The below line is called inside static block
    log.info("Driver location is set to '" + driverLoc + "'");
    
  6. You will get your application log in the log file(which you have specified in your log4j.properties, in this example i have specified "logs/autoLog.log" file) as shown in the below sample:
     
    2013-09-05 12:36:04  INFO (ConfigUtil.java::39) - Properties file loaded at '/Users/aksahu/MySpace/Web_Workspace/KnowledgeBase/config/config.properties'
    2013-09-05 12:36:04  INFO (BasePage.java:setTimeout:155) - The timeout value is set to 60 seconds.
    2013-09-05 12:36:04  INFO (DriverManager.java::54) - Driver location is set to '/Users/aksahu/MySpace/Web_Workspace/CoreDriver/drivers/'
    2013-09-05 12:36:04  INFO (DriverManager.java:getDriver:85) - initializing 'chrome' driver...
    2013-09-05 12:36:15  INFO (BasePage.java:windowMaximize:101) - Maximizing the browser window.
    2013-09-05 12:36:17  INFO (BasePage.java:openUrl:86) - Openning the url 'http://knowledgebase-wiki.appspot.com/' in the browser...
    2013-09-05 12:36:23  INFO (BasePage.java:waitForPageToLoad:956) - Waiting for page to load...
    2013-09-05 12:36:23  INFO (BasePage.java:typeByID:195) - Entering text 'java' to the element specified by id 'searchField'
    2013-09-05 12:36:23  INFO (BasePage.java:clickByID:258) - Clicking on the element specified by id 'resultDiv0'
    2013-09-05 12:36:23  INFO (BasePage.java:waitForElementLocatedByXpath:848) - Waiting for the element specified by xpath '//a[contains(text(),'[Go to page]')]'
    2013-09-05 12:36:23  INFO (BasePage.java:clickByXpath:238) - Clicking on the element specified by xpath '//a[contains(text(),'[Go to page]')]'
    2013-09-05 12:36:24  INFO (BasePage.java:waitForPageToLoad:956) - Waiting for page to load...
    2013-09-05 12:36:24  INFO (BasePage.java:isTextPresent:807) - Checking for the text 'Installing Java' in the page
    2013-09-05 12:36:24  INFO (BasePage.java:isTextPresent:807) - Checking for the text 'java' in the page
    2013-09-05 12:36:24  INFO (BasePage.java:quitBrowser:582) - Closing all the instances of the browser 'chrome'
    

Logging application log in the Console(by Console Appender)

To log your application log in the console by using log4j, you have to go through the following steps:
  1. Download latest jar of log4j.jar and add it to your project classpath.
  2. Create a log4j.properties file inside your source directory to define properties of your logger.
  3. To log your application log in the console, you need to add the following code in the log4j.properties
  4.  
    ################################################################
    #####     Application Logs to be printed in the console    #####
    ################################################################
     
    log4j.rootLogger= WARN, CONSOLE_APPENDER
    
    # console appender format
    log4j.appender.CONSOLE_APPENDER=org.apache.log4j.ConsoleAppender
    log4j.appender.CONSOLE_APPENDER.layout=org.apache.log4j.PatternLayout
    log4j.appender.CONSOLE_APPENDER.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p (%F:%M:%L) - %m%n
    
    # console appender for packages
    log4j.logger.com.myorg=DEBUG
    log4j.logger.com.myorg.core.util=CONSOLE_APPENDER
    log4j.logger.com.myorg.core.page=CONSOLE_APPENDER
    
  5. To know the usage of logger see the below code:
    //In ConfigUtil.java
    private static Logger log = Logger.getLogger(ConfigUtil.class);
    // The below line is called inside static block
    log.info("Properties file loaded at '" + configLoc + "'");
    
    //In BasePage.java
    protected static Logger log = Logger.getLogger(BasePage.class);
    // The below line is called inside setTimeout() method
    log.info("The timeout value is set to " + timeoutSeconds + " seconds.");
    
    //In DriverManager.java
    private static Logger log = Logger.getLogger(DriverManager.class);
    // The below line is called inside static block
    log.info("Driver location is set to '" + driverLoc + "'");
    
  6. You will get your application log as shown in the below example:
     
    [TestNG] Running:
      /private/var/folders/cl/34rlg3ns31g8w4jktmpkc2440000gn/T/testng-eclipse--1656210619/testng-customsuite.xml
    
    2013-09-05 12:58:03  INFO (ConfigUtil.java::39) - Properties file loaded at '/Users/ashwin/MySpace/Web_Workspace/KnowledgeBase/config/config.properties'
    2013-09-05 12:58:03  INFO (BasePage.java:setTimeout:155) - The timeout value is set to 60 seconds.
    2013-09-05 12:58:03  INFO (DriverManager.java::54) - Driver location is set to '/Users/ashwin/MySpace/Web_Workspace/CoreDriver/drivers/'
    2013-09-05 12:58:03  INFO (DriverManager.java:getDriver:85) - initializing 'chrome' driver...
    2013-09-05 12:58:09  INFO (BasePage.java:windowMaximize:101) - Maximizing the browser window.
    2013-09-05 12:58:12  INFO (BasePage.java:openUrl:86) - Openning the url 'http://knowledgebase-wiki.appspot.com/' in the browser...
    2013-09-05 12:58:18  INFO (BasePage.java:waitForPageToLoad:956) - Waiting for page to load...
    2013-09-05 12:58:18  INFO (BasePage.java:typeByID:195) - Entering text 'java' to the element specified by id 'searchField'
    2013-09-05 12:58:19  INFO (BasePage.java:clickByID:258) - Clicking on the element specified by id 'resultDiv0'
    2013-09-05 12:58:19  INFO (BasePage.java:waitForElementLocatedByXpath:848) - Waiting for the element specified by xpath '//a[contains(text(),'[Go to page]')]'
    2013-09-05 12:58:19  INFO (BasePage.java:clickByXpath:238) - Clicking on the element specified by xpath '//a[contains(text(),'[Go to page]')]'
    2013-09-05 12:58:19  INFO (BasePage.java:waitForPageToLoad:956) - Waiting for page to load...
    2013-09-05 12:58:19  INFO (BasePage.java:isTextPresent:807) - Checking for the text 'Installing Java' in the page
    2013-09-05 12:58:19  INFO (BasePage.java:isTextPresent:807) - Checking for the text 'java' in the page
    2013-09-05 12:58:19  INFO (BasePage.java:quitBrowser:582) - Closing all the instances of the browser 'chrome'
    PASSED: testJavaModule
            Verifies the Java Module form Knowledge base
    
    ===============================================
        Default test
        Tests run: 1, Failures: 0, Skips: 0
    ===============================================
    

Tuesday, December 06, 2011

Logging using java.util.logging.Logger (Custom logging)

Sometimes in our application we need to log different messages like info,warning,error etc.Here i have given a way how we can use it in our application.
Following 'Log' class creates different log files taking different logger value by input and it also maintains the directory structure of log files according to the value of 'path'  passed to the constructor of 'Log' class.For example, if we 'll pass a parameter 'utils.Example',it will create a file 'logs/utils/Example.log' in the current directory.
Note:First it checks for the directory 'logs/utils' is present or not if it is not present it creates the directory.

//Log.java
  1. package utils;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.logging.FileHandler;
  5. import java.util.logging.Logger;
  6. import java.util.logging.SimpleFormatter;
  7.  
  8. public class Log {
  9.  
  10.   static FileHandler handler;
  11.   static Logger logger;
  12.  
  13.   public static void createLog(String path){
  14.     try {
  15.       String [] s = path.split("\\.");
  16.       File f = new File("./"+"logs/"+s[s.length-2]);
  17.       if(f.exists()==false){
  18.         f.mkdirs();
  19.       }
  20.       handler = new FileHandler("logs/"+s[s.length-2]+"/"+s[s.length-1]+".log");
  21.       handler.setFormatter(new SimpleFormatter());
  22.       logger = Logger.getLogger(path);
  23.       logger.addHandler(handler);
  24.      } catch (IOException e) {
  25.         e.printStackTrace();
  26.      }
  27.   }
  28.  
  29.   public static void loggerINFO(String msg){
  30.      logger.info(msg);
  31.   }
  32.  
  33.   public static void loggerWARN(String msg){
  34.      logger.warning(msg);
  35.   }
  36.  
  37.   public static void loggerERROR(String msg){
  38.      logger.severe(msg);
  39.   }
  40. }
//Example.java
  1. package utils;
  2. import static utils.Log.loggerINFO;
  3. import static utils.Log.loggerWARN;
  4. import static utils.Log.loggerERROR;
  5.  
  6. public class Example {
  7.  
  8.    public Example() {
  9.      Log.createLog(this.getClass().getName());
  10.    }
  11.  
  12.    public void method1(){
  13.      loggerINFO("Doing division by zero");//Log an INFO message
  14.      loggerWARN("May get ArithmeticException");//Log a WARNING message
  15.      try {
  16.        int i = 20/0;
  17.      } catch (Exception e) {
  18.        loggerERROR(e.getMessage());//Log a SEVERE message
  19.      }
  20.    }
  21.  
  22.    public static void main(String[] args) {
  23.      new Example().method1();
  24.    }
  25. }
After running this we 'll get a log file 'logs/utils/Example.log' (In eclipse,if 'Example.java' is in 'utils' package ,you 'll find a log file 'Example.log' in the 'logs' folder which is generated parallel to 'src' folder of the current project)
Note: Everytime you run the 'utils/Example.java' you 'll get a fresh file with new content.

//Content of 'logs/utils/Example.log' after running 'utils/Example.java'

Dec 6, 2011 6:37:33 PM utils.Log loggerINFO
INFO: Doing division by zero
Dec 6, 2011 6:37:33 PM utils.Log loggerWARN
WARNING: May get ArithmeticException
Dec 6, 2011 6:37:33 PM utils.Log loggerERROR
SEVERE: / by zero