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));
        }
    }
    

      

  • 相关阅读:
    Jquery 获取CheckBoxList 中选择的值和获取RadioButton 选中的状态
    JS数组取相同的值和不同的值
    JS删除数组总是报错
    调用WebAPI接口
    MVC3 Excel导入数据到sql Server数据库
    MVC JS动态添加 @Html.DropDownList
    得瑟一下
    出差小记
    jQuery自学打卡二
    jQuery自学打卡一
  • 原文地址:https://www.cnblogs.com/webwangbao/p/9229635.html
Copyright © 2011-2022 走看看