springboot 記錄request和response

import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang3.time.StopWatch; import org.springframework.core.annotation.Order; import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.ContentCachingRequestWrapper; import org.springframework.web.util.ContentCachingResponseWrapper; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Description 請求-鏈路 * * @author by mays */ @Slf4j @Order(-1) @Component public class HttpTraceLogFilter extends OncePerRequestFilter { private static final String[] IGNORE_PATH_ARRAY = {"/login", "/logout"}; @Override protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { StopWatch stopWatch = StopWatch.createStarted(); try { ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request); ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response); filterChain.doFilter(requestWrapper, responseWrapper); stopWatch.stop(); if (!ArrayUtils.contains(IGNORE_PATH_ARRAY, request.getRequestURI())) { shouldLog(stopWatch.getTime(), requestWrapper, responseWrapper); } } finally { if (!stopWatch.isStopped()) { stopWatch.stop(); } } } private void shouldLog(long cost, ContentCachingRequestWrapper requestWrapper, ContentCachingResponseWrapper responseWrapper) throws IOException { String requestBody = "GET".equals(requestWrapper.getMethod()) ? requestWrapper.getQueryString() : new String(requestWrapper.getContentAsByteArray(), requestWrapper.getCharacterEncoding()); String responseBody = new String(responseWrapper.getContentAsByteArray(), responseWrapper.getCharacterEncoding()); responseWrapper.copyBodyToResponse(); log.info("請求鏈路信息 耗時:{}毫秒,requestUri:{},requestBody:{},responseBody:{}", cost, requestWrapper.getRequestURI(), requestBody, responseBody); } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章