How to properly configure custom PatternSelector in log4j2 Java Properties file

46 views Asked by At

I am using a properties file to configure Log4j2 and am having trouble figuring out how to configure my custom PatternSelector plugin. I have my appender defined with:

appender.rolling.layout.type = MyCustomPatternSelector
appender.rolling.layout.defaultPattern = %d %p{length=5} [%t] %c{1} - %m%n
appender.rolling.layout.alternatePattern = %m%n

The first few lines of MyCustomPatternSelector look like this

@Plugin(name="MyCustomPatternSelector", category=Node.CATEGORY, elementType=PatternSelector.ELEMENT_TYPE, printObject = true)
public class MyCustomPatternSelector implements PatternSelector, LocationAware {

    public static class Builder implements org.apache.logging.log4j.core.util.Builder<MyCusstomPatternSelector> {

        @PluginBuilderAttribute("defaultPattern")
        private String defaultPattern;

        @PluginBuilderAttribute("alternatePattern")
        private String alternatePattern;

When I call Configurator.reconfigure, I get the following error:

2024-01-18 14:38:28,306 main ERROR appender RollingFile has no parameter that matches element MyCustomPatternSelector

My properties are obviously wrong by all the examples I find for PatternSelector are XML configurations. What should my properties file look like??

My PatternSelector plugin is getting loaded but the appender ends up using the default layout because my custom pattern selector is not added to the appender.

1

There are 1 answers

0
Piotr P. Karwasz On

The problem with your configuration is that PatternSelector is an attribute of PatternLayout not RollingFileAppender (cf. PatternLayout.Builder).

Therefore you need to move your selector one level down:

appender.rolling.type = RollingFile
...
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.s.type = MyCustomPatternSelector
appender.rolling.layout.s.defaultPattern = %d %p{length=5} [%t] %c{1} - %m%n
appender.rolling.layout.s.alternatePattern = %m%n

Remark: in the upcoming version 3.0.0-beta1 the properties configuration you are using will be removed and replaced with one based on jackson-dataformat-properties (cf. PR#2170).

Using the new configuration factory, your configuration could look like this:

Appenders.RollingFile.PatternLayout.MyCustomPatterSelector.defaultPattern = %d %p{length=5} [%t] %c{1} - %m%n
Appenders.RollingFile.PatternLayout.MyCustomPatterSelector.alternatePattern = %m%n