一个注解轻松搞定审计日志服务!

审计日志】,简单的说就是系统需要记录谁,在什么时间,对什么数据,做了什么样的更改!任何一个 IT 系统,如果要过审,这项任务基本上也是必审项!

实现【审计日志】这个需求,我们有一个很好的技术解决方案,就是使用 Spring 的切面编程。

  • 先创建审计日志表

图片

然后编写一个注解类

图片

接着编写一个代理类

@Component
@Aspect
public class SystemAuditLogAspect {

    @Autowired
    private SystemAuditLogService systemAuditLogService;

    /**
     * 定义切入点,切入所有标注此注解的类和方法
     */
    @Pointcut("@within(com.example.demo.core.annotation.SystemAuditLog)|| @annotation(com.example.demo.core.annotation.SystemAuditLog)")
    public void methodAspect() {
    }

    /**
     * 方法调用前拦截
     */
    @Before("methodAspect()")
    public void before(){
        System.out.println("SystemAuditLog代理 -> 调用方法执行之前......");
    }

    /**
     * 方法调用后拦截
     */
    @After("methodAspect()")
    public void after(){
        System.out.println("SystemAuditLog代理 -> 调用方法执行之后......");
    }

    /**
     * 调用方法结束拦截
     */
    @AfterReturning(value = "methodAspect()")
    public void afterReturning(JoinPoint joinPoint) throws Exception {
        System.out.println("SystemAuditLog代理 -> 调用方法结束拦截......");
        //封装数据
        AuditLog entity = warpAuditLog(joinPoint);
        entity.setResult(0);

        //插入到数据库
        systemAuditLogService.add(entity);
    }


    /**
     * 抛出异常拦截
     */
    @AfterThrowing(value="methodAspect()", throwing="ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) throws Exception {
        System.out.println("SystemAuditLog代理 -> 抛出异常拦截......");
        //封装数据
        AuditLog entity = warpAuditLog(joinPoint);
        entity.setResult(1);
        //封装错误信息
        entity.setExMsg(ex.getMessage());

        //插入到数据库
        systemAuditLogService.add(entity);
    }


    /**
     * 封装插入实体
     * @param joinPoint
     * @return
     * @throws Exception
     */
    private AuditLog warpAuditLog(JoinPoint joinPoint) throws Exception {
        //获取请求上下文
        HttpServletRequest request = getHttpServletRequest();
        //获取注解上的参数值
        SystemAuditLog systemAuditLog = getServiceMethodDescription(joinPoint);
        //获取请求参数
        Object requestObj = getServiceMethodParams(joinPoint);
        //封装数据
        AuditLog auditLog = new AuditLog();
        auditLog.setId(SnowflakeIdWorker.getInstance().nextId());
        //从请求上下文对象获取相应的数据
        if(Objects.nonNull(request)){
            auditLog.setUserAgent(request.getHeader("User-Agent"));
            //获取登录时的ip地址
            auditLog.setIpAddress(IpAddressUtil.getIpAddress(request));
            //调用外部接口,获取IP所在地
            auditLog.setIpAddressName(IpAddressUtil.getLoginAddress(auditLog.getIpAddress()));
        }
        //封装操作的表和描述
        if(Objects.nonNull(systemAuditLog)){
            auditLog.setTableName(systemAuditLog.tableName());
            auditLog.setOperateDesc(systemAuditLog.description());
        }
        //封装请求参数
        auditLog.setRequestParam(JSON.toJSONString(requestObj));
        //封装请求人
        if(Objects.nonNull(requestObj) && requestObj instanceof BaseRequest){
            auditLog.setOperateUserId(((BaseRequest) requestObj).getLoginUserId());
            auditLog.setOperateUserName(((BaseRequest) requestObj).getLoginUserName());
        }
        auditLog.setOperateTime(new Date());
        return auditLog;
    }


    /**
     * 获取当前的request
     * 这里如果报空指针异常是因为单独使用spring获取request
     * 需要在配置文件里添加监听
     *
     * 如果是spring项目,通过下面方式注入
     * <listener>
     * <listener-class>
     * org.springframework.web.context.request.RequestContextListener
     * </listener-class>
     * </listener>
     *
     * 如果是springboot项目,在配置类里面,通过下面方式注入
     * @Bean
     * public RequestContextListener requestContextListener(){
     *     return new RequestContextListener();
     * }
     * @return
     */
    private HttpServletRequest getHttpServletRequest(){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes)ra;
        HttpServletRequest request = sra.getRequest();
        return request;
    }

    /**
     * 获取请求对象
     * @param joinPoint
     * @return
     * @throws Exception
     */
    private Object getServiceMethodParams(JoinPoint joinPoint) {
        Object[] arguments = joinPoint.getArgs();
        if(Objects.nonNull(arguments) && arguments.length > 0){
            return arguments[0];
        }
        return null;
    }


    /**
     * 获取自定义注解里的参数
     * @param joinPoint
     * @return 返回注解里面的日志描述
     * @throws Exception
     */
    private SystemAuditLog getServiceMethodDescription(JoinPoint joinPoint) throws Exception {
        //类名
        String targetName = joinPoint.getTarget().getClass().getName();
        //方法名
        String methodName = joinPoint.getSignature().getName();
        //参数
        Object[] arguments = joinPoint.getArgs();
        //通过反射获取示例对象
        Class targetClass = Class.forName(targetName);
        //通过实例对象方法数组
        Method[] methods = targetClass.getMethods();
        for(Method method : methods) {
            //判断方法名是不是一样
            if(method.getName().equals(methodName)) {
                //对比参数数组的长度
                Class[] clazzs = method.getParameterTypes();
                if(clazzs.length == arguments.length) {
                    //获取注解里的日志信息
                    return method.getAnnotation(SystemAuditLog.class);
                }
            }
        }
        return null;
    }
}
  • 最后,只需要在对应的接口或者方法上添加审计日志注解即可

