How to enable ANSI colors with Log4j2 on Windows Terminal?

Viewed 631

Unlike CMD and PowerShell, the new Windows Terminal supports ANSI colors out of the box. A quick test program can confirm that things are working:

public class Color {
    public static void main(String[] args) {
        System.out.println("\u001b[32mHello, World\n\u001b[0m");
    }
}

Log4j2 doesn't seem to be picking up on this though. I have this sequence in my PatternLayout:

%highlight{%-5level}{FATAL=bg_red white, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue}

This works on macOS and Linux, but not Windows. Looking at the docs, I have disableAnsi and noConsoleNoAnsi, but the defaults seem to be what I want and explicitly setting them doesn't have any effect.

I did make sure that I included JANSI in my project, even though I didn't think it should be necessary, but it also doesn't make any difference.

What option am I missing to get the colors to work?

1 Answers

As per the docs, I used the system property log4j.skipJansi.

In Gradle you can for example modify system properties for test tasks as follows (using Kotlin DSL):

tasks.withType<Test> {
    systemProperty("log4j.skipJansi", "false")
}

// don't forget to add jANSI to your dependencies
dependencies {
    :
    api(group = "org.fusesource.jansi", name = "jansi", version = "1.18")
}
Related