Java FormattingConverter-class And Method Code Example


Here is an example of how to use the logback.core.pattern.FormattingConverter class to create a custom pattern converter that can format the output of a log event:

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

public class MyFormattingConverter extends FormattingConverter {
    private String option;

    @Override
    public void setFormat(String format) {
        super.setFormat(format);
        option = getFirstOption();
    }

    @Override
    public String convert(Object event) {
        String formatted = String.format(getFormat(), event);
        if ("uppercase".equals(option)) {
            return formatted.toUpperCase();
        } else {
            return formatted;
        }
    }
}

In this example, a custom converter called MyFormattingConverter is created, which inherits from FormattingConverter. 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.

The setFormat method is overridden to extract the first option, then the convert method is overridden to use the format and the option to format the event.

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="format" converterClass="path.to.MyFormattingConverter" />

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

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

It's important to note that, the FormattingConverter class provides a template method, convert, that subclasses need