失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > logback利用mdc机制为日志增加traceId

logback利用mdc机制为日志增加traceId

时间:2023-11-15 13:13:10

相关推荐

logback利用mdc机制为日志增加traceId

1 . 增加LogMdcFilter

package mon.filter;import org.slf4j.MDC;import javax.servlet.*;import javax.servlet.annotation.WebFilter;import java.io.IOException;/*** @title 为logback日志增加traceId* @author Xingbz* @createDate -4-12*/@WebFilter(urlPatterns = "/*", filterName = "logMdcFilter")public class LogMdcFilter implements Filter {private static final String UNIQUE_ID = "traceId";@Overridepublic void init(FilterConfig filterConfig) {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {boolean bInsertMDC = insertMDC();try {chain.doFilter(request, response);} finally {if(bInsertMDC) {MDC.remove(UNIQUE_ID);}}}@Overridepublic void destroy() {}private boolean insertMDC() {UUID uuid = UUID.randomUUID();String uniqueId = uuid.toString().replace("-", "");MDC.put(UNIQUE_ID, uniqueId);return true;}}

2 . 配置logback日志格式

将 [%X[traceId]] 添加到日志输出格式中

...<pattern>%d{HH:mm:ss} [%thread][%X{traceId}] %-5level %logger{36} - %msg%n</pattern>...

3 . 异步任务补充

完成前2步之后 , 从前端发起的请求就可以输出traceId了 , 但是一些未经过前端的定时或异步任务 , 是走不了过滤器的 . 所以我们还需要添加一个类

package mon.aspect;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.slf4j.MDC;import org.ponent;/*** @title 为异步方法添加traceId* @author Xingbz* @createDate -4-16*/@Aspect@Componentpublic class LogMdcAspect {private static final String UNIQUE_ID = "traceId";@Pointcut("@annotation(org.springframework.scheduling.annotation.Async)")public void logPointCut() {}@Around("logPointCut()")public Object around(ProceedingJoinPoint point) throws Throwable {MDC.put(UNIQUE_ID, UUID.randomUUID().toString().replace("-",""));Object result = point.proceed();// 执行方法MDC.remove(UNIQUE_ID);return result;}}

4 . 大功告成

如果觉得《logback利用mdc机制为日志增加traceId》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。