了解源码后、不废话直接放相关代码
1、重新 TraceEnvironmentPostProcessor
package com.xxxx.common.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import java.util.HashMap;
import java.util.Map;
/**
* @author HanKeQi
* @Date 2021/8/10 17:09 下午
* @Version 1.0
*/
@Slf4j
// 在TraceEnvironmentPostProcessor之后执行
@Order(100)
public class CustomTraceEnvironmentPostProcessor implements EnvironmentPostProcessor{
private static final String PROPERTY_SOURCE_NAME = "defaultProperties";
/**
* 自定义修改日志,可从MDC中获取
* @param environment
* @param application
*/
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
Map<String, Object> map = new HashMap();
if (Boolean.parseBoolean(environment.getProperty("spring.sleuth.enabled", "true"))) {
//修改sleuth中logging.pattern.level配置,自定义参数如:customCode
map.put("logging.pattern.level", "%5p [${spring.zipkin.service.name:${spring.application.name:}},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{customCode:-},%X{X-Span-Export:-}]");
}
this.addOrReplace(environment.getPropertySources(), map);
}
private void addOrReplace(MutablePropertySources propertySources, Map<String, Object> map) {
MapPropertySource target = null;
if (propertySources.contains(PROPERTY_SOURCE_NAME)) {
PropertySource<?> source = propertySources.get(PROPERTY_SOURCE_NAME);
if (source instanceof MapPropertySource) {
target = (MapPropertySource) source;
for (String key : map.keySet()) {
if (!target.containsProperty(key)) {
target.getSource().put(key, map.get(key));
}
}
}
}
if (target == null) {
target = new MapPropertySource(PROPERTY_SOURCE_NAME, map);
}
if (!propertySources.contains(PROPERTY_SOURCE_NAME)) {
propertySources.addLast(target);
}
}
}
2、添加过滤器
package com.xxxx.common.filter;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
/**
* @author HanKeQi
* @Date 2021/8/10 17:30 下午
* @Version 1.0
*/
@Component
public class UserCodeMCDFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
//
//全局设置MDC
MDC.put("customCode", "动态自定义");
chain.doFilter(servletRequest, servletResponse);
}
}