简单记录操作日志即:谁什么时间做了什么事情。
实现
第一步
创建一个@Log注解类
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/**
* 操作类型
*/
String operationType() default "add";
/**
* 操作记录静态记录
* @return 操作记录
*/
String operationName() default "";
}
第二步
创建一个aop切面来读取使用@Log的方法,进行log记录
@Aspect
@Component
@Slf4j
public class SystemLogAspect {
@Autowired
private AuthTokenSystemLogMapper systemLogMapper;
//声明切面为@Log注解
@Pointcut("@annotation(cn.ideamake.auth.common.annotation.Log)")
public void controllerAspect() {
}
//通过后置处理器进行日志的记录
@After("controllerAspect()")
public void after(JoinPoint joinPoint) {
try {
//获取方法信息
Method method = getMethod(joinPoint);
//获取注解信息
Log logAnno = method.getAnnotation(Log.class);
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
String operationType = logAnno.operationType().getOptionType();
String operationName = logAnno.operationName();
SystemLog log = new SystemLog();
log.setDescription(operationName);
log.setMethod(targetName + "." + methodName + "()");
log.setOperType(operationType);
log.setRequestUrl(request.getMethod() + ":" + request.getServletPath());
log.setCreatedAt(new Date());
//日志记录保存
systemLogMapper.insert(log);
} catch (Exception e) {
log.error("日志记录失败,异常信息:{}", e.getMessage());
}
}
到这里就可以使用@Log来进行日志记录啦。
案例如下:
本文到此结束,希望对你有帮助~