log4j:自定义appender和从logger实例访问方法

时间:2014-04-09 17:03:40

标签: java logging log4j mule

我有一个自定义附加功能,可将LoggingEvent添加到ArrayList LoggingEvent,如下所示:

import java.util.ArrayList;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

public class PayloadLogAppender extends AppenderSkeleton {
    private final ArrayList<LoggingEvent> eventsList = new ArrayList();
    @Override
    protected void append(LoggingEvent event) {
        eventsList.add(event);
    }

    public void close() {
    }
    public boolean requiresLayout() {
        return false;
    }
    public ArrayList<LoggingEvent> getAllMessages() {
        return this.eventsList;
    }
}

我已将自定义appender添加到我的log4j.properties中,并且它可以正常加载:

log4j.appender.payloadLog=PayloadLogAppender

现在在我的应用内部,我使用getLogger()以常规方式访问记录器, 但最后我想拥有eventsList列表。我在appender中创建了方法getAllMessages(),并希望在我拥有我的记录器实例时调用它。获得logger.getAllMessage()属性的引用需要eventsList吗?

1 个答案:

答案 0 :(得分:0)

我能够通过以下方式实现这一目标:

import mypackage.PayloadLogAppender;

// in the method that gets triggered at the end.
this.LOGGER = Logger.getRootLogger();
Appender payloadlog = this.LOGGER.getAppender("payloadLog");
System.out.println("My list of logging events" + ((PayloadLogAppender) payloadlog).getAllMessage());

感谢指点。