简体   繁体   中英

How to configure null appender in log4j2

Log4j 1.* has a null appender class , but I couldn't find the equivalent in log4j 2. Is there one? How does one configure a null appender in log4j2.xml?

There is a NullAppender class as of Log4j2 version 2.7. Earlier versions didn't have it. The name it uses in the configuration file is "Null". It can be added to the Appenders list like so:

<Appenders>
  <Null name="arbritrary_name" />
</Appenders>

Use the CountingNoOp appender.

<Appenders>
  <CountingNoOp name="DEV_NULL" />
</Appenders>

The NullAppendar was basically an (almost) empty implementation of the Appender interface, using the AppenderSkeleton as a base class. Doing the same in Log4j2 is trivial, but you'll need some boilerplate code to make it work, see the Apache documentation on custom appenders .

@Plugin(name = "NullAppender", category = "Core", elementType = "appender", printObject = true)
public class NullAppender extends AbstractAppender {

    private static final long serialVersionUID = -701612541126635333L;

    private NullAppender(String name, Filter filter, Layout<? extends Serializable> layout) {
        super(name, filter, layout);    
    }

    @Override
    public void append(LogEvent event) {
        // do exactly nothing
    }

    // blatantly stolen from the Apache doc, all errors (C) by me
    @PluginFactory
    public static NullAppender createAppender(@PluginAttribute("name") String name,
                                              @PluginElement("Layout") Layout layout,
                                              @PluginElement("Filters") Filter filter) {

        if (name == null) {
            LOGGER.error("No name provided for NullAppender");
            return null;
        }

        if (layout == null) {
            layout = PatternLayout.createDefaultLayout();
        }
        return new NullAppender(name, filter, layout);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM