springboot 使用aop记录访问日志

  • pom文件增加aop的依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
  • 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAnnotation {
    String value() default "";
}
  • 切面
@Aspect
@Component
public class SysLogAspect {

    @Autowired
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.xxx.xxx.annotation.LogAnnotation)")
    public void pointcut() {
    }

    @Pointcut("execution(public * com.xxx.xxx.modules.*.controller.*.*(..))")
    public void exceptionPointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        long time = 0;
        try {
            result = point.proceed();
            time = System.currentTimeMillis() - beginTime;

            saveLog(point, time, result, null, 0);
        } catch (Throwable throwable) {
            saveLog(point, time, "", throwable, 1);

            MethodSignature methodSignature = (MethodSignature) point.getSignature();
            Class<?> returnType = methodSignature.getReturnType();
            if (returnType.getName().equalsIgnoreCase(JsonContent.class.getName())) {
                result = JsonContent.error(UtilsString.isBlank(throwable.getMessage()) ? "系统异常,请联系管理员!" : throwable.getMessage());
            }

            throwable.printStackTrace();
        }

        return result;
    }

    @AfterThrowing(pointcut = "exceptionPointcut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        saveLog(joinPoint, 0, "", e, 1);
    }

    private void saveLog(JoinPoint point, long time, Object result, Throwable e, int type) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        if (annotation != null) {
            sysLog.setOperation(annotation.value());
        }

        // 方法名
        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        // 方法参数
        Object[] args = point.getArgs();
        LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method);
        if (args != null && parameterNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += parameterNames[i] + ": " + args[i];
                params += ", ";
            }
            sysLog.setParams(params);
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        sysLog.setIpAddress(UtilsIp.getIpAddr(request));
        sysLog.setUri(request.getRequestURI());
        sysLog.setTime(time);
        sysLog.setType(type);
        sysLog.setReturnValue(UtilsJson.obj2json(result));
        sysLog.setCreateBy("system");
        sysLog.setUpdateBy("system");

        if (e != null) {
            sysLog.setExcName(e.getClass().getName());
            sysLog.setExcMessage(e.getMessage());
        }

        sysLogService.save(sysLog);
    }

}
  • 使用
@RestController
@RequestMapping("user/manage")
public class UserManageController extends BaseController {


    @LogAnnotation("获取用户信息")
    @RequestMapping("info")
    public JsonContent info() throws Exception {
        throw new Exception();
    }

    /**
     * 返回成功数据,默认提示,默认handler
     *
     * @return
     */
    public JsonContent success(Object data) {
        return this.success("操作成功!", data, true);
    }
}

如果目标方法中出现异常,并由catch捕捉处理且catch又没有抛出新的异常,那么针对该目标方法的AfterThrowing增强处理将不会被执行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值