springboot--使用AOP统一处理web请求日志

为什么要通过AOP来统一处理日志,因为随着你项目的增大,方法增多,代码量上来的时候,比如你有几千个方法,你要打印日志,你要在几千个方法上面都加上冗余的代码logger.info(),让你的代码量瞬间提示几千行,相信很多人都不想这样去做,那么接下来讲一个统一的处理方法:

springboot--使用AOP统一处理web请求日志,首先来添加下pom文件依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<dependency>

然后贴下代码:

@Aspectbr/>@Component
public class WebLogAspect {
private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

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

//通过使用AOP的前置通知来拦截请求信息
@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());

    Enumeration<String> enu = request.getParameterNames();
    while (enu.hasMoreElements()) {
        String name = (String) enu.nextElement();
        logger.info("name:{},value:{}", name, request.getParameter(name));
    }
}

@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
    // 处理完请求,返回内容
    logger.info("RESPONSE : " + ret);
}

}

猜你喜欢

转载自blog.51cto.com/13225344/2424387