Monday, 27 July 2015

Logger in Java - Using this we can generate seperate log files for each test script

package data;

import java.io.File;
import java.io.PrintWriter;
import java.util.Date;

public class PrintWriterMethods {
   
    public static String filename="";
    public static PrintWriter pw= null;
    public static File file =null;
    public static String resultsFolder = "src/results/";
   
    public static boolean startLogger()
    {
        boolean flag = false;
        try{
            Date dt= new Date();
            String dt1 = dt.toString().replace("-", "_").replace(":", "_").replace(" ", "");
            System.out.println(dt1);
            filename = "summary"+ dt1 + ".txt";
            file = new File(resultsFolder + filename);
            pw = new PrintWriter(file);                       
            flag = true;
        }
        catch(Exception oExp){
            System.out.println(oExp.getMessage());
        }
        return flag;
    }
   
    public static String getFileName(){
        return filename;
    }
   
    public static void logFailer(String message){
        Date dt= new Date();
        pw.append(dt.toString() + "--FAILURE--" + message + "\r\n");
       
    }
    public static void closeLogFile(){
        Date dt= new Date();
        pw.append(dt.toString() + "--END OF THE SCRIPT--");
        pw.close();
    }
    public static void logSuccess(String message){
        Date dt= new Date();
        pw.append(dt.toString() + "--SUCCESS--" + message + "\r\n");
    }
    public static void logWarning(String message){
        Date dt= new Date();
        pw.append(dt.toString() + "--WARNING--" + message + "\r\n");
    }  
   
}










package data;
public class SubClassTest {

    public static void main(String[] args) {
        PrintWriterMethods.startLogger();
        PrintWriterMethods.logFailer("Print the step Failed..");
        PrintWriterMethods.logFailer("Print the step Failed2..");
        PrintWriterMethods.logSuccess("Print the step Failed3..");
        PrintWriterMethods.logFailer("Print the step Failed4..");
        PrintWriterMethods.logWarning("Print the step Failed5..");
        PrintWriterMethods.closeLogFile();
        System.out.println(PrintWriterMethods.getFileName());       
    }
}



Output: summaryMonJul2717_15_46IST2015.txt

Mon Jul 27 17:15:46 IST 2015--FAILURE--Print the step Failed..
Mon Jul 27 17:15:46 IST 2015--FAILURE--Print the step Failed2..
Mon Jul 27 17:15:46 IST 2015--SUCCESS--Print the step Failed3..
Mon Jul 27 17:15:46 IST 2015--FAILURE--Print the step Failed4..
Mon Jul 27 17:15:46 IST 2015--WARNING--Print the step Failed5..
Mon Jul 27 17:15:46 IST 2015--END OF THE SCRIPT--

No comments:

Post a Comment