下面是我在公司写操作日志记录的时候的代码使用的aop自定义注解的方式,这里记录一下代码希望可以给大家带来一些帮助,顺便自己也巩固一下。方便随时取用。
Aop注解实现日志的话其实不难,我认为只要理解下面三个点,操作日志就比较简单了。
话不多说,直接上代码。
1.操作注解设置(也就是定义后面要加在接口名称上面的注解)
@Target(ElementType.METHOD)//注解放置的目标位置即方法级别
@Retention(RetentionPolicy.RUNTIME)//注解在哪个阶段执行
@Documented
public @interface OperationLogAnnotation {
//操作编号
String operId() default "";
//操作用户编号
String operuserId() default "";
//操作用户姓名
String operuserName() default "";
//操作模块名称
String opermoduleName() default "";
//操作名称
String operhandleName() default "";
//操作结果
String operhandleResult() default "";
//操作附加信息
String operhandleAddInfo() default "";
//操作时间
String operhandleTime() default "";
}
2.定义操作日志切面(这里也就是做拿获取日志的数据的时候,把数据保存到数据库中)
@Aspect
@Component
public class OperationLogAspect {
@Resource
TabXtrzDao xtrzDao;
//数据库里面时间字段是哪个类型就用哪个
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static LocalDateTime localDateTime=LocalDateTime.now();
@Pointcut("@annotation(com.zufengst.intelcom.config.OperationLogAnnotation)")
public void operLogPoinCut() {
}
@AfterReturning(returning = "result", value = "operLogPoinCut()")
public void saveOperLog(JoinPoint joinPoint, Object result) throws Throwable {
// 获取RequestAttributes
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
// 从获取RequestAttributes中获取HttpServletRequest的信息
HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
try {
//将返回值转换成map集合
// Result result1=result;
TabXtrz tabXtrz=new TabXtrz();
// 从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//获取切入点所在的方法
Method method = signature.getMethod();
//获取操作
OperationLogAnnotation annotation = method.getAnnotation(OperationLogAnnotation.class);
if (annotation != null) {
//设置获取的操作(可以直接定义的操作)
tabXtrz.setRzMkmc(annotation.opermoduleName());
tabXtrz.setRzCzmc(annotation.operhandleName());
tabXtrz.setRzFjxx(annotation.operhandleAddInfo());
}
//日志编号
// tabXtrz.setRzId("3");
//用户编号
tabXtrz.setRzYhbh(UUID.randomUUID().toString());
//操作结果
tabXtrz.setRzCzjg("msg");
// //操作用户
tabXtrz.setRzYhName(request.getHeader("yh_zh"));
// DpUser dpUser=new DpUser();
// dpLog.setUser_id(request.getHeader(dpUser.getAccount()));
//操作时间
tabXtrz.setRzCztime(localDateTime);
//返回值信息
// tga.setKey(map.get("message"));
//保存日志(就是一个添加的SQL语句)
xtrzDao.save(tabXtrz);
} catch (Exception e) {
e.printStackTrace();
}
}
3.注解位置(在把添加日志的sql写好了之后,去需要监控的sql上面加上注解)
然后,后面的话去使用postman进行测试,调用del接口,调取成功后去查看数据库,
这里就成功了。
后续,如果有不懂的同学私信评论都可以,非常乐意解答(顺便巩固自己)!!!



