首页 > 其他分享 >springboot 切面注解方式 记录日志

springboot 切面注解方式 记录日志

时间:2023-05-04 15:25:29浏览次数:35  
标签:interfacePath String GateOpLog logBean 切面 operationType 日志 public springboot

1.定义GateOpLog

import java.lang.annotation.*;

/**
 * 操作日志记录
 * @author codefulture
 */
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GateOpLog {

    /**
     * 说明
     */
    String content() default "";

    /**
     * 业务模块类型
     */
    String operationType();

    /**
     * 接口地址
     */
    String  interfacePath();

}

 

2.定义切面,Pointcut指向GateOpLog

/**
 * 此类主要是用来用户保留操作记录
 * 主要记录的内容有:id,操作人,业务模块、请求方法、请求地址、操作时间
 *
 * @author codefulture
 */
@Aspect
@Slf4j
@Component("gateOpLogAspect")
public class GateOpLogAspect {

    @Autowired
    private GateOperationLogMapper gateOperationLogMapper;

    @Pointcut("@annotation(cn.com.xxx.aspect.GateOpLog)")
    public void gateOpLogAspect() {
    }

    @Before(value = "gateOpLogAspect()")
    public void beforeMethod(JoinPoint joinPoint) throws Exception {
        log.info("==========执行业务操作日志留痕===============");
        this.saveLog(joinPoint);
    }

    public void saveLog(JoinPoint proceedingJoinPoint) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
            String methodName = method.getName();
            String gateId = "";
            GateOpLog opLog = method.getAnnotation(GateOpLog.class);
            String operationType = opLog.operationType();
            String interfacePath = opLog.interfacePath();
            List<Object> args = Arrays.asList(proceedingJoinPoint.getArgs());
            if (args.size() > 0) {
                Object entitys = args.get(0);
                // 如果参数是List类型,取第一个对象
                if (entitys instanceof List) {
                    Object entity = ((List<?>) entitys).get(0);
                    Field rsIdFiled = entity.getClass().getDeclaredField("id");
                    rsIdFiled.setAccessible(true);
                    // 获取ID
                    gateId = StringUtils.defaultString((String) rsIdFiled.get(entity), StringUtils.EMPTY);
                } else {
                    Field rsIdFiled = entitys.getClass().getDeclaredField("id");
                    rsIdFiled.setAccessible(true);
                    // 获取ID
                    gateId = StringUtils.defaultString((String) rsIdFiled.get(entitys), StringUtils.EMPTY);
                }
            }
            operatingLog(gateId, methodName, operationType, interfacePath);
        } catch (Exception e) {
            log.error("******发生异常******", e.getMessage());
        }
    }



    /**
     * 保留业务操作日志
     * @param methodName 方法名
     * @param interfacePath 接口地址
     */
    public void operatingLog(String gateId, String methodName, String operationType,String interfacePath) {
        Subject subject = SecurityUtils.getSubject();
        JwtToken jwtToken = (JwtToken) subject.getPrincipal();
        String currentUsername = jwtToken.getNAME();
        GateOperationLog logBean = new GateOperationLog();
        logBean.setId(UuidUtil.uuid());
        logBean.setGateId(gateId);
        logBean.setOperationType(operationType);
        logBean.setMethodname(methodName);
        logBean.setStatus("1");
        logBean.setOperationUser(currentUsername);
        logBean.setCreatetime(new Date());
        logBean.setAuditUser(currentUsername);
        logBean.setAuditTime(new Date());
        logBean.setInterfacePath(interfacePath);
        gateOperationLogMapper.insert(logBean);//入库的mapper
    }
}

 

3.Controller的接口中使用

    @GateOpLog(operationType = "操作类型", interfacePath = "/app/test/saveSubmit")
    @PostMapping("/saveSubmit")
    public ResponseResult<String> saveSubmit(@RequestBody GeoMatchQuery query){
        //业务代码
    }

 

 测试,在调用Controller的接口时,会先执行 记录日志 的切面方法

 

标签:interfacePath,String,GateOpLog,logBean,切面,operationType,日志,public,springboot
From: https://www.cnblogs.com/Donnnnnn/p/17371325.html

