「Tomcat」サーブレットで DailyRollingFileAppender

サーブレットで DailyRollingFileAppender 使うサンプル作ったのでメモ。

[ 環境情報 ]
CentOS 6.2
Apache Tomcat 6.0.32
Java SE 6 Update 34
Apache log4j 1.2.17

■ DailyRollingFileAppenderServlet.java

package test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class DailyRollingFileAppenderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = null;

	public void init(ServletConfig config) throws ServletException {
		logger = Logger.getLogger(DailyRollingFileAppenderServlet.class);
		ServletContext context = config.getServletContext();
		DOMConfigurator.configure(context.getRealPath("WEB-INF/xml/log4j.xml"));
	}

	public DailyRollingFileAppenderServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		logger.info("DailyRollingFileAppenderServlet INFO !!");

		PrintWriter out = response.getWriter();
		out.print("<html><body>");
		out.print("DailyRollingFileAppenderServlet");
		out.print("</body></html>");
	}
}

log4j.xml ( WEB-INF/xml ディレクトリに配置 )

<?xml version="1.0" encoding="UTF-8"?>
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

<appender name="n1" class="org.apache.log4j.DailyRollingFileAppender">
  <param name="File" value="${catalina.home}/webapps/Log4jWeb/dailyrollingfile.log" />
  <param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm" />
  <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d : %m%n"/>
  </layout>
</appender>

<logger name="test.DailyRollingFileAppenderServlet">
  <appender-ref ref="n1"/>
</logger>

</log4j:configuration>

※ 検証目的なので分単位でローテートさせてます。


あとは、WEB-INF/lib に log4j-1.2.17.jar を配置して、Log4jWeb.war で Tomcat にデプロイすれば動くはずです。

以上です。