package {{ package.Common }}.config; //--- 固定引入 ---// import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; //--- 固定引入 ---// /*** * @Description: 日志切面 * @Author: {{author}} * @Date: {{date}} * @Wechat: {{ wechat }} */ @Slf4j @Aspect @Component public class WebLogAspect { private final ObjectMapper objectMapper = new ObjectMapper(); /** 拦截所有 Controller 方法 */ @Around("within(@org.springframework.web.bind.annotation.RestController *)") public Object logWebRequest(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes != null ? attributes.getRequest() : null; MethodSignature signature = (MethodSignature) joinPoint.getSignature(); String methodName = signature.toShortString(); // ========== 读取请求入参 ========== String paramsJson = ""; try { paramsJson = objectMapper.writeValueAsString(joinPoint.getArgs()); } catch (Exception ignored) {} // ----------- 打印入参 ------- if (request != null) { log.info("\n================= 请求开始 =================\n" + "URL : {}\n" + "Method : {}\n" + "Controller : {}\n" + "IP : {}\n" + "Request : {}\n" + "============================================", request.getRequestURI(), request.getMethod(), methodName, request.getRemoteAddr(), paramsJson); } // ========== 执行方法 ========== Object result = joinPoint.proceed(); // ========== 打印返回结果 ========== String resultJson = ""; try { resultJson = objectMapper.writeValueAsString(result); } catch (Exception ignored) {} log.info("\n================= 请求结束 =================\n" + "URL : {}\n" + "耗时 : {} ms\n" + "返回值 : {}\n" + "============================================", request != null ? request.getRequestURI() : methodName, (System.currentTimeMillis() - start), resultJson); return result; } }