springboot 配置切片記錄日誌
阿新 • • 發佈:2019-01-09
1、pom中配置依賴的aop包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、切片事件監控
@Aspect @Component public class WebLogAspect { private Logger logger = Logger.getLogger(WebLogAspect.class); @Pointcut("execution(public * com.mplus.marketing.controller..*.*(..))") public void webLog(){} @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到請求,記錄請求內容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 記錄下請求內容 logger.info("URL : " + request.getRequestURL().toString()); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs())); } @AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { // 處理完請求,返回內容 logger.info("RESPONSE : " + ret); } }
註解@Pointcut配置要監控的方法,本例中文監控所有控制器的方法
註解@Before會在進入切片監控方法方法之前執行
註解@AfterReturning會在切片監控方法即將返回時執行