如何保证log4j.properties中的行顺序

时间:2014-05-15 10:06:50

标签: java log4j

我的log4j.properties包含这个2 appender:

log4j.appender.TEST_SYNC=org.apache.log4j.DailyRollingFileAppender
log4j.appender.TEST_SYNC.DatePattern=.yyyy-MM-dd-HH
log4j.appender.TEST_SYNC.File=test.log
log4j.appender.TEST_SYNC.encoding=UTF-8
log4j.appender.TEST_SYNC.layout=org.apache.log4j.PatternLayout
log4j.appender.TEST=org.com.log.AsyncAppenderHelper
log4j.appender.TEST.appenderFromLogger=TEST_SYNC

我预计log4j将首先注册TEST_SYNC,然后使用TEST_SYNC appender注册TEST。当它注册时反之亦然,那么日志记录不起作用。使用调试我发现log4j使用java.util.Properties,其中订单不保证,所以有时我的日志记录不起作用。如何保证注册appender的顺序?

/*
 * This class helps configure to AsyncAppender from log4j as part of log4j.properties
 * You can inject other appenders to AsyncAppender using the AsyncAppenderHelper
 * This would free up the main program thread to be independent of log4j's logging operation
 * @Author http://www.linkedin.com/in/jobypgeorge
 */

public class AsyncAppenderHelper extends AsyncAppender {

    public AsyncAppenderHelper() {
        super();
    }

    public void setAppenderFromLogger(String name) {
        Logger l = Logger.getLogger(name);

        Enumeration<Appender> appenders = l.getAllAppenders();

        while (appenders.hasMoreElements()) {
            Appender appender = appenders.nextElement();
            this.addAppender(appender);
            LogLog.debug("Attaching appender named [" + name + "] to appender named [" + appender.getName() + "].");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以切换到log4j.xml。 (这可能会有所帮助:log4j.properties vs log4j.xml