如何在log4j2中创建自定义Appender?

时间:2014-06-13 12:17:10

标签: java logging log4j log4j2

如此链接所述:How to create a own Appender in log4j?

为了在log4j 1.x中创建自定义appender,我们必须扩展AppenderSkeleton类并实现其append方法。

类似我们如何在log4j2中创建自定义appender,因为我们没有扩展AppenderSkelton类,所有其他appender扩展了AppenderBase类。

4 个答案:

答案 0 :(得分:74)

这在log4j2中的作用与在log4j-1.2中的作用完全不同。

在log4j2中,您将为此创建一个插件。本手册中有一个自定义appender示例的说明:http://logging.apache.org/log4j/2.x/manual/extending.html#Appenders

扩展org.apache.logging.log4j.core.appender.AbstractAppender可能很方便,但这不是必需的。

当您使用@Plugin(name="MyCustomAppender", ....注释自定义Appender类时,插件名称将成为配置元素名称,因此使用自定义appender的配置将如下所示:

<Configuration packages="com.yourcompany.yourcustomappenderpackage">
  <Appenders>
    <MyCustomAppender name="ABC" otherAttribute="...">
    ...
  </Appenders>
  <Loggers><Root><AppenderRef ref="ABC" /></Root></Loggers>
</Configuration>

请注意,配置上的packages属性是包含自定义log4j2插件的所有包的逗号分隔列表。 Log4j2将在类路径中搜索这些包,注释用@Plugin注释的类。

以下是打印到控制台的示例自定义appender:

package com.yourcompany.yourcustomappenderpackage;

import java.io.Serializable;
import java.util.concurrent.locks.*;
import org.apache.logging.log4j.core.*;
import org.apache.logging.log4j.core.config.plugins.*;
import org.apache.logging.log4j.core.layout.PatternLayout;

// note: class name need not match the @Plugin name.
@Plugin(name="MyCustomAppender", category="Core", elementType="appender", printObject=true)
public final class MyCustomAppenderImpl extends AbstractAppender {

    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();

    protected MyCustomAppenderImpl(String name, Filter filter,
            Layout<? extends Serializable> layout, final boolean ignoreExceptions) {
        super(name, filter, layout, ignoreExceptions);
    }

    // The append method is where the appender does the work.
    // Given a log event, you are free to do with it what you want.
    // This example demonstrates:
    // 1. Concurrency: this method may be called by multiple threads concurrently
    // 2. How to use layouts
    // 3. Error handling
    @Override
    public void append(LogEvent event) {
        readLock.lock();
        try {
            final byte[] bytes = getLayout().toByteArray(event);
            System.out.write(bytes);
        } catch (Exception ex) {
            if (!ignoreExceptions()) {
                throw new AppenderLoggingException(ex);
            }
        } finally {
            readLock.unlock();
        }
    }

    // Your custom appender needs to declare a factory method
    // annotated with `@PluginFactory`. Log4j will parse the configuration
    // and call this factory method to construct an appender instance with
    // the configured attributes.
    @PluginFactory
    public static MyCustomAppenderImpl createAppender(
            @PluginAttribute("name") String name,
            @PluginElement("Layout") Layout<? extends Serializable> layout,
            @PluginElement("Filter") final Filter filter,
            @PluginAttribute("otherAttribute") String otherAttribute) {
        if (name == null) {
            LOGGER.error("No name provided for MyCustomAppenderImpl");
            return null;
        }
        if (layout == null) {
            layout = PatternLayout.createDefaultLayout();
        }
        return new MyCustomAppenderImpl(name, filter, layout, true);
    }
}

有关插件的更多详细信息: http://logging.apache.org/log4j/2.x/manual/plugins.html

如果手册不够,在log4j-core中查看内置appender的源代码可能会很有用。

答案 1 :(得分:1)

  

看起来插件appender在启动时被扫描,并且在运行时无法添加。这是真的吗?

在运行时添加新的appender可以使用monitorInterval属性来更新日志配置,即每60秒:

    <Configuration monitorInterval="60">

答案 2 :(得分:0)

对于需要输出到TextArea的用户,这是一个有效的调整

使TextArea保持静态

NetBeans Swing TextArea is not static, causes trouble

在框架中添加静态方法

public class MyFrame extends javax.swing.JFrame {
    ...
    public static void outputToTextArea(String message) {
        jTextArea.append(message);
    }

调用Appender的附录

@Override
public void append(LogEvent event) {
    final byte[] bytes = getLayout().toByteArray(event);
    MyFrame.outputToTextArea(new String(bytes));
}

答案 3 :(得分:0)

正如您所指出的,AppenderSkeleton不再可用,因此How to create my own Appender in log4j?中的解决方案将不起作用。

如果您期望收到多个日志消息,则由于MutableLogEvent已在多个日志消息上重用,因此无法使用Mockito或类似的库通过ArgumentCaptor创建Appender。

我为log4j2找到的最通用的解决方案是提供一个记录所有消息的模拟实现。它不需要任何其他库,例如Mockito或JMockit。

private static MockedAppender mockedAppender;
private static Logger logger;

@Before
public void setup() {
    mockedAppender.message.clear();
}

/**
 * For some reason mvn test will not work if this is @Before, but in eclipse it works! As a
 * result, we use @BeforeClass.
 */
@BeforeClass
public static void setupClass() {
    mockedAppender = new MockedAppender();
    logger = (Logger)LogManager.getLogger(ClassWithLoggingToTest.class);
    logger.addAppender(mockedAppender);
    logger.setLevel(Level.INFO);
}

@AfterClass
public static void teardown() {
    logger.removeAppender(mockedAppender);
}

@Test
public void test() {
    // do something that causes logs
    for (String e : mockedAppender.message) {
        // add asserts for the log messages
    }
}

private static class MockedAppender extends AbstractAppender {

    List<String> message = new ArrayList<>();

    protected MockedAppender() {
        super("MockedAppender", null, null);
    }

    @Override
    public void append(LogEvent event) {
        message.add(event.getMessage().getFormattedMessage());
    }
}