首先,須要在項目中導入log4j使用的JAR包,導入結果以下圖:apache
菜單:Build Path->Configure Build Path->Add Extern Jarsapp
導入JAR包後,在SRC級別下建立log4j.properties配置文件,配置方法以下:函數
### 設置### log4j.rootLogger = debug,stdout,D,E ### 輸出信息到控制擡 ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n ### 輸出DEBUG 級別以上的日誌文件設置 ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = vincent_player_debug.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 輸出ERROR 級別以上的日誌文件設置 ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File = vincent_player_error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
若是日誌文件沒有設置路徑的話,那麼日誌文件會輸出到工程目錄下。測試
測試代碼以下:ui
import org.apache.log4j.*; public class vincent_player_framt { private static Logger logger = Logger.getLogger(vincent_player_framt.class); public static void main(String[] args) throws Exception { // 記錄debug級別的信息 logger.debug("This is debug message."); // 記錄info級別的信息 logger.info("This is info message."); // 記錄error級別的信息 logger.error("This is error message."); } }
首先,建立logger,而後能夠調用debug、info、error函數來輸出信息到日誌文件。error函數信息只會輸出到error的log文件下面。spa