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輸出級別和輸出目的地 ### 2log4j.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 }
Java 為程序創建日誌系統