1. 程式人生 > >編寫一個隨處可呼叫的靜態日誌操作類

編寫一個隨處可呼叫的靜態日誌操作類

import java.io.*;
import java.util.*;
public class LogWriter {
  private static final String DefalutLogFilePathName="c://logtext.log";//預設的日誌檔案的路徑和檔名稱
  private static LogWriter logwriter; //該類的唯一的例項
  private static InputStream fin; //屬性配置檔案的輸入流
  private static Properties pro; //class Properties's supper is Hashtable class
  private static PrintWriter out; //output stream
  private static String logFileName; //output file name
  private LogWriter() {
    outInit();//init out put stream,例項化PrintWriter out 物件.
  }
  /**儲存你想儲存在日誌檔案中的資訊,實現同步
   * out put the message infomation
   * @param message infomation
   */
  public static synchronized void log(String message) {
    if (logwriter == null || (out == null)){
      logwriter = new LogWriter();
    }
    if (out != null) {
      out.println(new java.util.Date() + ":" + message);
    }
  }
  /**把異常資訊儲存在日誌檔案中,實現同步
   * out put the Excetion infomation
   * @param message infomation
   */
  public static synchronized void log(Exception ex) {
    if (logwriter == null || (out == null))
      logwriter = new LogWriter();
    if (out != null) {
      out.println(new java.util.Date() + ":" );
      ex.printStackTrace(out);
    }
  }
  /**
   *輸出檔案流的init
   */
  private void outInit() {
    if (logFileName == null)
      logFileName = getlogFileName(); //從屬性檔案中類獲得日誌檔案的路徑
    try {
      if (out == null) {//如果輸出i/o沒有例項,則生成一個信的
        out = new PrintWriter(new FileWriter(logFileName, true), true); ; //
        //其中的FileWriter()中的第二個引數的含義是:是否在檔案中追加內容
      }
    }
    catch (IOException ex) {
      System.out.println("無法開啟日誌檔案:"+logFileName);
      ex.printStackTrace();
      out = null;
    }
  }
  /**
   *根據配置檔案.來獲得日誌檔案的位置
   *
   * @return logFileName
   */
  private String getlogFileName() {
    try {
      if (pro == null) {
        pro = new java.util.Properties();
        fin = getClass().getResourceAsStream("log.properties"); //在類的當前位置,查詢屬性配置檔案log.properties
        pro.load(fin);//載入配置檔案
        fin.close();
      }
    }
    catch (IOException ex) {
       System.err.println("無法開啟屬性配置檔案: log.properties" );
      ex.printStackTrace();
    }
    return pro.getProperty("logfile",DefalutLogFilePathName);
    //根據屬性值獲得日誌檔案路徑,第二個引數是:如果找不到"logfile"標誌,就返回的預設值
  }
  /**你也可以在所有的日誌都記錄完成的時候,呼叫該方法,釋放資源.
   * free all the resouce,this is secuty method
   */
  public void free() {
    try {
      this.logwriter = null;
      if (out != null)
        this.out.close();
      if (fin != null)
        this.fin.close();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}