自定义注解+Aop实现简单的日志管理系统

目的:

        在项目中,经常要使用日志管理系统来记录操作日志,在spring AOP的典型实际应用中就有日志管理的应用场景,在这篇老帖中给出简单的实现方案(代码有不妥的地方,老手勿喷,指出后我会虚心学习)

实践:

        1.准备自定义注解

/**
 * @Description:
 * @Author: the_pure
 * @CreateDate: 2021/11/18 10:05
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
    /**
     * 模块名
     * @return
     */
    String model();
    /**
     * 访问的接口名
     * @return
     */
    String method();
}

        2.定义AOP切面

/**
 * @Description: 日志切面
 * @Author: the_pure
 * @CreateDate: 2021/11/18 10:09
 */
@Aspect
@Component
public class LogHandler {
    @Autowired
    private ILogService iLogService;

    ThreadLocal<Long> time = new ThreadLocal<>();

    /**
     * 日志注解作为切入点
     */
    @Pointcut("@annotation(cn.zk.annatation.Log)")
    public void pointcut() {
    }

    /**
     * 环绕通知
     *
     * @return
     */
    @Around("pointcut()&&@annotation(log)")
    public Object around(ProceedingJoinPoint joinPoint, Log log) {
        Map<String,Object> obj = null;
        LogInfo logInfo = null;
        try {
            // 获取运行前时间
            time.set(System.currentTimeMillis());
            // 执行方法
            obj = (Map<String,Object>)joinPoint.proceed();
            // 获取运行时间
            Long spendTime = System.currentTimeMillis() - time.get();
            // 记录日志
            logInfo = LogInfo.builder()
                    .model(log.model())
                    .method(log.method())
                    .spendTime(spendTime)
                    .build();
            if(obj.get("success").equals(true)){
                logInfo.setType(0);// 0 表示正常操作
            } else {
                logInfo.setType(1);// 1 表示错误操作
            }
        } catch (Throwable e) {
            // 记录日志
            logInfo = LogInfo.builder()
                    .type(1)
                    .model(log.model())
                    .method(log.method())
                    .build();
            e.printStackTrace();
        } finally {
            iLogService.save(logInfo);
            time.remove();
            return obj;
        }
    }
}

3.使用将注解使用在需要做日志记录的接口上

/**
 * @Description:
 * @Author: the_pure
 * @CreateDate: 2021/11/18 09:54
 */
@RestController
@RequestMapping("/user")
public class UserController {
   @Autowired
   private IUserService iUserService;

   @Log(model = "用户模块",method ="用户新增")
   @PostMapping
   public Map<String,Object> add(@RequestBody User user) {
       HashMap<String, Object> map = new HashMap<>();
       try {
           iUserService.add(user);
           map.put("success",true);
       } catch (Exception e) {
           e.printStackTrace();
           map.put("success",false);
       } finally {
           return map;
       }
   }

    @DeleteMapping
    @Log(model = "用户模块",method ="用户删除")
    public Map<String,Object> remove(@RequestBody Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            iUserService.remove(userId);
            map.put("success",true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success",false);
        } finally {
            return map;
        }
    }

}

4.其他辅助内容

UserServiceImpl

LogServiceImpl

 

验证:

测试新增用户接口(模拟异常操作)

测试删除用户接口(正常操作)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值