Java DynamicConverter-class And Method Code Example


Here is an example of how to use the logback.core.pattern.DynamicConverter class to create a custom pattern converter that can dynamically change its format based on the properties of the event:

import ch.qos.logback.core.pattern.DynamicConverter;
import ch.qos.logback.core.spi.ContextAware;
import ch.qos.logback.core.spi.LifeCycle;

public class MyDynamicConverter extends DynamicConverter<Object> implements ContextAware, LifeCycle {
    private String option;
    private boolean started;

    @Override
    public void start() {
        started = true;
    }

    @Override
    public void stop() {
        started = false;
    }

    @Override
    public boolean isStarted() {
        return started;
    }

    @Override
    public void setOptionList(List<String> optionList) {
        if (optionList != null && optionList.size() > 0) {
            option = optionList.get(0);
        }
    }

    @Override
    public String convert(Object event) {
        if (isStarted()) {
            if ("uppercase".equals(option)) {
                return event.toString().toUpperCase();
            } else {
                return event.toString();
            }
        } else {
            return "Converter is not started";
        }
    }
}

In this example, a custom converter called MyDynamicConverter is created, which inherits from DynamicConverter and implements the ContextAware and LifeCycle interfaces. The converter takes an option which is passed in during configuration, the option value is "uppercase" the event will be returned in uppercase or else the event will be returned as it is.

You will need to configure your logback.xml to use this new converter, for example, by including a reference to it in the conversion pattern, like

<conversionRule conversionWord="dynamic" converterClass="path.to.MyDynamicConverter" />

then, you could use it in your pattern layout like this

<pattern>%dynamic{uppercase} %msg%n</pattern>

It's important to note that, the DynamicConverter class provides a template method, convert, that subclasses need to implement. The convert method takes a single argument, an object of type E, which represents the event.

The DynamicConverter also provides a template method, setOptionList, which subclasses can use to set the options, and should call the super implementation when finished.

Please ensure to close the converter after use and keep in mind the fact that converters are stateful, so it is important to call stop method after using it.