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)示例僅供參數,可以根據需求進行優化。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM