如何在spring-boot中为ANSI颜色功能配置logback?

Hus*_*sha 13 logback spring-boot

我有一个在Windows上运行的spring-boot应用程序.我在我的项目中添加了jansi(v1.8)依赖项,用于在Windows上启用彩色终端输出.

包含了spring-boot中提供的logback配置,即在logback.xml中添加了以下行.

<include resource="org/springframework/boot/logging/logback/base.xml" />
Run Code Online (Sandbox Code Playgroud)

我不清楚在logback.xml中配置什么,以便它的日志语句按照spring-boot提供的base.xml进行着色.对不起,如果是一个非常愚蠢的问题,我是一个新手回归.

谢谢 !

And*_*son 19

这在Logback文档的着色部分中描述:

如上所述通过括号分组允许对子图案进行着色.从版本1.0.5开始,PatternLayout识别"%black","%red","%green","%yellow","%blue","%magenta","%cyan","%white"," %grey","%boldRed","%boldGreen","%boldYellow","%boldBlue","%boldMagenta","%boldCyan","%boldWhite"和"%highlight"作为转换字.这些转换字旨在包含子模式.由着色字包围的任何子图案将以指定的颜色输出.

还有一个示例配置文件,向您展示如何使用转换字:

<configuration debug="true">
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- On Windows machines setting withJansi to true enables ANSI
         color code interpretation by the Jansi library. This requires
         org.fusesource.jansi:jansi:1.8 on the class path.  Note that
         Unix-based operating systems such as Linux and Mac OS X
         support ANSI color codes by default. -->
    <withJansi>true</withJansi>
    <encoder>
      <pattern>[%thread] %highlight(%-5level) %cyan(%logger{15}) - %msg %n</pattern>
    </encoder>
  </appender>
  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
Run Code Online (Sandbox Code Playgroud)

  • 你是对的。但我的问题是在 Spring Boot 的上下文中。如果您看到与 spring-boot 捆绑在一起的 base.xml 已经包含配置。如何激活是我的问题?我需要在 logback.xml 中设置什么? (2认同)

acs*_*404 17

Spring boot增加了对此的支持:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html#boot-features-logging-color-coded-output

刚设置

spring.output.ansi.enabled=always
Run Code Online (Sandbox Code Playgroud)

  • 不仅要设置“spring.output.ansi.enabled=ALWAYS”,还需要在日志记录模式中使用“%clr”转换字。例如,如果日志记录模式以前是 `logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level - %msg%n`,现在它可以完全着色为 `logging .pattern.console=%clr(%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level - %msg%n)` 或仅在控制台 `logging.pattern.console 中为日志级别着色=%d{yyyy-MM-dd HH:mm:ss.SSS} $clr(%-5level) - %msg%n` 我花了几个小时才把它记入我厚厚的头骨中。 (6认同)