logback 實現 (ASNI)彩色日誌(還原Spring boot 彩色日誌)
阿新 • • 發佈:2019-01-01
介紹
ASNI
ANSI是一種字元程式碼,為使計算機支援更多語言,通常使用 0x00~0x7f 範圍的1 個位元組來表示 1 個英文字元。超出此範圍的使用0x80~0xFFFF來編碼,即擴充套件的ASCII編碼。
logback
Logback是由log4j創始人設計的又一個開源日誌元件。logback當前分成三個模組:logback-core,logback- classic和logback-access。logback-core是其它兩個模組的基礎模組。logback-classic是log4j的一個 改良版本。此外logback-classic完整實現SLF4J API使你可以很方便地更換成其它日誌系統如log4j或JDK14 Logging。logback-access
自定義日誌等級高亮顏色
- ANSI 簡單輸出測試
public static void main(String[] args) {
System.out.println("\033[32m test \033[39m 時間");
}
輸出結果
- ASNI 顏色編碼說明
ANSIConstants | ASNI | 顏色 |
---|---|---|
ESC_START | \033[ | 編碼開始標識 |
BLACK_FG | 30 | BLACK_FG |
RED_FG | 31 | RED_FG |
GREEN_FG | 32 | GREEN_FG |
YELLOW_FG | 33 | YELLOW_FG |
BLUE_FG | 34 | BLUE_FG |
MAGENTA_FG | 35 | MAGENTA_FG |
CYAN_FG | 36 | CYAN_FG |
WHITE_FG | 37 | WHITE_FG |
DEFAULT_FG | 39 | DEFAULT_FG |
ESC_END | m | 編碼結束標識 |
- logback 自定義等級高亮顏色
package com.easy.assembly.logging;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.color.ANSIConstants;
import ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase;
/**
* 自定義日誌等級高亮顏色
*
* @author kun
*
*/
public class EasyHighlightingCompositeConverter extends ForegroundCompositeConverterBase<ILoggingEvent> {
/**
* (non-Javadoc)
*
* @see ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase#
* getForegroundColorCode(java.lang.Object)
*/
protected String getForegroundColorCode(ILoggingEvent event) {
switch (event.getLevel().toInt()) {
case Level.ERROR_INT:
return ANSIConstants.RED_FG;
case Level.WARN_INT:
return ANSIConstants.YELLOW_FG;
case Level.INFO_INT:
return ANSIConstants.GREEN_FG;
case Level.DEBUG_INT:
return ANSIConstants.MAGENTA_FG;
default:
return null;
}
}
}
自定義 程序ID 獲取
package com.easy.assembly.logging;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
/**
* 程序ID 獲取
*
* @author kun
*
*/
public class ProcessIdClassicConverter extends ClassicConverter {
/**
* (non-Javadoc)
*
* @see ch.qos.logback.core.pattern.Converter#convert(java.lang.Object)
*/
public String convert(ILoggingEvent event) {
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
String name = runtime.getName();
return name.substring(0, name.indexOf("@"));
}
}
自定義PatternLayout
package com.easy.assembly.logging;
import java.util.HashMap;
import java.util.Map;
import ch.qos.logback.classic.pattern.CallerDataConverter;
import ch.qos.logback.classic.pattern.ClassOfCallerConverter;
import ch.qos.logback.classic.pattern.ContextNameConverter;
import ch.qos.logback.classic.pattern.DateConverter;
import ch.qos.logback.classic.pattern.EnsureExceptionHandling;
import ch.qos.logback.classic.pattern.ExtendedThrowableProxyConverter;
import ch.qos.logback.classic.pattern.FileOfCallerConverter;
import ch.qos.logback.classic.pattern.LevelConverter;
import ch.qos.logback.classic.pattern.LineOfCallerConverter;
import ch.qos.logback.classic.pattern.LineSeparatorConverter;
import ch.qos.logback.classic.pattern.LocalSequenceNumberConverter;
import ch.qos.logback.classic.pattern.LoggerConverter;
import ch.qos.logback.classic.pattern.MDCConverter;
import ch.qos.logback.classic.pattern.MarkerConverter;
import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.pattern.MethodOfCallerConverter;
import ch.qos.logback.classic.pattern.NopThrowableInformationConverter;
import ch.qos.logback.classic.pattern.PropertyConverter;
import ch.qos.logback.classic.pattern.RelativeTimeConverter;
import ch.qos.logback.classic.pattern.RootCauseFirstThrowableProxyConverter;
import ch.qos.logback.classic.pattern.ThreadConverter;
import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.pattern.color.HighlightingCompositeConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.pattern.PatternLayoutBase;
import ch.qos.logback.core.pattern.color.BlackCompositeConverter;
import ch.qos.logback.core.pattern.color.BlueCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldBlueCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldCyanCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldGreenCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldMagentaCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldRedCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldWhiteCompositeConverter;
import ch.qos.logback.core.pattern.color.BoldYellowCompositeConverter;
import ch.qos.logback.core.pattern.color.CyanCompositeConverter;
import ch.qos.logback.core.pattern.color.GrayCompositeConverter;
import ch.qos.logback.core.pattern.color.GreenCompositeConverter;
import ch.qos.logback.core.pattern.color.MagentaCompositeConverter;
import ch.qos.logback.core.pattern.color.RedCompositeConverter;
import ch.qos.logback.core.pattern.color.WhiteCompositeConverter;
import ch.qos.logback.core.pattern.color.YellowCompositeConverter;
import ch.qos.logback.core.pattern.parser.Parser;
/**
* 自定義內容加入
*
* @author kun
*
*/
public class EasyPatternLayout extends PatternLayoutBase<ILoggingEvent> {
public static final Map<String, String> defaultConverterMap = new HashMap<String, String>();
public static final String HEADER_PREFIX = "#logback.classic pattern: ";
static {
defaultConverterMap.putAll(Parser.DEFAULT_COMPOSITE_CONVERTER_MAP);
defaultConverterMap.put("d", DateConverter.class.getName());
defaultConverterMap.put("date", DateConverter.class.getName());
defaultConverterMap.put("r", RelativeTimeConverter.class.getName());
defaultConverterMap.put("relative", RelativeTimeConverter.class.getName());
defaultConverterMap.put("level", LevelConverter.class.getName());
defaultConverterMap.put("le", LevelConverter.class.getName());
defaultConverterMap.put("p", LevelConverter.class.getName());
defaultConverterMap.put("t", ThreadConverter.class.getName());
defaultConverterMap.put("thread", ThreadConverter.class.getName());
defaultConverterMap.put("lo", LoggerConverter.class.getName());
defaultConverterMap.put("logger", LoggerConverter.class.getName());
defaultConverterMap.put("c", LoggerConverter.class.getName());
defaultConverterMap.put("m", MessageConverter.class.getName());
defaultConverterMap.put("msg", MessageConverter.class.getName());
defaultConverterMap.put("message", MessageConverter.class.getName());
defaultConverterMap.put("C", ClassOfCallerConverter.class.getName());
defaultConverterMap.put("class", ClassOfCallerConverter.class.getName());
defaultConverterMap.put("M", MethodOfCallerConverter.class.getName());
defaultConverterMap.put("method", MethodOfCallerConverter.class.getName());
defaultConverterMap.put("L", LineOfCallerConverter.class.getName());
defaultConverterMap.put("line", LineOfCallerConverter.class.getName());
defaultConverterMap.put("F", FileOfCallerConverter.class.getName());
defaultConverterMap.put("file", FileOfCallerConverter.class.getName());
defaultConverterMap.put("X", MDCConverter.class.getName());
defaultConverterMap.put("mdc", MDCConverter.class.getName());
defaultConverterMap.put("ex", ThrowableProxyConverter.class.getName());
defaultConverterMap.put("exception", ThrowableProxyConverter.class.getName());
defaultConverterMap.put("rEx", RootCauseFirstThrowableProxyConverter.class.getName());
defaultConverterMap.put("rootException", RootCauseFirstThrowableProxyConverter.class.getName());
defaultConverterMap.put("throwable", ThrowableProxyConverter.class.getName());
defaultConverterMap.put("xEx", ExtendedThrowableProxyConverter.class.getName());
defaultConverterMap.put("xException", ExtendedThrowableProxyConverter.class.getName());
defaultConverterMap.put("xThrowable", ExtendedThrowableProxyConverter.class.getName());
defaultConverterMap.put("nopex", NopThrowableInformationConverter.class.getName());
defaultConverterMap.put("nopexception", NopThrowableInformationConverter.class.getName());
defaultConverterMap.put("cn", ContextNameConverter.class.getName());
defaultConverterMap.put("contextName", ContextNameConverter.class.getName());
defaultConverterMap.put("caller", CallerDataConverter.class.getName());
defaultConverterMap.put("marker", MarkerConverter.class.getName());
defaultConverterMap.put("property", PropertyConverter.class.getName());
defaultConverterMap.put("n", LineSeparatorConverter.class.getName());
defaultConverterMap.put("black", BlackCompositeConverter.class.getName());
defaultConverterMap.put("red", RedCompositeConverter.class.getName());
defaultConverterMap.put("green", GreenCompositeConverter.class.getName());
defaultConverterMap.put("yellow", YellowCompositeConverter.class.getName());
defaultConverterMap.put("blue", BlueCompositeConverter.class.getName());
defaultConverterMap.put("magenta", MagentaCompositeConverter.class.getName());
defaultConverterMap.put("cyan", CyanCompositeConverter.class.getName());
defaultConverterMap.put("white", WhiteCompositeConverter.class.getName());
defaultConverterMap.put("gray", GrayCompositeConverter.class.getName());
defaultConverterMap.put("boldRed", BoldRedCompositeConverter.class.getName());
defaultConverterMap.put("boldGreen", BoldGreenCompositeConverter.class.getName());
defaultConverterMap.put("boldYellow", BoldYellowCompositeConverter.class.getName());
defaultConverterMap.put("boldBlue", BoldBlueCompositeConverter.class.getName());
defaultConverterMap.put("boldMagenta", BoldMagentaCompositeConverter.class.getName());
defaultConverterMap.put("boldCyan", BoldCyanCompositeConverter.class.getName());
defaultConverterMap.put("boldWhite", BoldWhiteCompositeConverter.class.getName());
defaultConverterMap.put("highlight", HighlightingCompositeConverter.class.getName());
defaultConverterMap.put("lsn", LocalSequenceNumberConverter.class.getName());
defaultConverterMap.put("easyHighlight", EasyHighlightingCompositeConverter.class.getName());
defaultConverterMap.put("pid", ProcessIdClassicConverter.class.getName());
}
public EasyPatternLayout() {
this.postCompileProcessor = new EnsureExceptionHandling();
}
public Map<String, String> getDefaultConverterMap() {
return defaultConverterMap;
}
public String doLayout(ILoggingEvent event) {
if (!isStarted()) {
return CoreConstants.EMPTY_STRING;
}
return writeLoopOnConverters(event);
}
@Override
protected String getPresentationHeaderPrefix() {
return HEADER_PREFIX;
}
}
自定義配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<property resource="logging-test.properties" />
<property name="STDOUT_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} %easyHighlight(%5.5level) %magenta(%pid) --- [%15.15thread] %cyan(%-40.40logger{39} [%4.4line]) : %msg%n" />
<property name="FILE_PATTERN"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5.5level %pid --- [%15.15thread] %-40.40logger{40} [%4.4line] : %msg%n" />
<property name="LOGGINE_FILE_HOME" value="log" />
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder
class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="com.easy.assembly.logging.EasyPatternLayout">
<pattern>
${logging.console.pattern:-${STDOUT_PATTERN}}
</pattern>
</layout>
</encoder>
</appender>
<appender name="FILE_VIEW"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logging.file.path:-${LOGGINE_FILE_HOME}}/${logging.file.name:-easy}-view.log
</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logging.file.name:-easy}-view-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<maxFileSize>${logging.file.max.size:-100MB}</maxFileSize>
<maxHistory>${logging.file.max.history:-60}</maxHistory>
<totalSizeCap>${logging.file.total.size,cap:-20GB}</totalSizeCap>
</rollingPolicy>
<encoder
class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="com.easy.assembly.logging.EasyPatternLayout">
<pattern>
${logging.console.pattern:-${STDOUT_PATTERN}}
</pattern>
</layout>
</encoder>
</appender>
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logging.file.path:-${LOGGINE_FILE_HOME}}/${logging.file.name:-easy}.log
</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logging.file.name:-easy}-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<maxFileSize>${logging.file.max.size:-100MB}</maxFileSize>
<maxHistory>${logging.file.max.history:-60}</maxHistory>
<totalSizeCap>${logging.file.total.size,cap:-20GB}</totalSizeCap>
</rollingPolicy>
<encoder
class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="com.easy.assembly.logging.EasyPatternLayout">
<pattern>
${logging.file.pattern:-${FILE_PATTERN}}
</pattern>
</layout>
</encoder>
</appender>
<appender name="FILE_ERROR_VIEW"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logging.file.path:-${LOGGINE_FILE_HOME}}/${logging.file.name:-easy}-error-view.log
</file>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logging.file.name:-easy}-error-view-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<maxFileSize>${logging.file.max.size:-100MB}</maxFileSize>
<maxHistory>${logging.file.max.history:-60}</maxHistory>
<totalSizeCap>${logging.file.total.size,cap:-20GB}</totalSizeCap>
</rollingPolicy>
<encoder
class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="com.easy.assembly.logging.EasyPatternLayout">
<pattern>
${logging.console.pattern:-${STDOUT_PATTERN}}
</pattern>
</layout>
</encoder>
</appender>
<appender name="FILE_ERROR"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logging.file.path:-${LOGGINE_FILE_HOME}}/${logging.file.name:-easy}-error.log
</file>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${logging.file.name:-easy}-error-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<maxFileSize>${logging.file.max.size:-100MB}</maxFileSize>
<maxHistory>${logging.file.max.history:-60}</maxHistory>
<totalSizeCap>${logging.file.total.size,cap:-20GB}</totalSizeCap>
</rollingPolicy>
<encoder
class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="com.easy.assembly.logging.EasyPatternLayout">
<pattern>
${logging.file.pattern:-${FILE_PATTERN}}
</pattern>
</layout>
</encoder>
</appender>
<root level="${logging.level:-info}">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
<appender-ref ref="FILE_VIEW" />
<appender-ref ref="FILE_ERROR" />
<appender-ref ref="FILE_ERROR_VIEW" />
</root>
</configuration>