AOP实现系统通用日志功能
实现使用AOP记录日志
1.添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2.自定义注解
首先在启动类的同级包下边新建一个config包,在这个报下边新建new一个名为Log的Annotation文件
/** * @author Promise * @createTime 2018年12月18日 下午9:26:25 * @description 定义一个方法级别的@log注解 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Log { String value() default ""; }
3.建表
根据自己需求的字段建就可以了。
4.创建对应实体类、接口等实现方法
5.创建AOP切面实现类(重点)
将该类放在config包下即可
@Aspect @Component public class LogAsPect { private final static Logger log = org.slf4j.LoggerFactory.getLogger(LogAsPect.class); @Autowired private SysLogService sysLogService; @Autowired private UserServices userServices; //表示匹配带有自定义注解的方法 @Pointcut("@annotation(com.sunwoda.ms.dips.config.Log)") public void pointcut() {} @Around("pointcut()") public Object around(ProceedingJoinPoint point) { Object result =null; try { result = point.proceed(); insertLog(point,result); } catch (Throwable e) { insertLog(point,e); } return result; } private void insertLog(ProceedingJoinPoint point ,Object message) { MethodSignature signature = (MethodSignature)point.getSignature(); Method method = signature.getMethod(); DevHistoryPo devHistoryPo = new DevHistoryPo(); // 注解上的描述 Log userAction = method.getAnnotation(Log.class); // 请求的类名 String className = point.getTarget().getClass().getName(); // 请求的方法名 String methodName = signature.getName(); // 请求的方法参数值 String args = JSON.toJSONString(point.getArgs()); //强制转换请求的对象为基本对象 BasePo b = (BasePo) point.getArgs()[0]; //用户ID String userId = userServices.getCurrentAccount(); //操作结果 String opResult = JSON.toJSONString(message); //数据ID String dataId = b.getId()+""; devHistoryPo.setOpContent("请求描述:["+userAction.value()+"],请求类名:["+className+"],请求方法名:["+methodName+"],请求方法的参数值:["+args+"]"); devHistoryPo.setOpMan(userId); devHistoryPo.setOpResult(opResult); devHistoryPo.setOpDate(new java.sql.Timestamp(new Date().getTime())); devHistoryPo.setDeviceCode(dataId); sysLogService.save(devHistoryPo); } }
6.使用
直接在控制器方法或service层添加注解,如: @Log(“增加”)
注解名是在第三步,自定义注解的时候命名的。
下一篇:
mysql 经验积累 (持续更新)