zoukankan      html  css  js  c++  java
  • 使用Spring的AOP实现切面日志

    AOP切面日志的使用方式

    @Aspect
    @Component
    public class HttpAspect {
    
        private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);
        //定义切点
        @Pointcut("execution(public * com.example.springdemo.controller.*.*(..))")
        public void log() {
        }
    
        @Before("log()")
        public void doBefore(JoinPoint joinPoint) {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
    
            StringBuilder httpInfo = new StringBuilder();
    
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            // 请求的方法参数值
            Object[] args = joinPoint.getArgs();
            // 请求的方法参数名称
            LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
            String[] paramNames = u.getParameterNames(method);
            String params = "";
            if (args != null && paramNames != null) {
                for (int i = 0; i < args.length; i++) {
                    params += " " + paramNames[i] + ": " + args[i];
                }
            }
            //拼接参数请求报文
            httpInfo.append("[{DATE=").append(DateUtils.convertDateTimeToString(new Date())).append("},{URI=").append(request.getRequestURI()).append("},{method=").append(request.getMethod())
                    .append("},{ip=").append(request.getRemoteAddr()).append("},{params=");
    
            if (!StringUtils.isEmpty(params)) {
                httpInfo.append(JsonUtils.objectToJson(params));
            }
            httpInfo.append("}]");
            logger.info("request = {}", httpInfo);
    
        }
    
        @After("log()")
        public void doAfter() {
        }
    
        /**
         * 记录请求完成之后的响应体
         *
         * @param object
         */
        @AfterReturning(returning = "object", pointcut = "log()")
        public void doAfterReturning(Object object) {
            logger.info("response={}", JsonUtils.objectToJson(object));
        }
    }
    

      

  • 相关阅读:
    攻防世界-web-Web_php_unserialize(PHP反序列化漏洞)
    攻防世界-web-unfinish(sql二次注入)
    【第19次CCF CSP认证】Markdown渲染器 (模拟)
    c++类 构造函数 析构函数 拷贝构造函数
    linux快速配置网络脚本
    编译安装openresty
    编译openresty出现的报错
    编译安装libmcrypt
    编译安装PHP支持环境libiconv
    Spring Boot-内置的Tomcat服务器配置详解
  • 原文地址:https://www.cnblogs.com/webwangbao/p/9229635.html
Copyright © 2011-2022 走看看