使用AOP同一处理WEB请求日志

在实际开发中,我们可能会经常用到log.info(),这句代码会出现多次,使代码比较冗余,通过aop原理可以帮助我们减少冗余代码。

需要在pom文件中引入aop的依赖:

<!-- 引入aop依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

编写aop日志记录类:

package wyh.aop;

import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Aspect
@Component
public class WebLogAspect {

	
	private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
	
	@Pointcut("execution(public * wyh.controller.*.*(..))")//表示拦截public 任意返回值的wyh.controller 这个包下面的所有类的所有方法,(..)表示任意参数列表
	public void webLog() {
		
	}
	
	
	
	/**
	 * 
	 * <p>Title: doBefore</p>  
	 * <p>Description:aop的前置通知 ,拦截请求参数信息</p>  
	 * @param joinPoint
	 * @throws Throwable
	 */
	@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) throws Throwable{
		/*接收到请求将其转换为原生的servlet,记录请求内容,日志一般记录在NoSQL数据库中
		 * 
		 */
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		//通过原生servlet获取URL等信息,记录下请求内容
		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));
		}
		System.out.println(System.currentTimeMillis());
	}
	
	
	/**
	 * 
	 * <p>Title: doAfterReturning</p>  
	 * <p>Description: 后置通知 </p>  
	 * @param ret
	 * @throws Throwable
	 */
	@AfterReturning(returning = "ret" ,pointcut="webLog()")
	public void doAfterReturning(Object ret) throws Throwable{
		//处理完请求,返回内容
		logger.info("RESPONSE:"+ret+System.currentTimeMillis());
		
	}
}

编写controller

@RequestMapping("/getMember")
	public String getMember(String name,Integer age) {
		return "success"+System.currentTimeMillis();
	}

在打印输出时我加上了系统当前时间,便于证明前置增强和后置增强的实际执行时间,访问结果:日志信息在控制台中打印输出

猜你喜欢

转载自blog.csdn.net/QYHuiiQ/article/details/84710218