spring boot 下作一個切面日誌

添加依賴 web

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

配置開啓aopspring

# AOP
spring.aop.auto=true 
# 使用cglib
spring.aop.proxy-target-class=false

入口類添加 app

@EnableAspectJAutoProxy

不開啓會致使切面類不執行spring-boot

切面類實現日誌

/**
 * 李成陽
 * 2018/3/23
 * 日誌切面類
 */
@Aspect
@Component
public class AspectLogs {



        private Logger logger = Logger.getLogger(getClass());

        ThreadLocal<Long> startTime = new ThreadLocal();

        @Pointcut("execution(public * com.rzt.controller.*.*(..))")
        public void webLog(){}

        @Before("webLog()")
        public void doBefore(JoinPoint joinPoint) throws Throwable {
            startTime.set(System.currentTimeMillis());
            // 接收到請求,記錄請求內容
            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);
            logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
        }


}
@RequestMapping("/test")
public String test(){
    return "test!!";
}

訪問 http://127.0.0.1:2222/test 查看日誌code

2018-03-23 10:24:35.417  INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs                   : URL : http://127.0.0.1:2222/test
2018-03-23 10:24:35.417  INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs                   : HTTP_METHOD : GET
2018-03-23 10:24:35.421  INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs                   : IP : 127.0.0.1
2018-03-23 10:24:35.421  INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs                   : CLASS_METHOD : com.rzt.controller.ComputeController.test
2018-03-23 10:24:35.421  INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs                   : ARGS : []
2018-03-23 10:24:35.428  INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs                   : RESPONSE : test!!
2018-03-23 10:24:35.428  INFO 4692 --- [nio-2222-exec-1] com.rzt.aop.AspectLogs                   : SPEND TIME : 6312
 get

相關文章
相關標籤/搜索