标签:org pos 表达 操作 aspect logging string EDA osi
springboot中使用AOP做访问请求日志:这次引入springboot的aop和日志
1、pom.xml引入:
<!--springBoot的aop,已经集成了spring aop和AspectJ--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-logging --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency>
2、切面类配置:
@Component @Aspect public class LogAspect { private static final Logger logger = LoggerFactory.getLogger(LogAspect.class); //切入点表达式,com.springboot.controller自己controller包的路径 @Pointcut("execution(public * com.springboot.controller..*.*(..))") public void pointCut(){ } @Before("pointCut()") public void beforeMethod(JoinPoint joinPoint){ ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); HttpServletRequest request = servletRequestAttributes.getRequest();
//获取需要打印的参数信息 String requestURI = request.getRequestURI(); String method = request.getMethod(); String remoteAddr = request.getRemoteAddr();
//这里使用的是阿里的fastjson String jsonString = JSON.toJSONString(joinPoint.getArgs());
//打印信息 logger.info("------------------------请求信息----------------------------------"); logger.info("请求时间 :{}",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); logger.info("remoteAddr: {} ",remoteAddr); logger.info("requestURI : {}",requestURI); logger.info("Controller : {}", joinPoint.getTarget().getClass()); logger.info("method type: {}" ,method); logger.info("req paras: {}",jsonString); logger.info("------------------------请求信息-----------------------------------"); } }
效果:
com.springboot.common.aop.LogAspect : ------------------------请求信息---------------------------------- com.springboot.common.aop.LogAspect : 请求时间 :2020-01-02 22:38:40 com.springboot.common.aop.LogAspect : remoteAddr: 0:0:0:0:0:0:0:1 com.springboot.common.aop.LogAspect : requestURI : /user/10001 com.springboot.common.aop.LogAspect : Controller : class com.springboot.controller.UserController com.springboot.common.aop.LogAspect : method type: GET com.springboot.common.aop.LogAspect : req paras: [10001] com.springboot.common.aop.LogAspect : ------------------------请求信息---------------------------------
这里只做访问请求的日志打印,还可以后置通知,打印响应信息,结合环绕通知可以打印程序执行的时间等其他操作。
。。。
标签:org pos 表达 操作 aspect logging string EDA osi
原文地址:https://www.cnblogs.com/tdyang/p/12142177.html