使用spring aop简单进行操作日志的记录

简单记录操作日志即:谁什么时间做了什么事情。

实现

第一步

创建一个@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来进行日志记录啦。

案例如下:
image

本文到此结束,希望对你有帮助~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值