Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
Meng Lu Avatar asked Aug 27 '15 16:08

Meng Lu


Video Answer


2 Answers

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>
like image 141
Peter Dolberg Avatar answered Sep 25 '22 16:09

Peter Dolberg


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);
    }

}
like image 26
Florian Schaetz Avatar answered Sep 23 '22 16:09

Florian Schaetz