log4j 配合 tomcat

想要在 tomcat 中把 log4j 用在自己的程式中,用下列的安裝方式:
1.下載 log4j, 把 log4j.jar 放在自己專案的 WEB-INF/lib 目錄中
2.寫一個 log4j.properties 放在 WEB-INF/classes 中,參考內容如下:

log4j.rootLogger=debug, R
#log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.MaxFileSize=512KB
log4j.appender.R.MaxBackupIndex=3
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
log4j.appender.R.File=C:/logs/log.txt

log4j.appender.R.File 是log 檔的路徑和檔名

可以參考 Short introduction to log4j 中的方式,寫一個 servlet 程式,用來載入 log4j.properties 設定好 log4j 的參數:

import org.apache.log4j.PropertyConfigurator;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.IOException;

public class Log4jInit extends HttpServlet {

  public
  void init() {
    String prefix =  getServletContext().getRealPath("/");
    String file = getInitParameter("log4j-init-file");
    // if the log4j-init-file is not set, then no point in trying
    if(file != null) {
      PropertyConfigurator.configure(prefix+file);
    }
  }

  public
  void doGet(HttpServletRequest req, HttpServletResponse res) {
  }
}

另外在 web.xml 中加上 servlet 的 tag

  <servlet>
    <servlet-name>log4j-init</servlet-name>
    <servlet-class>Log4jInit</servlet-class>

    <init-param>
      <param-name>log4j-init-file</param-name>
      <param-value>WEB-INF/classes/log4j.properties</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
  </servlet>

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s

%d 位部落客按了讚: