logback格式根据请求动态颜色
前文聊到了到,点击链接快速传送!!!
开始
今天来修改一下logback中颜色显示,根据请求来随机控制日志的显示颜色,一次请求输出日志相同颜色,这样也方便像我这种年纪大的开发者查看
配置动态颜色步骤十分简单,主要两步:
1. 重写logback的‘前景色设置复合转换器的基类’、设置默认颜色,
2. 创建一个过滤器,将随机颜色设置到MDC中、随后logback.xml再取出该颜色作显示
步骤
重写 getForegroundColorCode 方法:
package com.mqz.better.skills.logback.alogback.config;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.color.ANSIConstants;
import ch.qos.logback.core.pattern.color.ForegroundCompositeConverterBase;
import org.springframework.stereotype.Component;
/**
* 版权所有 copyright© 蒙大拿
*
* @author mqz
* @date
* @about https://www.gitee.com/DemoMeng
* @description
*/
@Component
public class MDCColorConverter extends ForegroundCompositeConverterBase<ILoggingEvent> {
public static final String key = "MY_AUTO_COLOR";
@Override
protected String getForegroundColorCode(ILoggingEvent event) {
//从event中获取MDCMap,再获取里面的key对应的值
String color = event.getMDCPropertyMap().get(key);
//如果没有返回默认颜色数值
if (color == null) {
return ANSIConstants.RED_FG;
}
//否则返回对应颜色的数值
return color;
}
}
2. 创建过滤器,设置动态颜色到MDC中
package com.mqz.better.skills.logback.alogback.config;
import ch.qos.logback.core.pattern.color.ANSIConstants;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 版权所有 copyright© 蒙大拿
*
* @author mqz
* @date
* @about https://www.gitee.com/DemoMeng
* @description
*/
@Component
public class MDCColorFilter implements Filter {
private static List<String> list = new ArrayList<>();
private static AtomicInteger atm = new AtomicInteger();
{
list.add(ANSIConstants.MAGENTA_FG); //洋红/紫色
list.add(ANSIConstants.BLUE_FG); //蓝色
list.add(ANSIConstants.CYAN_FG); //青色
list.add(ANSIConstants.GREEN_FG); //绿色
list.add(ANSIConstants.YELLOW_FG); //黄色
list.add(ANSIConstants.RED_FG); //红色
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
//循环调用list内的颜色
int index = atm.getAndIncrement() % list.size();
//将颜色对用的数值存入MDC
MDC.put(MDCColorConverter.key, list.get(Math.abs(index)));
chain.doFilter(request, response);
} finally {
//从MDC中删除键值
MDC.remove(MDCColorConverter.key);
}
}
}
3. logback.xml 配置转换规则、获取到MDC中的动态颜色
<!--利用mdc 、 MDCColorConverter 实现动态日志颜色 -->
<conversionRule conversionWord="autoColor" converterClass="com.mqz.better.skills.logback.alogback.config.MDCColorConverter" />
<!-- 获取到MDC中的值 -->
<property name="log.colorPattern" value="%autoColor(%d{yyyy-MM-dd HH:mm:ss} %-5level %thread %logger [%class : %method : %line] %msg%n)"/>
最终效果
效果很明显颜色区分突兀显示了每次请求,这样查看日志就稍微方便那么一点点了(有进步,至少方便了)!!果然这种花花绿绿的颜色才符合我成熟稳重的气质