SpringBoot AOP+自定义注解实现日志功能

本文档展示了如何使用Spring Boot的AOP(面向切面编程)特性来创建一个系统日志系统。首先,创建了系统日志数据库表,并引入了AspectJ和Spring AOP的相关依赖。接着,定义了系统日志实体类`SysLog`,包含了如日志类型、操作用户等字段。然后,创建了一个名为`AutoLog`的注解,用于标记需要记录日志的方法。`AutoLogAspect`切面类处理注解,实现了方法执行前后的时间记录、日志保存等功能。最后,通过在Controller层的方法上添加`@AutoLog`注解,实现了对特定操作的日志记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建系统日志数据库表

在这里插入图片描述

2.maven坐标

<dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.7</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

3.创建系统日志实体类

@Data
public class SysLog implements Serializable {
    private String id;
    /**日志类型(1登录日志,2操作日志)*/
    private int logType;
    /**日志内容*/
    private String logContent;
    /**操作类型(1添加2修改3删除)*/
    private int operateType;
    /**操作用户账号*/
    private String userid;
    /**操作用户姓名*/
    private String username;
    /**ip*/
    private String ip;
    /**请求Java 方法*/
    private String method;
    /**请求路径*/
    private String requestUrl;
    /**请求参数*/
    private String requestParam;
    /**请求类型*/
    private String requestType;
    /**耗时*/
    private long costTime;
    private String createBy;
    private Date createTime;
    private String updateBy;
    private Date updateTime;
}

4.创建系统日志注解

@Target(ElementType.METHOD)  //target用于标识此注解能标记在方法上还是类上
@Retention(RetentionPolicy.RUNTIME) //retention用于决定此注解的生命周期
@Documented
public @interface AutoLog {
    /**日志内容*/
    String value() default "";

    /**日志类型(1登录日志,2操作日志)*/
    int logType() default 2;

    /**操作日志类型 1查询2添加3修改4删除*/
    int operateType() default 0;
}

5.创建日志注解切面类

@Aspect
@Component
public class AutoLogAspect {

    @Autowired
    SysLogService sysLogService;

    private static Logger logger = LoggerFactory.getLogger(AutoLogAspect.class);

    @Pointcut("@annotation(com.example.demo.commit.annotation.AutoLog)")
    public void logPointCut(){}

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        System.out.println("日志");
        //执行方法
        Object result = point.proceed();
        //执行时长
        long time = System.currentTimeMillis()-beginTime;

        //保存日志
        saveSysLog(point,time,result);

        return result;
    }

    private void saveSysLog(ProceedingJoinPoint point,long time,Object obj){
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SysLog dto = new SysLog();
        AutoLog syslog = method.getAnnotation(AutoLog.class);
        if (syslog != null){
            String content = syslog.value();
            dto.setLogType(syslog.logType());
            dto.setLogContent(content);
        }
        //请求的方法名
        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();
        dto.setMethod(className+"."+methodName+"()");
        //设置操作类型
        if (dto.getLogType() == 2){
            dto.setOperateType(getOperateType(methodName,syslog.operateType()));
        }
        //获取request
        HttpServletRequest request = getHttpServletRequest();
        //请求的参数
        dto.setRequestParam(getRequestParams(request,point));
        //设置ip地址
        dto.setIp(getIpAddr(request));
        //获取用户登录信息
        TUser user = (TUser) SecurityUtils.getSubject().getPrincipal();
        if (user != null){
            dto.setUserid(user.getUserName());
            dto.setUsername(user.getPassWord());
        }
        dto.setCostTime(time);
        dto.setCreateTime(new Date());

        sysLogService.save(dto);
    }

    private int getOperateType(String methodName , int operateType){
        if (operateType>0){
            return operateType;
        }
        if (methodName.startsWith("list")){
            return 1;
        }
        if (methodName.startsWith("add")){
            return 2;
        }
        if (methodName.startsWith("edit")){
            return 3;
        }
        if (methodName.startsWith("delete")){
            return 4;
        }
        if (methodName.startsWith("import")){
            return 5;
        }
        if (methodName.startsWith("export")){
            return 6;
        }
        return 1;
    }

    private HttpServletRequest getHttpServletRequest(){
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }

    private String getRequestParams(HttpServletRequest request, JoinPoint joinPoint){
        String httpMethod = request.getMethod();
        String param = "";
        if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)){
            Object[] paramArray = joinPoint.getArgs();
            Object[] arguments = new Object[paramArray.length];
            for (int i = 0; i < paramArray.length; i++) {
                if (paramArray[i] instanceof BindingResult || paramArray[i] instanceof ServletRequest || paramArray[i] instanceof ServletResponse || paramArray[i] instanceof MultipartFile){
                    continue;
                }
                arguments[i] = paramArray[i];
            }
            PropertyFilter propertyFilter = new PropertyFilter() {
                @Override
                public boolean apply(Object object, String name, Object value) {
                    if (value!=null && value.toString().length()>500){
                        return false;
                    }
                    return true;
                }
            };
            param = JSONObject.toJSONString(arguments,propertyFilter);
        }else {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            //请求的方法参数值
            Object[] args = joinPoint.getArgs();
            //请求的方法名称
            LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
            String[] parameterNames = u.getParameterNames(method);
            if (args != null && parameterNames !=null){
                for (int i = 0; i < args.length; i++) {
                    param += " " + parameterNames[i] +": " + args[i];
                }
            }
        }
        return param;
    }

    public String getIpAddr(HttpServletRequest request){
        String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
                ip = request.getHeader("HTTP_CLIENT-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
                ip = request.getHeader("HTTP_X-FORWARDED-FOR");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)){
                ip = request.getRemoteAddr();
            }
        }catch (Exception e){
            logger.error("IP error",e);
        }
        return ip;
    }
}

6.在controller层的方法添加系统日志注解

    @AutoLog(value = "easyPoi导入")
    @ApiOperation("easyPoi导入")
    @GetMapping("/importEasyPoi")
    @ResponseBody
    public Result<TUser> easyPoiImport(@RequestParam("file")MultipartFile file) {
        try {
            userService.easyPoiImport(file);
            return ResultUtil.success();
        }catch(Exception e){
            e.printStackTrace();
            return ResultUtil.fail(201,"导入失败");
        }

    }

gitee地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值