相关文章

  • k8s 编写pod yaml 文件 启动pod 查看pod详细信息 查看pod日志 连接pod容器 删除po
    #1创建podyaml文件#使用帮助命令 [root@master01pod]#kubectlexplainpod.spec[root@master01pod]#catpod-self.yamlapiVersion:v1kind:Podmetadata:name:pod-selfnamespace:defaultlabels:app:my-selfdev:prospec:restartPolic......
  • springboot异常处理的通用方式2
    2、定义一个异常的枚举数组•ServerErrCodeDefine类//```java@AllArgsConstructor@GetterpublicenumServerErrCodeDefine{privateinterrCode;privateStringcode;privateHttpStatushttpStatus;privateStringmessageSourceKey;/***************************......
  • SpringBoot 集成 Shiro 简单教程
    1.前言 ApacheShiro是一个功能强大且易于使用的Java安全框架,提供了认证,授权,加密,和会话管理。Shiro有三大核心组件:Subject: 即当前用户,在权限管理的应用程序里往往需要知道谁能够操作什么,谁拥有操作该程序的权利,shiro中则需要通过Subject来提供基础的当前用户信息,Sub......
  • SpringBoot项目部署在外置Tomcat正常启动,但项目没有被加载的问题
    最近打算部署个SpringBoot项目到外置Tomcat运行,但是发现tomcat启动成功,访问却一直404,刚开始以为是Tomcat的问题,就一直在改Tomcat配置。最后发现tomcat启动时根本就没加载到项目,因为控制台没有打印"SpringBoot"的项目标志经过一番百度查找,最后发现是因为项目启动类没有继承Spring......
  • Vector日志收集
    .=parse_grok!(string!(.message),"%{TIMESTAMP_ISO8601:timestamp}%{GREEDYDATA:message}")https://open.larksuite.com/document/ukTMukTMukTM/uczM3QjL3MzN04yNzcDN?lang=zh-CN......
  • 记录一件很神奇的类型转换问题(springboot项目+echarts)
    今天博主在应付学校的实验,想要使用echarts绘制一张很简单的条形图(博主是初学者),如下(时间还未作排序) 对于横轴,我封装了一个dateList,这个datelist是用java,将数据库中date类型的数据,提取其年月拼装而成的,代码如下:Stringdate=String.valueOf(art.getArticleCreateTime().getYea......
  • java基于springboot+vue非前后端分离的网上商城购物系统、在线商城管理系统,附源码+数
    1、项目介绍java基于springboot+vue非前后端分离的网上商城购物系统、在线商城管理系统,实现管理员:首页、个人中心、用户管理、商品分类管理、商品信息管理、订单评价管理、系统管理、订单管理,用户;首页、个人中心、订单评价管理、我的收藏管理、订单管理,前台首页;首页、商品信息、......
  • SpringBoot定义优雅全局统一Restful API 响应框架二
    这里解决之前留下来的问题,当程序没有正常返回时候就是程序由于运行时异常导致的结果,有些异常我们可,能无法提前预知,不能正常走到我们return的R对象返回。这个时候该如何处理在SpringBoot中,可以使用@ControllerAdvice注解来启用全局异常处理。通过使用@ControllerAdvice注解,可以捕......
  • 【SpringBoot系列】八、SpringBoot 中的事务处理
        前两章节主要讲解了在SpringBoot中关于对数据的操作,本章节将介绍如何进行事务处理。所有的数据访问技术都离不开事务处理,否则将会造成数据不一致。事务是一系列的动作,一旦其中有一个动作出现错误,必须全部回滚,系统将事务中对数据库的所有已完成的操作全部撤消,滚回到事务......
  • 【SpringBoot系列】七、SpringBoot 中使用Redis缓存
        在项目中对数据的访问往往都是直接访问数据库的方式,但如果对数据的访问量很大或者访问很频繁的话,将会对数据库来很大的压力,甚至造成数据库崩溃。为了解决这类问题redis数据库脱颖而出,redis数据库出现时是以非关系数据库的光环展示在广大程序猿的面前的,后来redis的迭代版......