摘要
AOP 是面向切面的编程,就是在运行期通过动态代理的方式对代码进行增强处理,比较核心的概念有 切点,切面,通知,有关AOP的详情参考:。
本文要介绍的是在一个SpringBoot项目中如何统一的处理Web请求日志,基本思想还是采用AOP的方式,拦截请求,然后,写入日志。
相关依赖
<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>
项目引入spring-boot-starter-web 依赖之后无需在引入相关的日志依赖,因为spring-boot-starter-web中已经集成了slf4j 的依赖。
引入spring-boot-starter-aop 依赖之后,AOP 的功能即是启动状态,无需在添加@EnableAspectJAutoProxy注解。
定义系统日志注解
/** * 系统日志注解 * Created by xiang.wei on 2018/10/17 * * @author xiang.wei */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SysLog { String value() default ""; }
定义切面
@Aspect @Component public class SysLogAspect { private Logger logger = LoggerFactory.getLogger(SysLogAspect.class); // @Autowired // private MtoLogService mtoLogService; /** * 定义日志切点 */ @Pointcut("@annotation(com.jay.common.annotation.SysLog)") public void logPointCut() { } /** * 环绕通知 * @param point * @return */ @Around("logPointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { long startTime = System.currentTimeMillis(); Object proceed = point.proceed(); // 执行时长 long time = System.currentTimeMillis() - startTime; saveSysLog(point, time); return proceed; } private void saveSysLog(ProceedingJoinPoint joinPoint, long time) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); MtoLog mtoLog = new MtoLog(); // 获取注解内容 SysLog annotation = method.getAnnotation(SysLog.class); if (annotation != null) { mtoLog.setOperation(annotation.value()); } // 获取类名 String className = joinPoint.getTarget().getClass().getName(); // 获取方法名 String methodName = method.getName(); mtoLog.setMethod(className + "." + methodName + "()"); // 获取参数 Object[] args = joinPoint.getArgs(); if (args != null) { String param = JSON.toJSONString(args[0]); mtoLog.setParams(param); } mtoLog.setTime(time); HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); mtoLog.setIp(IpUtil.getIpAddr(request)); mtoLog.setCreateDate(new Date()); logger.info("请求的参数="+JSON.toJSONString(mtoLog)); // mtoLogService.insert(mtoLog); } }
使用
@SysLog("登录接口") @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(String username,String password, @RequestParam(value = "rememberMe", defaultValue = "0") int rememberMe, ModelMap model) { 。。。。 }
运行效果:
参考博客
http://blog.didispace.com/springbootaoplog/
代码地址
https://github.com/XWxiaowei/JayBlog/tree/v3-logback-validation