部落客廣告聯播

2007年6月9日 星期六

筆記:程式內組態log4j (Note: configure log4j in the code)

筆記:程式內組態log4j
組態配置log4j最常的方法,就是將log4j.properties檔案置放在class path中。
雖然在程式內配置log4j API通常比較不建議被採用(配置被寫死程式碼中),但有時還是有需要在程式中組態配置。
在上次的文章: 不只是System.out.print, 筆記: log4j 提到了log4j最重要的三樣東西:
  1. Logger --> 接收訊息
  2. Appender --> 寫訊息到特定目的
  3. Layout --> 用來表示訊息的格式
log4j.properties主要配置這三樣東西,想當然如果在程式中配置Log4j也相同的是對這三樣東西做配置囉。
以下的基本組態非常容易,只要簡單四步即可完成:
  1. Logger myLogger = Logger.getLogger( this.getClass() );
    myLogger.setLevel( Level.DEGUG );
  2. Layout myLayout = new PatternLayout("%d{ yyyy-MM-dd}; %t;%p; %m%n ");
  3. String filePathName="/somepath/somefile.log";
    FileAppender myAppender = new FileAppender(myLayout,filePathName);
  4. myLogger.setAdditiity( false ); // remove appender from parent loggers
    myLogger.addAppender( myAppender );
------------------------------------------------------------------------------------
Note: configure log4j in the code
The common way to configure log4j API is using the log4j.properties file in the class path.
Although configure log4j in the code is not advised, but it is sometimes needed.
In the past articale : just not System.out, Note: log4j mentioned, the most important three things is:
  1. Logger --> for receiving messages
  2. Appender --> outupt messages to some target
  3. Layout --> used represent the format of messages which will be outputed
log4j.properties is mainly used to configure these three things . Of course, these three things will be configured in your code if you want configure log4j in your code.
The basic configure will be very easy, just follow four steps below:

  1. Logger myLogger = Logger.getLogger( this.getClass() );
    myLogger.setLevel( Level.DEGUG );
  2. Layout myLayout = new PatternLayout("%d{ yyyy-MM-dd}; %t;%p; %m%n ");
  3. String filePathName="/somepath/somefile.log";
    FileAppender myAppender = new FileAppender(myLayout,filePathName);
  4. myLogger.setAdditiity( false ); // remove appender from parent loggers
    myLogger.addAppender( myAppender );

沒有留言: