1. 程式人生 > >Java 為程式建立日誌系統

Java 為程式建立日誌系統

使用JAVA建立日誌系統有兩種方法

    1.使用log4j操作日誌檔案

    2.使用系統重定向輸出日誌資訊

  方法1:使用log4j操作日誌檔案(可使用jar或者xml)

     步驟1:下載log4j.jar

        下載地址:http://mirrors.hust.edu.cn/apache/logging/log4j/1.2.17/log4j-1.2.17.zip

    步驟2:匯入log4j.jar

        1.在當前工程處右鍵》new(新建)》Folder(資料夾)<沒找到的話選Other》wizards》輸出Folder>》Library(資料夾的名字)

        2.Library資料夾處放入剛才下在的log4j-1.2.17.zip裡面的log4j-1.2.17.jar

        3.捆綁Library(右鍵Library》Build Path》ADD to Bulid Path)

    步驟3:配置log4j.properties

        1.在當前工程處右鍵》new(新建)》File(檔案)》File  Name(檔名)》設定為log4j.properties

        2.為log4j.properties新增配置資訊

         

 1 ### 設定Logger輸出級別和輸出目的地 ###
2 log4j.rootLogger=debug,stdout,logfile 3 4 ### 把日子輸出到控制檯 ### 5 log4j.appender.stdout=org.apache.log4j.ConsoleAppender 6 log4j.appender.stdout.Target=System.err 7 log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout 8 9 ### 把日誌資訊輸出到檔案 ### 10 ### 設定輸出路徑 jbit.log(jbit可以隨意改字尾.log) ###
11 log4j.appender.logfile.File=jbit.log 12 ### 設定配置檔案 ### 13 log4j.appender.logfile=org.apache.log4j.FileAppender 14 log4j.appender.logfile.layout=org.apache.log4j.PatternLayout 15 log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %F %p %m%n

    步驟4:新建日誌檔案

        在當前工程處右鍵》new(新建)》File(檔案)》File  Name(檔名)》設定為LogFile.log

    步驟5:在所需的匯出日誌的Class新增以下程式碼即可實現匯出日誌資訊功能

          .

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
  測試程式碼
*/
public class Log4JTest { //關鍵程式碼1:建立日誌物件 private static Logger logger =Logger.getLogger(Log4JTest.class.getName()); public static void main(String[] args) { //關鍵程式碼2:設定log4j配置檔案 PropertyConfigurator.configure( "log4j.properties" ); try { throw new Exception("輸出資訊錯誤!"); }catch(Exception e) { logger.error(e.getMessage()); } } }

 

 

  方法2:使用系統重定向輸出日誌資訊

      步驟1:建立PrintStream物件

      步驟2:設定您要輸出的System輸出格式

          系統輸出格式有2種(System.setErr(PrintStream err)和System.setOut(PrintStream Out))

          一種是輸出錯誤資訊,一種是輸出普通列印資訊

      步驟3:實現以下程式碼即可輸出日誌資訊

      

 1 import java.io.FileOutputStream;
 2 import java.io.PrintStream;
 3 
 4 /**
 5  * 測試重定向標準I/O流
 6  * @author Administrator
 7  *
 8  */
 9 public class RedirectionOutputStreamTest {
10     public static void main(String[] args) throws Exception {
11         //建立PrintStream物件
12         PrintStream ps= new PrintStream(new FileOutputStream("jbit.log"));
13         //設定輸出資訊格式(普通訊息輸出or錯誤資訊輸出)
14         System.setErr(ps);
15         try {
16             throw new Exception("非法操作!!!");
17         }catch(Exception e) {
18             System.err.println(e.getMessage());
19         }
20     }
21 
22 }