1. 程式人生 > >IDEA+Log4j2 設定控制檯列印彩色日誌

IDEA+Log4j2 設定控制檯列印彩色日誌

在Log4j 2.10以前的版本,pattern中配置%highlight屬性是可以正常列印彩色日誌的

例如:

pattern: "%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight{%-5level} [%t] %highlight{%c{1.}.%M(%L)}: %msg%n"

但是更新到2.10版本以後,控制檯中就無法顯示彩色日誌了,各種級別的日誌混雜在一起,難以閱讀

通過查閱官方文件,發現在2.10版本以後,Log4j2預設關閉了Jansi(一個支援輸出ANSI顏色的類庫)

ANSI Styling on Windows
ANSI escape sequences are supported natively on many platforms but are not by default on Windows. To enable ANSI support add the Jansi jar to your application and set property log4j.skipJansi to false. This allows Log4j to use Jansi to add ANSI escape codes when writing to the console.

NOTE: Prior to Log4j 2.10, Jansi was enabled by default. The fact that Jansi requires native code means that Jansi can only be loaded by a single class loader. For web applications this means the Jansi jar has to be in the web container's classpath. To avoid causing problems for web applications, Log4j will no longer automatically try to load Jansi without explicit configuration from Log4j 2.10 onward.

可見,配置 log4j.skipJansi 這個全域性屬性即可。

IDEA中,點選右上角->Edit Configurations,在VM options中新增

-Dlog4j.skipJansi=false

啟動應用,顯示效果如下: