Radek Postołowicz Radek Postołowicz - 1 month ago 13
Java Question

Logback list properties configured via xml

I'm writing my own Layout and I want to have ability to pass it list of values from config file.

My layout code:

public class MyPatternLayout extends PatternLayout {

private ArrayList<String> test;

public ArrayList<String> getTest() {
return test;
}

public void setTest(ArrayList<String> test) {
this.test = test;
}

@Override
public String doLayout(ILoggingEvent event) {
return test.stream().collect(Collectors.joining(", ")); //temporary, for testing purposes only
}
}


Configuration:

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="rpost.MyPatternLayout">
<pattern>%date{HH:mm:ss.SSS} [%t] %-5p %c{40}:%L - %m%n</pattern>
<test>value 1</test>
<test>value 2</test>
</layout>
</encoder>
</appender>

<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>


Example above is not working - it prints nothing.

Is it possible to configure list properties? How can it be done?

Answer

I found following solution:

Configuration (the same as in question):

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <layout class="rpost.MyPatternLayout">
                <pattern>%date{HH:mm:ss.SSS} [%t] %-5p %c{40}:%L - %m%n</pattern>
                <test>value 1</test>
                <test>value 2</test>
            </layout>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

Java code:

public class MyPatternLayout extends PatternLayout {

    private List<String> test = new ArrayList<>();

    public void addTest(String test) {
        this.test.add(test);
    }

    @Override
    public String doLayout(ILoggingEvent event) {
        return test.stream().collect(Collectors.joining(", ")); //temporary, for testing purposes only
    }
}