On my side, I found a workaround by creating a custom PatternLayout
.
Its job is to replace default color converters by converters doing nothing when the terminal doesn't support color.
As :
- I also use Picocli
- and in my experience, the Picocli ANSI color support detection heuristic is pretty good.
I use it to know when the color converter should be removed. (but you could use any other heuristic or using an environmental variable like in https://mcmap.net/q/597553/-logback-use-colored-output-only-when-logging-to-a-real-terminal without the need of janino dependency)
The code looks like this :
/**
* A Logback Pattern Layout that uses Picocli ANSI color
* heuristic to apply ANSI color only on the terminal which
* supports it.
*/
public class ColorAwarePatternLayout extends PatternLayout {
static {
if (!Ansi.AUTO.enabled()) { // Usage of Picocli heuristic
DEFAULT_CONVERTER_MAP.put("black", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("red", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("green", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("yellow", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("blue", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("magenta", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("cyan", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("white", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("gray", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("boldRed", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("boldGreen", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("boldYellow", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("boldBlue", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("boldMagenta", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("boldCyan", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("boldWhite", NoColorConverter.class.getName());
DEFAULT_CONVERTER_MAP.put("highlight", NoColorConverter.class.getName());
}
}
}
public class NoColorConverter<E> extends CompositeConverter<E> {
@Override
protected String transform(E event, String in) {
return in;
}
}
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="your.package.ColorAwarePatternLayout">
<pattern>%gray(%30.30logger{0}) %gray(%d) [%highlight(%p)] %m%n</pattern>
</layout>
</encoder>
</appender>
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
</configuration>
(See https://github.com/eclipse/leshan/pull/1068)
if
apparently isn't allowed insideroot
tag, so your configuration should probably be updated. – Slushy