口上 †
- 昔のようにアプリケーションが War や Ear に閉じているのであれば、そこに logback.xml を入れれば良い
- しかし、昨今では OSGi を使ってモジュール化するのが普通になってきた
- ということで、ログは VM ごとに一本化する
Glassfish の設定 †
アプリケーション †
- ログ出力サーブレット
@WebServlet(name = "LogServlet", urlPatterns = {"/LogServlet"})
public class LogServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Logger log = LoggerFactory.getLogger(LogServlet.class);
log.info("処理開始");
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet LogServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet LogServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
log.info("処理終了");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
- pom.xml では、slf4j-api への依存関係を provided にする。コンパイル時には要るけど、実行環境にはあるので Jar に入れないということ。
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
実行結果 †
[~/GlassFish40/glassfish/domains/domain1]$ cat logs/app_2014-04-21.log
2014-04-21 22:04:16,963 INFO org.jboss.weld.Version - WELD-000900 2.0.0 (SP1)
2014-04-21 22:04:17,632 WARN o.j.w.i.u.InterceptionTypeRegistry - Class 'javax.ejb.PostActivate' not found, interception based on it is not enabled
2014-04-21 22:04:17,632 WARN o.j.w.i.u.InterceptionTypeRegistry - Class 'javax.ejb.PrePassivate' not found, interception based on it is not enabled
2014-04-21 22:04:54,499 INFO com.mycompany.sampleweb.LogServlet - 処理開始
2014-04-21 22:04:54,501 INFO com.mycompany.sampleweb.LogServlet - 処理終了
Java#Jakarta