运用Spring aop 切面 记录日志

基础了解

首先需要知道几个注解

@Pointcut

概念:spring aop切点

举例:

//当使用到QhLog这个类时,会切入切点
@Pointcut("@annotation(net.qh.common.annotation.QhLog)")
    public void qhLog(){
        log.info("---注入用户操作日志切面---");
    }
 

@Around

概念:通俗来说是调用@Pointcut 中的方法

举例:

@Around("qhLog()")

步骤:

  1. 创建日志注解类
  2. 编写切面方法
  3. 在控制层引用

具体实现

1. 创建日志注解类

package net.qh.common.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface QhLog {
    String module() default "";

    String ot() default "";

    String summary() default "";
}

2. 编写切面方法

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Pointcut("@annotation(net.qh.common.annotation.QhLog)")
    public void qhLog(){
        log.info("---注入用户操作日志切面---");
    }


	@Around("qhLog()")
	    public Object interfaceProcess(ProceedingJoinPoint joinPoint) throws Throwable {
	        log.info("---切面开始执行---");
	        Object[] args = joinPoint.getArgs();
	        // 在joinPoint.proceed()前先获取参数,防止在方法参数被修改
	        String params = argsArrayToString(args);
	        Object respResult = joinPoint.proceed(args);
	        handleLog(joinPoint, params, null, respResult);
	        return respResult;
    }

	/**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "qhLog()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        Object[] args = joinPoint.getArgs();
        String params = argsArrayToString(args);
        handleLog(joinPoint, params, e, null);
    }


	protected void handleLog(final JoinPoint joinPoint, String params, final Exception e, Object result) {
	        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
	        QhLog qhLog = signature.getMethod().getAnnotation(QhLog.class);
	
	       
	
	        OperLog operLog = new OperLog();
	     	//这种就是控制层传进来的值
	        operLog.setModule(qhLog.module());
	        operLog.setOperType(qhLog.ot());
	       
	        // 请求的地址
	        String ip = IpUtils.getIpAddr(request);
	        operLog.setOperIp(ip);
	        operLog.setOperUrl(request.getRequestURI());
	
	        // 返回参数
	        operLog.setResult(JSON.toJSONString(result));
	
	      
	    }
}

3. 在控制层引用

@QhLog(module = "套餐", ot = "修改", summary = "修改软件套餐")
    @PutMapping
    public R update(@RequestBody Soft soft){
        return softService.update(soft);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值