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

      

  • 相关阅读:
    jstl嵌套以及输出json的逗号
    关闭win10 更新以后自动重启
    maven 配置错误。
    SQL SERVER 订阅发布在restore DB以后的问题
    Unable to convert MySQL date/time value to System.DateTime
    sql server恢复卡在restoring的解决方法
    打开Excel时总是运行Windows Installer(Visual studio)解决方法
    单元测试用excel connstr
    node.js调试
    javascript数组对象实例方法
  • 原文地址:https://www.cnblogs.com/webwangbao/p/9229635.html
Copyright © 2011-2022 走看看