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

查看:27
本文介绍了如何在 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()

核心方法是append.请记住,您不需要在其中实现过滤逻辑,因为它已经在 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天全站免登陆