spring boot aop
这里要做就是利用aop 来打印请求的日志,返回结果,简单的异常处理
一:使用@Aspect注解创建切面,类名是 RquestAspect
import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; 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; import com.alibaba.fastjson.JSON; /** * 对每个请求进行log打印 * @author ningque * */ @Aspect @Component public class HttpAspect { }
二:再RquestAspect中创建切入点
/** * 扫描so.dian.device.controller 包下所有类,所有有注解@RequestMapping 的方法 */ @Pointcut("execution(* com.zhangxs.device.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)") public void log() {}
三:创建调用方法前的日志打印
@Before("log()") public void doBefore(JoinPoint joinPoint){ beginTime=System.currentTimeMillis(); HttpServletRequest request=this.getHttpServletRequest(); url=request.getRequestURL().toString(); method=request.getMethod(); args=joinPoint.getArgs(); inputAgrs=new Object[args.length]; for(int i=0;i<args.length;i++) { if(args[i] instanceof HttpServletRequest) { //有部分请求参数中会有request,request不能转json 会抛出not in non blocking mode 异常 }else { inputAgrs[i]=args[i]; } } logger.info("开始调用: url={},method={},args={}",url,method,JSON.toJSONString(inputAgrs)); }
四:创建调用方法后的日志打印
@After("log()") public void doAfter() { long endTime=System.currentTimeMillis(); logger.info("接口结束调用: url={},method={},调用耗时={}",url,method,endTime-beginTime); }
五:创建返回结果的日志打印
@Around("log()") public Object doAround(ProceedingJoinPoint pjp) { Object result=null; try { result=pjp.proceed(); } catch (Throwable e) { requestErrLogger.error("接口结束调用: url={},method={},异常信息={}",url,method,e); e.printStackTrace(); } logger.info("reponse={}",result); return result; }
六:获取request请求
public HttpServletRequest getHttpServletRequest() { ServletRequestAttributes sa= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = sa.getRequest(); return request; }
控制台打印日志:
2017-11-01-18-10 [http-nio-9090-exec-1] [HttpAspect] [INFO] - 开始调用: url=http://localhost:8080/zhangxs/studentInfo,method=GET,args=[{“testUrl":";https://com.zhangxs.so/hello/p/010000000308208"},null] 2017-11-01-18-10 [http-nio-9090-exec-1] [HttpAspect] [INFO] - reponse={"success":false,"code":0,"msg":"查询信息失败"} 2017-11-01-18-10 [http-nio-9090-exec-1] [HttpAspect] [INFO] - 接口结束调用: url=http://localhost:8080/zhangxs/studentInfo,method=GET,调用耗时=27446