图片

  • 相关的实体类

@Data
public class AuditLog {

    /**
     * 审计日志,主键ID
     */
    private Long id;

    /**
     * 操作的表名,多个用逗号隔开
     */
    private String tableName;

    /**
     * 操作描述
     */
    private String operateDesc;

    /**
     * 请求参数
     */
    private String requestParam;

    /**
     * 执行结果,0:成功,1:失败
     */
    private Integer result;

    /**
     * 异常信息
     */
    private String exMsg;

    /**
     * 请求代理信息
     */
    private String userAgent;

    /**
     * 操作时设备IP
     */
    private String ipAddress;

    /**
     * 操作时设备IP所在地址
     */
    private String ipAddressName;

    /**
     * 操作时间
     */
    private Date operateTime;


    /**
     * 操作人ID
     */
    private String operateUserId;

    /**
     * 操作人
     */
    private String operateUserName;
}
public class BaseRequest implements Serializable {

    /**
     * 请求token
     */
    private String token;

    /**
     * 登录人ID
     */
    private String loginUserId;

    /**
     * 登录人姓名
     */
    private String loginUserName;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getLoginUserId() {
        return loginUserId;
    }

    public void setLoginUserId(String loginUserId) {
        this.loginUserId = loginUserId;
    }

    public String getLoginUserName() {
        return loginUserName;
    }

    public void setLoginUserName(String loginUserName) {
        this.loginUserName = loginUserName;
    }
}

@Data
public class UserLoginDTO extends BaseRequest {

    /**
     * 用户名
     */
    private String userName;

    /**
     * 密码
     */
    private String password;
}

整个程序的实现过程,主要使用了 Spring AOP 特性,对特定方法进行前、后拦截,从而实现业务方的需求。

最后说一句(求关注!别白嫖!)

如果这篇文章对您有所帮助,或者有所启发的话,求一键三连:点赞、转发、在看。

关注公众号:woniuxgg,在公众号中回复:笔记  就可以获得蜗牛为你精心准备的java实战语雀笔记,回复面试、开发手册、有超赞的粉丝福利!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Java中,我们可以使用注解来为类、方法、变量等元素添加一些元数据信息。下面是一个简单的日志注解的示例: ```java import java.lang.annotation.*; @Target(ElementType.METHOD) // 该注解只能用于方法 @Retention(RetentionPolicy.RUNTIME) // 该注解在运行时保留 public @interface Log { String value() default ""; // 日志信息 } ``` 通过上述代码,我们定义了一个名为Log的注解,它只能用于方法上,并且在运行时保留。该注解包含一个名为value的属性,用来指定日志信息。 接下来,我们可以在需要打印日志的方法上使用该注解,例如: ```java public class Demo { @Log("执行了方法A") public void methodA() { // 方法A的实现 } } ``` 在上述示例中,我们在方法methodA上使用了Log注解,并指定了日志信息为“执行了方法A”。接下来,我们可以在方法执行前后打印日志: ```java public class LogUtil { public static void log(Method method) { Log log = method.getAnnotation(Log.class); if (log != null) { System.out.println(log.value() + " 开始执行..."); } // 执行方法 try { method.invoke(); } catch (Exception e) { e.printStackTrace(); } if (log != null) { System.out.println(log.value() + " 执行结束..."); } } } ``` 在上述代码中,我们定义了一个名为LogUtil的工具类,其中log方法接受一个Method类型的参数,表示需要打印日志的方法。我们首先通过getAnnotation方法获取该方法上的Log注解,如果存在,则打印日志信息并执行该方法。方法执行完毕后,再次检查Log注解是否存在,如果存在,则打印日志信息表示方法执行结束。 最后,我们可以在调用需要打印日志的方法时,使用LogUtil工具类来实现日志打印: ```java public class Main { public static void main(String[] args) { Demo demo = new Demo(); Method method = Demo.class.getMethod("methodA"); LogUtil.log(method); } } ``` 在上述代码中,我们首先创建了一个Demo对象,然后通过反射获取methodA方法,并将其传入LogUtil.log方法中。LogUtil.log方法会根据该方法上的Log注解来打印日志信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值