日期:2014-05-20  浏览次数:20875 次

讨论log4j记录日志失败的异常处理
本帖最后由 lg_asus 于 2012-12-08 14:18:52 编辑 http://stackoverflow.com/questions/13758735/how-can-i-get-notified-when-log4j-fails

下面是demo code:

package test;

import java.lang.Thread.UncaughtExceptionHandler;

import org.apache.log4j.Logger;

public class Test2
{

    public static void main(String...args){
       Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(){
           @Override
           public void uncaughtException(Thread t, Throwable e)
           {
              System.out.println(t);
              e.printStackTrace();
           }
       });
       Logger logger = null;
       try{
           logger = Logger.getLogger(Test2.class);
       }catch(Exception e){
           e.printStackTrace();
//         switch to other appender
//         logger = Logger.getLogger("hell");
       }
       logger.info("Hello");
    }
}




my log4j.properties is:

log4j.rootLogger = error, DYNADS

log4j.logger.test= info, DYNADS

log4j.appender.DYNADS = org.apache.log4j.DailyRollingFileAppender   
log4j.appender.DYNADS.File = Z:/log/app-log.txt  
log4j.appender.DYNADS.Append = true  
log4j.appender.DYNADS.layout = org.apache.log4j.PatternLayout  
log4j.appender.DYNADS.layout.ConversionPattern = %d{HH:mm:ss,SSS} [%-5p] %m%n


the result of code is :

log4j:ERROR setFile(null,true) call failed.
java.io.FileNotFoundException: Z:\log\app-log.txt (系统找不到指定的路径。)
    at java.io.FileOutputStream.openAppend(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:177)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:102)
    at org.apache.log4j.FileAppender.setFile(FileAppender.java:290)
    at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:164)
    at org.apache.log4j.DailyRollingFileAppender.activateOptions(DailyRollingFileAppender.java:216)
    at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:257)
    at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:133)
    at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:97)
    at org.apache.log4j.PropertyConfigurator.parseAppender(PropertyConfigurator.java:689)
    at org.apache.log4j.PropertyConfigurator.parseCategory(PropertyConfigurator.java:647)