Aop进行日志处理

1、日志处理内容

  • 请求url
  • 访问者ip
  • 调用方法ClassMethod
  • 参数args

2、记录日志类

@Aspect
@Component
public class LogAspect {
    private final Logger logger= LoggerFactory.getLogger(this.getClass());
    @Pointcut("execution(* com.ljw.blog.controller.*.*(..))")
    public  void  log(){
    }

    @Before("log()")
    public  void  doBefore(JoinPoint joinPoint){
        ServletRequestAttributes  attributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        String  url= request.getRequestURI();
        String  ip = request.getRemoteAddr();
        String classMethod =joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args=joinPoint.getArgs();
        RequestLog requestLog =new RequestLog(url,ip,classMethod,args);
        logger.info("requestLog:{}",requestLog);
    }

    @After("log()")
    public void  doAfter(){
        logger.info("---------------doAfter-----------------");
    }
    @AfterReturning(pointcut ="log()",returning = "message")
    public void  afterReturn(Object  message){
        logger.info("Result:{}",message);
    }
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
发布了58 篇原创文章 · 获赞 1 · 访问量 1917

猜你喜欢

转载自blog.csdn.net/weixin_44343935/article/details/104557759