11/10/2009

Java 自已動手寫log

不用log4j自已寫個簡單的log程式。
分檔規則是將log分年,月記錄,每天一個log檔,日子一久想查某一天的log也比較方便。
例如:2009年10月11月有log時,log分檔會像這樣。
  • /2009/10/
    • 1.log
    • 2.log
    • 3.log
    • 5.log
    • ......
  • /2009/11/
    • 1.log
    • 2.log
    • 3.log
    • .....

Log class
/*
 * Log.java with encode
 * for logging
 *
 * Created on 2009年10月16日
 *
 * @author  Iden
 *
 ****<< Modification Note >>
 *     Date       PTS/PBR/PCR      Label       Editor         Description
 *  ==========  ===============  ==========  ==========  ============================================================
 *  2009/10/16                      0.0.0.1      Iden         create
 */
package com.iden.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.text.SimpleDateFormat;

public class Log {
 
 private String filePath = ""; //directory path of Log 
 private String filePrefix = ""; //prefix name of log file
 private String fileSubName = ""; //subname of log file
 String curWorkingDir = System.getProperty("user.dir"); //User working directory
 private String breakLine="\n";  
 private Object encoding;   
 private String encodingStr;   

 public Log(String path) {
  this(path, "log", "UTF-8");
 }
 
 public Log(String path, String subname, Object encoding) {
  this(path, "Log", subname, encoding);
 }
 
 public Log(String path, String prefix, String subname, Object encoding) {
  if(encoding ==null)
   new Exception("encoding is empth");
  
  filePath = path;
  filePrefix = prefix;
  fileSubName = subname;
  this.encoding = encoding;  
 }
 
 
 /**
  * Output the log file
  * @param str
  */
 public void write(String str) {  
  OutputStream stream = null;
        Writer writer = null;
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
  try {
   String folder = generateDirectory();
      
   File file = new File(folder + filePrefix + "_" + getCurrYYYYMMDD() + "." + fileSubName);
   
   StringBuffer sb = new StringBuffer("");
   sb.append("[" + formatter.format(new java.util.Date()) + "] [start]" + breakLine)
    .append(str)
    .append(breakLine + "[end]" + breakLine);
      
         stream = new FileOutputStream(file, true);
         
            if (encoding instanceof Charset) {
                writer = new OutputStreamWriter(stream, (Charset)encoding);
            } else if (encoding instanceof CharsetEncoder) {
                writer = new OutputStreamWriter(stream, (CharsetEncoder)encoding);
            } else {
                writer = new OutputStreamWriter(stream, (String)encoding);
            }
            OutputStreamWriter osw =(OutputStreamWriter)writer;
      encodingStr =  osw.getEncoding();      
      osw = null;
            
            writer.write(sb.toString());
            writer.flush();
            writer.close();
            
  } catch (java.io.FileNotFoundException efnf) {
   writeException("FileNotFoundException at open log file: " + efnf.getMessage());   
  } catch (java.io.IOException exio) {
   writeException("IOException at write log file: " + exio.getMessage());   
  } catch (java.lang.Exception e) {
   writeException("Exception at write log file: " + e.getMessage());   
  } finally {
   writer = null;
  }
 }
 
 /**
  * Output the log file with default encoding
  * @param str
  */
 public void writeDefaultEncode(String str) {
  java.io.FileWriter fw = null;  
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
  try {
   String folder = generateDirectory();

   fw = new java.io.FileWriter(folder + filePrefix + "_"
     + getCurrYYYYMMDD() + "." + fileSubName, true);
   
   fw.write("[" + formatter.format(new java.util.Date()) + "] " + breakLine + "[start]" + breakLine);
   fw.write(str);
   fw.write(breakLine + "[end]" + breakLine);
   fw.flush();
   fw.close();     
               
  } catch (java.io.FileNotFoundException efnf) {
   writeException("FileNotFoundException at open log file: " + efnf.getMessage());   
  } catch (java.io.IOException exio) {
   writeException("IOException at write log file: " + exio.getMessage());   
  } catch (java.lang.Exception e) {
   writeException("Exception at write log file: " + e.getMessage());   
  } finally {
   fw = null;
  }
 } 
 
 /**
  * Get the encoding string
  */
 public String getEncoding(){
  if(encodingStr != null)
   return encodingStr;
  return null;
 } 

 /**
  * Generate directory path
  * @return
  */
 private String generateDirectory() {
  String folder = defineDirectoryName(filePath);
  java.io.File file = new java.io.File(folder);
  file.mkdirs();
  return folder;
 }

 /**
  * Define the directory path of Log. format is path\YYYY\MM
  * @param path
  * @return current directory path
  */
 private String defineDirectoryName(String path) {
  java.util.Calendar cal = java.util.Calendar.getInstance(java.util.Locale.TAIWAN);
  String folder = path;  
  
  folder = folder + "\\" + String.valueOf(cal.get(java.util.Calendar.YEAR));
  if (String.valueOf((cal.get(java.util.Calendar.MONTH) + 1)).length() == 1) {
   folder = folder + "\\0" + String.valueOf((cal.get(java.util.Calendar.MONTH) + 1));
  } else {
   folder = folder + "\\" + String.valueOf((cal.get(java.util.Calendar.MONTH) + 1));
  } 
  folder = folder + "\\";
  return folder;
 }
 
 /**
  * Get the current date. format is YYYYMMDD
  * @return String of YYYYMMDD
  */
 private String getCurrYYYYMMDD() {  
  SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); //yyyy/MM/dd HH:mm:ss
  return formatter.format(new java.util.Date());
 } 
 
 /**
  * Output Exception message from this object
  * @param msg
  */
 private void writeException(String msg){
  new Log(this.curWorkingDir).write(msg);
 }
 
}

沒有留言:

張貼留言