package com.guahao; //import com.google.gson.Gson; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; /** * @author T.W * @site xxx * @date 2021/9/8 * @time 下午9:19 * @discription **/ @Aspect @Component //@Profile({"dev", "test"}) public class WebLogAspect { private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class); /** 换行符 */ private static final String LINE_SEPARATOR = System.lineSeparator(); /** 以自定义 @WebLog 注解为切点 */ @Pointcut("@annotation(com.guahao.WebLog)") public void webLog() {} /** * 在切点之前织入 * @param joinPoint * @throws Throwable */ @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 开始打印请求日志 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 获取 @WebLog 注解的描述信息 String methodDescription = getAspectLogDescription(joinPoint); // 打印请求相关参数 logger.info("========================================== Start =========================================="); // 打印请求 url logger.info("URL : {}", request.getRequestURL().toString()); // 打印描述信息 logger.info("Description : {}", methodDescription); // 打印 Http method logger.info("HTTP Method : {}", request.getMethod()); // 打印调用 controller 的全路径以及执行方法 logger.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); // 打印请求的 IP logger.info("IP : {}", request.getRemoteAddr()); // 打印请求入参 // if(methodDescription.equals("loginUserInfo") || methodDescription.equals("quitUserInfo")){ // // }else{ // logger.info("Request Args : {}", JSON.toJSON(joinPoint.getArgs())); // } // ✅ 安全地处理请求参数:只序列化非 Servlet 类型的参数 Object[] args = joinPoint.getArgs(); List safeArgs = new ArrayList<>(); for (Object arg : args) { if (arg == null || !(arg instanceof ServletRequest || arg instanceof ServletResponse || arg instanceof InputStream || arg instanceof Reader)) { safeArgs.add(arg); } } logger.info("Request Args : {}", JSON.toJSONString(safeArgs)); // 使用 toJSONString 更安全 } /** * 在切点之后织入 * @throws Throwable */ @After("webLog()") public void doAfter() throws Throwable { // 接口结束后换行,方便分割查看 logger.info("=========================================== End ===========================================" + LINE_SEPARATOR); } /** * 环绕 * @param proceedingJoinPoint * @return * @throws Throwable */ @Around("webLog()") public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { long startTime = System.currentTimeMillis(); Object result = proceedingJoinPoint.proceed(); // 检查是否需要记录响应参数 boolean logResponse = true; try { // 获取方法上的@WebLog注解 String targetName = proceedingJoinPoint.getTarget().getClass().getName(); String methodName = proceedingJoinPoint.getSignature().getName(); Object[] arguments = proceedingJoinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { WebLog webLog = method.getAnnotation(WebLog.class); if (webLog != null) { logResponse = webLog.logResponse(); } break; } } } } catch (Exception e) { // 如果获取注解信息失败,默认记录响应参数 logger.warn("获取WebLog注解信息失败: {}", e.getMessage()); } // 根据配置决定是否打印出参 if (logResponse) { logger.info("Response Args : {}", JSON.toJSON(result)); } // 执行耗时 logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime); return result; } /** * 获取切面注解的描述 * * @param joinPoint 切点 * @return 描述信息 * @throws Exception */ public String getAspectLogDescription(JoinPoint joinPoint) throws Exception { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); StringBuilder description = new StringBuilder(""); for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { description.append(method.getAnnotation(WebLog.class).description()); break; } } } return description.toString(); } }