17 de out. de 2012

Send a Logger output to File using java.util.logging.Logger

Creating a simple java main class showing the implementation of Java Logger using the api java.util.logging.Logger. This code supports: max Length of file(s), number of files to write log, filename of output file, custom feature when logger writting, defines a Log Level, format of log message, works with one or more handlers.

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class LogMain {

 static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
 public static Logger logger = null;

 public static void main(String[] args) {

   // define a max file length
    final int limitMbytes = 50 ;

    // max number of files
    final int limitFiles = 1;
 
  try {
// file to write my log
   final Handler handler = new FileHandler( "/my_logs_dir/my_log.log", ( limitMbytes  * 1024 * 1024 ), limitFiles, true ) {
    public synchronized final void publish( final LogRecord record ) {
    
     // adding a new custom feature to my publish method
     System.out.println("Executing this line..");
    
     record.setMessage( record.getMessage() );
     super.publish( record );
    }
   };
  
   // setting a log level
   handler.setLevel( Level.INFO );
  
   // A custom formatter to my logger file
   Formatter formatter = new Formatter() {
    Date dt = new Date();
    @Override
    public String format(LogRecord record) {
     dt.setTime(record.getMillis());
     return  sdf.format(dt)  + " MESSAGE OUTPUT= - " + record.getMessage() +" Level ="+record.getLevel()+"\n";
    }
   };
   handler.setFormatter( formatter );

   // Add a configured handler to logger instance
   logger = Logger.getLogger( "the_instance_name_of_my_log" );
   logger.addHandler( handler );
   logger.setLevel( Level.INFO );
   logger.setUseParentHandlers( true );
  
  } catch (SecurityException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 
 }

}

Nenhum comentário:

Postar um comentário