Search code examples
javalog4jlog4j2

Log4j2 - Get appender filter programmatically


I am currently upgrading a project from using log4j1 to log4j2. There are places in the code where calls to appender.getFilter() are being made which are no longer available using the new API. Old code used org.apache.log4j.Appender and I am now currently using org.apache.logging.log4j.core.Appender.

Checking the log4j2 documentation and code I can see that filters can be added to Appenders but I am not able to find how to get them.

Is there a way to programmatically get a filter which has been applied to an Appender?


Solution

  • The getFilter() is still there, but it has been removed from the Appender interface: an appender is not required to support filters, although all those standard ones do.

    To retrieve the filter you just need to cast to Filterable:

    final Filter filter = appender instanceof Filterable ?
                          ((Filterable) appender).getFilter() :
                          null;
    

    Remark: in Log4j 2.x filters can appear in four different locations (cf. documentation).