简体   繁体   中英

Spring Boot Logging override Colours

I wish to use different colours to distinguish between INFO, DEBUG and TRACE in Spring Ansi Coloured Logs, as they are currently all set to Green (see table below)

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

Color coding is configured by using the %clr conversion word. In its simplest form, the converter colors the output according to the log level, as shown in the following example:

%clr(%5p) The following table describes the mapping of log levels to colors:

Level Color
FATAL Red
ERROR Red
WARN Yellow
INFO Green
DEBUG Green
TRACE Green

It would appear I need to override the %clr conversion word, but I cannot find anything in the docs about that.

If it makes a difference I am using log4j2, and wish to build this into the application.

You can use GrepConsole plugin (Idea) for it. See more here

I don't see any conventional/documented way to override colors at a level scope. For example: ColorConverter for log4j2 doesn't like to be opened for that kind of options.
You could try to define your Log42 color plugin implementation, that is a plugin implementation annotating with that log4j2 Plugin annotation:

@Plugin(name = "color", category = PatternConverter.CATEGORY)

But not sure that it works or works reliably since Spring defines already one for that.
For the record here is the ColorConverter source code for logback.

By the way, if it is enough, you could define a pattern by starting from the CONSOLE_LOG_PATTERN defined in the Spring Boot source code for log4j2:

<Property name="CONSOLE_LOG_PATTERN">%clr{%d{${sys:LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${sys:LOG_LEVEL_PATTERN}} %clr{%pid}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>

First, the %clr defined is a logback conversion rule and is the one with the color logic. This conversion rule is defined in the spring class DefaultLogbackConfiguration .

There we can see that spring adds the ColorConverter with the clr conversionWord in the logback configurator.

From this exploration, my conclusion is that you have to create your own logback.xml file (it disable spring default configuration, according to the documentation). With this file in place, you can add your own conversion rule like this:

<conversionRule conversionWord="nanos" 
              converterClass="chapters.layouts.MySampleConverter" />

After that you should change the property logging.pattern.console using your conversionWord created above, instead of %clr.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM