一:示例
@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)示例仅供参数,可以根据需求进行优化。