Spring Framework/Spring Boot

[Spring Boot] logback 로그 레벨별 색 지정

장쫄깃 2024. 7. 16. 20:45
728x90


CustomHighlightConverter 구현


ForegroundCompositeConverterBase 상속 객체를 구현한다.

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.color.ANSIConstants;
import ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase;

/**
 * logback-spring 로그 레벨별 색상 지정 Custom Converter Class
 */
public class CustomHighlightConverter extends ForegroundCompositeConverterBase<ILoggingEvent> {

    @Override
    protected String getForegroundColorCode(ILoggingEvent event) {
        return switch (event.getLevel().toString()) {
            case "ERROR" -> ANSIConstants.BOLD + ANSIConstants.RED_FG;
            case "WARN" -> ANSIConstants.BOLD + ANSIConstants.YELLOW_FG;
            case "INFO" -> ANSIConstants.BOLD + ANSIConstants.GREEN_FG;
            case "DEBUG" -> ANSIConstants.BOLD + ANSIConstants.BLUE_FG;
            case "TRACE" -> ANSIConstants.BLUE_FG;
            default -> ANSIConstants.DEFAULT_FG;
        };
    }

}

 

 

logback-spring.xml


logback-spring.xml에 CustomHighlightConverter를 적용한다.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- Custom Highlight Converter -->
    <conversionRule conversionWord="highlight" converterClass="com.jdh.sample.config.log.CustomHighlightConverter"/>

    <property name="LOG_LEVEL_PATTERN" value="%highlight(%-5level)"/>

    <appender name="STDOUT"
              class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%boldMagenta(%d{MM-dd HH:mm:ss}) [${LOG_LEVEL_PATTERN}] %cyan(%logger{5}.%M) - %msg %n</pattern>
        </encoder>
    </appender>
    
    ...
    
    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

 

 

결과


 

로그별 색상이 다르게 출력되는 것을 볼 수 있다.

 

728x90