1. ide需要配置支持颜色转换,eclipse配置方式如下图(在marketspace上搜索安装ansi):
2. 自定义颜色配置类(我这里是每种日志级别定义一种颜色)
1 package com.example.demo.logtest.config; 2 3 import ch.qos.logback.classic.Level; 4 import ch.qos.logback.classic.spi.ILoggingEvent; 5 import ch.qos.logback.core.pattern.color.ANSIConstants; 6 import ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase; 7 8 public class LogColor extends ForegroundCompositeConverterBase<ILoggingEvent>{ 9 10 @Override 11 protected String getForegroundColorCode(ILoggingEvent event) { 12 Level level = event.getLevel(); 13 switch(level.toInt()) { 14 case Level.ERROR_INT: 15 return ANSIConstants.RED_FG; 16 case Level.WARN_INT: 17 return ANSIConstants.YELLOW_FG; 18 case Level.INFO_INT: 19 return ANSIConstants.BLUE_FG; 20 case Level.DEBUG_INT: 21 return ANSIConstants.GREEN_FG; 22 case Level.TRACE_INT: 23 return ANSIConstants.DEFAULT_FG; 24 default: 25 return ANSIConstants.DEFAULT_FG; 26 } 27 } 28 29 }
3.修改logback的配置(主要配置内容为下面1,2两处)
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="false"> <contextName>Logback For demo Mobile</contextName> <!-- 1.这里指定控制颜色的类为上面写的java类,关键字为mycolor --> <conversionRule conversionWord="mycolor" converterClass="com.example.demo.logtest.config.LogColor" /> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!-- <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %cyan([%thread]) %magenta(%-5level) %cyan(%logger{15}) - %msg%n</pattern> -->
<!-- 2.下面的mycolor,表示使用自定义的颜色类包装日志,使用方式是 %mycolor(), 注意,我这里是包装了整行日志,也可以只把关键信息用mycolor括起来 -->
<pattern>%mycolor(%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{15} - %msg%n)</pattern>
</encoder> </appender> <appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--日志文件输出的文件名 ,每天保存(侧翻)一次 --> <FileNamePattern>./logs2/%d{yyyy-MM-dd}.log</FileNamePattern> <!--日志文件保留天数 --> <MaxHistory>180</MaxHistory> </rollingPolicy> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{25} -%msg%n</pattern> </encoder> <!--日志文件最大的大小 --> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>20MB</MaxFileSize> </triggeringPolicy> </appender> <logger name="com" level="info"> <appender-ref ref="ROLLING_FILE" /> </logger> <root level="INFO"> <appender-ref ref="STDOUT" /> </root> </configuration>