まさたかさんのところ(id:masataka_k:20050209)で紹介したついでに、少し興味があったので試してみる。
ライブラリ準備
- http://logging.apache.org/log4j/docs/ からlogging-log4j-1.3alpha-6.tar.gzをダウンロードし、log4j-1.3alpha-6.jarをクラスパスに追加。
- http://cvs.apache.org/viewcvs.cgi/logging-log4j-sandbox/src/java/org/apache/log4j/servlet/ からServletContextLogAppender.javaとServletContextLogAppenderListener.javaをダウンロードしコンパイル。
web.xml設定
web.xmlにServletContextLogAppenderListenerを追加。
<listener> <listener-class>org.apache.log4j.servlet.ServletContextLogAppenderListener</listener-class> </listener>
log4j.xml設定
ServletContextLogAppenderをlog4j.xmlで設定。
このときservletContextPathというパラメータにアプリケーションのコンテキストパスを設定する必要がある。
コンテキストパスを設定することで、複数のアプリケーションを一つのクラスローダで動かすAPサーバでも大丈夫ということなんでしょうか。
なおlog4j.xmlはクラスパスのルートに置くと自動で読み込まれる。
<?xml version="1.0" encoding="Shift_JIS" ?> <!DOCTYPE configuration > <configuration debug="true" xmlns='http://logging.apache.org/'> <appender name="servletLog" class="org.apache.log4j.servlet.ServletContextLogAppender"> <param name="servletContextPath" value="/ww2-demo" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy/MM/dd hh:mm:ss} %-5p (%C:%L) - %m"/> </layout> </appender> <root> <level value="error" /> <appender-ref ref="servletLog" /> </root> </configuration>
ログ出力
どっかのクラスでログを出力
Logger.getLogger(this.getClass()).error("エラー"); Logger.getLogger(this.getClass()).fatal("例外", new Exception());
出力結果
2005-02-10 00:39:08 StandardContext[/ww2-demo]2005/02/10 12:39:08 ERROR (ww2.examples.event.SimpleAction:13) - エラー 2005-02-10 00:39:08 StandardContext[/ww2-demo]2005/02/10 12:39:08 FATAL (ww2.examples.event.SimpleAction:14) - 例外 [Ljava.lang.String;@1132e76
先頭に出ている「[/ww2-demo]」までの部分はTomcatで出してるログです。
Throwableのスタックトレースはちゃんと出てません。
注意点
- ログメッセージはそのままでるのではなく、ServletContextで出しているログの中にメッセージが出る(今回の場合はServletContextは最後に改行を出力しているのでlayoutには改行を入れませんでした)
- Throwableを渡してもスタックトレースが出ない
↑この辺はもしかしたらAPサーバのせいかもしれません(今回使ったのはTomcat5.0.25)