1.maven 依赖 AspectJ静态代理模式
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
2.定义 LoggerManage 注解类
package com.ruoyi.common.annotation; import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface LoggerManage { /** * 说明 * @return */ public String description(); }
3.创建日志切面类 LoggerAspect
package com.ruoyi.framework.aspectj; import com.ruoyi.common.annotation.LoggerManage; import com.ruoyi.common.utils.GsonUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; @Aspect @Component public class LoggerAspect { private static final Logger logger = LoggerFactory.getLogger(LoggerAspect.class); /** * 在这里定义切面的点,Pointcut的表达式语法需要匹配到你调用的方法中 */ @Pointcut("within(com.jh.*.controller.*)") public void declareJoinPointExpression() { } @Before("declareJoinPointExpression()") public void addBeforeLogger(JoinPoint joinPoint) { try { RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest(); String url = request.getRequestURL().toString(); String method = request.getMethod(); String uri = request.getRequestURI(); String userAgent = request.getHeader("User-Agent"); // 获取请求参数 String params = GsonUtils.toJsonString(request.getParameterMap()); String apiName = ""; String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); for (Method m : methods) { if (m.getName().equals(methodName)) { Class[] clazzs = m.getParameterTypes(); if (clazzs.length == arguments.length) { if (m.getDeclaredAnnotation(LoggerManage.class) != null) { apiName = m.getDeclaredAnnotation(LoggerManage.class).description(); break; } } } } logger.info("apiName:{}, url: {}, uri: {}, method: {}, params: {},UserAgent:{}", apiName,url,uri, method,params, userAgent); } catch (ClassNotFoundException e) { e.printStackTrace(); } } // @AfterReturning(value = "declareJoinPointExpression()", returning = "returnObj") // public void addAfterReturningLogger(JoinPoint joinPoint, Object returnObj) { // System.out.println("结束"); // } // @AfterThrowing(pointcut = "declareJoinPointExpression()", throwing = "ex") // public void addAfterThrowingLogger(JoinPoint joinPoint, Exception ex) { // System.out.println("异常"); // } @Around(value = "declareJoinPointExpression()") public Object doAround(ProceedingJoinPoint proceeding) throws Throwable { long beforeTime=System.currentTimeMillis(); //执行被拦截的方法 result是返回结果 Object result = proceeding.proceed(); //debug模式下才计算方法耗时 if (logger.isDebugEnabled()) { long afterTime=System.currentTimeMillis(); RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest(); logger.info("请求:{} , 耗时:{}ms",request.getRequestURI(),afterTime-beforeTime); } //此处可以在log输出result,依据业务要求处理 return result; } } 4.在Controller中注解的使用
@LoggerManage(description = "app检查升级")
@GetMapping("/check_update")
public String checkUpdate() {
return "ok";
}
5.apiName:app检查升级, url: http://localhost:8888/check_update , uri: /check_update, method: GET, params: {},Cookie:{"name":"xxxx","value":"XXXX","version":0,"maxAge":-1,"secure":false,"httpOnly":false},UserAgent:XXXX
...
...
...
请求:/driver/check_update , 耗时:953ms