在我的这一侧,我通过创建一个自定义的
PatternLayout
来找到了一种解决方法。它的工作是通过当终端不支持颜色时,替换默认的颜色转换器为不执行任何操作的转换器。
如下:
- 我也使用Picocli
- 根据我的经验,Picocli的ANSI颜色支持检测启发式算法非常好。
我使用它来确定何时应该删除颜色转换器。(但你可以使用任何其他启发式算法或像
https://dev59.com/_l0Z5IYBdhLWcg3wzC5W#36790201中那样使用环境变量,而无需janino依赖项)
代码看起来像这样:
public class ColorAwarePatternLayout extends PatternLayout {
static {
if (!Ansi.AUTO.enabled()) {
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>
请查看:
(请参见https://github.com/eclipse/leshan/pull/1068)