使用JAVA建立日誌系統有兩種方法java
1.使用log4j操做日誌文件apache
2.使用系統重定向輸出日誌信息app
方法1:使用log4j操做日誌文件(可以使用jar或者xml)測試
步驟1:下載log4j.jarui
下載地址:http://mirrors.hust.edu.cn/apache/logging/log4j/1.2.17/log4j-1.2.17.zipspa
步驟2:導入log4j.jardebug
1.在當前工程處右鍵》new(新建)》Folder(文件夾)<沒找到的話選Other》wizards》輸出Folder>》Library(文件夾的名字)日誌
2.Library文件夾處放入剛纔下在的log4j-1.2.17.zip裏面的log4j-1.2.17.jar
code
3.捆綁Library(右鍵Library》Build Path》ADD to Bulid Path)xml
步驟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 }