如何在log4j中创建自己的Appender? [英] How to create my own Appender in log4j?

查看:128
本文介绍了如何在log4j中创建自己的Appender?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是log4j的新手。任何人都可以解释如何创建自己的Appender?即如何实现类和接口以及如何覆盖它?

I am new in log4j. Can anyone explain how to create my own Appender? i.e. how to implement the classes and interfaces and how to override it?

推荐答案

你应该扩展AppenderSkeleton类,(引用javadoc) 提供常用功能的代码,例如支持阈值过滤和对常规过滤器的支持。

You should extend AppenderSkeleton class, that (quoting javadoc) "provides the code for common functionality, such as support for threshold filtering and support for general filters."

如果您阅读了AppenderSkeleton的代码,您会看到它处理几乎所有,只留给你:

If you read the code of AppenderSkeleton, you'll see that it handles almost all, leaving to you just:


  1. protected void append(LoggingEvent event)

  2. public void close()

  3. public boolean requiresLayout()

核心方法是追加。请记住,您不需要在其中实现过滤逻辑,因为它已经在doAppend中实现,而doAppend又调用append。
这里我创建了一个(相当无用的)类,它将日志条目存储在ArrayList中,就像演示一样。

The core method is append. Remember that you don't need to implement the filtering logic in it because it is already implemented in doAppend that in turn calls append. Here I made a (quite useless) class that stores the log entries in an ArrayList, just as a demo.

public /*static*/ class MyAppender extends AppenderSkeleton {
    ArrayList<LoggingEvent> eventsList = new ArrayList();

    @Override
    protected void append(LoggingEvent event) {
        eventsList.add(event);
    }

    public void close() {
    }

    public boolean requiresLayout() {
        return false;
    }

}

好的,让我们测试一下:

Ok, let's test it:

public static void main (String [] args) {

    Logger l = Logger.getLogger("test");

    MyAppender app = new MyAppender();

    l.addAppender(app);

    l.warn("first");
    l.warn("second");
    l.warn("third");

    l.trace("fourth shouldn't be printed");

    for (LoggingEvent le: app.eventsList) {
        System.out.println("***" + le.getMessage());
    }
} 

你应该有第一个,第二个, 第三印刷;不应打印第四条消息,因为根记录器的日志级别是调试,而事件级别是跟踪。这证明AbstractSkeleton正确地为我们实现了级别管理。所以这肯定是要走的路......现在的问题是:为什么你需要一个自定义的appender,而有许多内置的日志几乎到达任何目的地? (顺便说一下从log4j开始的好地方: http://logging.apache.org/log4j /1.2/manual.html

You should have "first", "second", "third" printed; the fourth message shouldn't be printed since the log level of root logger is debug while the event level is trace. This proves that AbstractSkeleton implements "level management" correctly for us. So that's definitely seems the way to go... now the question: why do you need a custom appender while there are many built in that log to almost any destination? (btw a good place to start with log4j: http://logging.apache.org/log4j/1.2/manual.html)

这篇关于如何在log4j中创建自己的Appender?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