Filter chase
將處理請求的線程,更名爲隨機名稱,即可知道該HTTP請求對應的線程的所有同步操作的日誌,便於排查問題
Spring Filter
WebFilter,過濾所有url
@Component
@WebFilter(urlPatterns = "/*", filterName = "controllerFilter")
public class ControllerFilter implements Filter {
protected Logger logger = LoggerFactory.getLogger(ControllerFilter.class);
private static List<String> ignoreUri = Lists.newArrayList();
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
MetricsStopWatch metricsStopWatch = MetricsStopWatch.startServerWatch();
Thread thread = Thread.currentThread();
String oldName = thread.getName();
HttpServletRequest httpServletRequest = (HttpServletRequest) req;
String servletPath = httpServletRequest.getServletPath();
boolean isIgnore = false;
for (String s : ignoreUri) {
if (servletPath.contains(s)){
isIgnore = true;
break;
}
}
try {
String randomId = RandomStringUtils.randomAlphanumeric(10);
thread.setName(servletPath + "-" + randomId);
if (!isIgnore){
logger.info("請求:{}", servletPath);
}
chain.doFilter(req, resp);
} finally {
metricsStopWatch.code(0).uri(servletPath.replaceAll("/", "_")).markDurationAndCode();
if (!isIgnore) {
logger.info("響應url:{}, time: {} ms", servletPath, metricsStopWatch.getTime());
}
thread.setName(oldName);
}
}
@Override
public void init(FilterConfig config) throws ServletException {}
@Override
public void destroy() {}
}
返回示例
[2020-06-28 20:53:52,889] [INFO ] [/authority/test-lOYazuqsxN] [ControllerFilter_doFilter:55] - 請求:/authority/test
[2020-06-28 20:53:52,895] [INFO ] [/authority/test-lOYazuqsxN] [AuthorityController_test:584] - test, id:123, result:TestVO(total=0, list=[])
[2020-06-28 20:53:52,897] [INFO ] [/authority/test-lOYazuqsxN] [ControllerFilter_doFilter:61] - 響應url:/authority/test, time: 8 ms
使用grep
命令即可查詢此次同步請求的調用日誌
grep 'lOYazuqsxN' test.log