zoukankan      html  css  js  c++  java
  • AOP实现接口请求参数和响应参数的日志打印

    一:示例

    @Aspect
    @Component
    public class WebLogAspect {
    
        private static Logger log = LoggerFactory.getLogger(WebLogAspect.class);
    
        private final ObjectMapper mapper;
    
        @Autowired
        public WebLogAspect(ObjectMapper mapper) {
            this.mapper = mapper;
        }
    
        @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
        public void requestLog() {
        }
    
        @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
        public void postLog() {
        }
    
        @Before("requestLog() || postLog()")
        public void doBefore(JoinPoint joinPoint) {
            for (Object object : joinPoint.getArgs()) {
                if (object instanceof MultipartFile ||
                        object instanceof HttpServletRequest ||
                        object instanceof HttpServletResponse) {
                    continue;
                }
    
                if (log.isInfoEnabled()) {
                    log.info(joinPoint.getTarget().getClass().getName() +
                            "." +
                            joinPoint.getSignature().getName() +
                            " : request parameter : " +
                            object.toString());
                }
            }
        }
    
        @AfterReturning(returning = "response", pointcut = "requestLog() || postLog()")
        public void doAfterReturning(Object response) throws Throwable {
            if (response != null) {
                log.info("response parameter : " + mapper.writeValueAsString(response));
            }
        }
    }

    二:说明

    (1)请求参数对象最好重写toString()方法

    (2)响应对象实现Serializable接口

    (3)示例仅供参数,可以根据需求进行优化。

  • 相关阅读:
    [ext4]空间管理
    [ext4] 磁盘布局
    [ext4]磁盘布局
    [ext4]08 磁盘布局
    [ext4]07 磁盘布局
    [ext4]06 磁盘布局
    [ext4]05 磁盘布局
    jQuery之链式编程
    jQuery之排他思想
    jQuery之筛选方法
  • 原文地址:https://www.cnblogs.com/fdzfd/p/9916172.html
Copyright © 2011-2022 走看看