aop切面+ 注解 增加方法日志打印

1.自定义日志注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {

    // 业务类型
    BusinessType businessType() default BusinessType.OTHER;
    // 模块名称
    String title() default "";

}

2.增加业务注解操作类型

public enum BusinessType {
    /**
     * 其它
     */
    OTHER,

    /**
     * 新增
     */
    INSERT,

    /**
     * 修改
     */
    UPDATE,

    /**
     * 删除
     */
    DELETE,

    /**
     * 授权
     */
    GRANT,
}

3.切面方法

@Aspect
@Component
public class LogAspect {

    @Autowired
    HttpServletRequest httpServletRequest;
    @Autowired
    SysLogDao sysLogDao;

    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    /**
     * 定义切面
     */
    @Pointcut("@annotation(com.common.anno.Log)")
    public void pt() {
    }

    /**
     * 环绕切点
     */
    @Around("pt()")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行切点方法M
        Object result = pjp.proceed();
        // 执行时长
        Long runTime = System.currentTimeMillis() - beginTime;
        // 记录日志
        handleLog(pjp,runTime,result);
        return result;
    }

    private void handleLog(ProceedingJoinPoint pjp,Long runTime, Object result) {
        MethodSignature signature = (MethodSignature)
                pjp.getSignature();
        Method method = signature.getMethod();
        // 获取注解内容
        Log logAnnotation = method.getAnnotation(Log.class);
        // 获取模块
        String title = logAnnotation.title();
        // 获取业务类型
        BusinessType businessType = logAnnotation.businessType();
        Object[] args = pjp.getArgs();
        // 入参数
        String params = JSON.toJSONString(args);
        //出参
        String res = JSON.toJSONString(result);
        // 请求方法
        String httpMenthod = httpServletRequest.getMethod();
        // ip
        String ip = IPUtils.getIpAddr(httpServletRequest);
        // 请求url
        String requestURL = httpServletRequest.getRequestURL().toString();
        // 封装日志对象
        SysLog sysLog = new SysLog(title, businessType, httpMenthod, requestURL, ip, params, res, runTime);
        // 这里可以根据自己的需求去处理sysLog
        sysLogDao.insert(sysLog);


    }


}

4.实际使用

    @RequestMapping("/saveUser")
    @Log(title = "新建用户" ,businessType = BusinessType.INSERT)
    public R saveUser(){
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值