Monday, November 10, 2014

Custom Logging from stand alone Java

This post shows how to log manually in a file system from Java without involving cordys.

---------------------------------------------------------------------------------------------------------------

package better.faster.smarter.development;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class CustomLogger {
private static Logger logger = Logger.getLogger("IsureTransUtil");
private static FileHandler fh=null;
protected static void logEntry(String message)
{
try{
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
       Calendar cal = Calendar.getInstance();          
    String logFile="IsureTransUtil_"+dateFormat.format(cal.getTime())+".log"; 
//FileHandler takes two parameter 1st one being the fileName and the second one being append mode. If set to true then it will append to the existing log file else will create new one.
    fh = new FileHandler(logFile,true);        
    logger.addHandler(fh);
    SimpleFormatter formatter = new SimpleFormatter();  
       fh.setFormatter(formatter); 
       logger.log(Level.SEVERE, message);        
}
catch(Exception e)
{

}
finally{
//Until you close the file handler the bytes which were written will not get reflected.
fh.close();
}
}
}

-----------------------------------------------------------------------------------------------
Usage of the above class
----------------------------------------------------------

package better.faster.smarter.development;

public class HowToLog{

public static void main(String[] args) {
try{
CustomLogger.logEntry("Started custom Logging");
}
catch(Exception e)
{

}
}
}


No comments:

Post a Comment