log4j

log4jを使ってみたメモ。

Log4j の出力先をコードで変更する

例えば、"hoge" というディレクトリに出力する場合、System.property に設定。

Everything is expanded.Everything is shortened.
  1
 
 System.setProperty("log.dir", "/hoge/");

で、log.dir を log4j.xml から参照する。

log4j.xml

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 
 
 
 
 
 
 
 
 
 <!-- アペンダ -->
 <appender name="record" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="File" value="${log.dir}/app.log" />
    <param name="Append" value="true" />
    <param name="DatePattern" value="'.'yyyy-MM-dd" />
    <layout class="org.apache.log4j.PatternLayout">
       <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss},%m%n" />
    </layout>
 </appender>

この設定を反映させる。

Everything is expanded.Everything is shortened.
  1
 
 DOMConfigurator.configure("log4j.xml");

渡すパスはアプリケーションのルートディレクトリの下という前提。
このパスはクラスローダを使えば取得できるので、

Everything is expanded.Everything is shortened.
  1
  2
 
 
 ClassLoader loader = Thread.currentThread().getContextClassLoader();
 DOMConfigurator.configure(loader.getResource("log4j.xml"));

とするか、Servlet なら

Everything is expanded.Everything is shortened.
  1
  2
 
 
 ServletContext context = getServletContext();
 DOMConfigurator.configure(context.getRealPath("WEB-INF/classes/log4j.xml"));

などとする。

Tomcat 5.5 でログ出力エラー

ファイルの読み書きをするときに、パーミッションが不正というエラーが出ることがある。

例えば、ログファイルの書き込みで、

log4j:ERROR setFile(null,true) call failed.
java.io.FileNotFoundException: /hoge/app.log (Permission denied)
       at java.io.FileOutputStream.openAppend(Ljava.lang.String;)V(Native Method)
       at java.io.FileOutputStream.<init>(FileOutputStream.java:177)
       at java.io.FileOutputStream.<init>(FileOutputStream.java:102)
...

とか。

ディレクトリのパーミッションを777とかに変更してもやはり状況変わらず。

そんなときは、Tomcatのセキュリティをはずしてみると上手くいくことがある。

/etc/init.d/tomcat5 を次のように変更。

# Use the Java security manager? (yes/no)
#TOMCAT5_SECURITY=yes ←コメントアウト
TOMCAT5_SECURITY=no

参考


Java 開発環境構築


トップ   編集 凍結解除 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2010-05-15 (土) 12:08:00 (5088d)