Table of Contents
1、设计用户操作日志表: sys_oper_log
2、引入依赖
3、自定义用户操作日志注解
4、自定义用户操作日志切面
5、MyLog注解的使用
6、最终效果
Home Java javaTutorial How to use SpringBoot+Aop to record user operation logs

How to use SpringBoot+Aop to record user operation logs

May 11, 2023 pm 09:16 PM
aop springboot

1、设计用户操作日志表: sys_oper_log

How to use SpringBoot+Aop to record user operation logs

对应实体类为SysOperLog.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

import com.baomidou.mybatisplus.annotation.IdType;

import com.baomidou.mybatisplus.annotation.TableId;

import io.swagger.annotations.ApiModelProperty;

import lombok.Data;

import lombok.EqualsAndHashCode;

import lombok.experimental.Accessors;

import java.io.Serializable;

import java.util.Date;

 

/**

 * <p>

 * 操作日志记录

 * </p>

 */

@Data

@EqualsAndHashCode(callSuper = false)

@Accessors(chain = true)

public class SysOperLog implements Serializable {

 

    private static final long serialVersionUID = 1L;

 

    @TableId(value = "id", type = IdType.AUTO)

    @ApiModelProperty("主键Id")

    private Integer id;

 

    @ApiModelProperty("模块标题")

    private String title;

 

    @ApiModelProperty("参数")

    private String optParam;

 

    @ApiModelProperty("业务类型(0其它 1新增 2修改 3删除)")

    private Integer businessType;

 

    @ApiModelProperty("路径名称")

    private String uri;

 

    @ApiModelProperty("操作状态(0正常 1异常)")

    private Integer status;

 

    @ApiModelProperty("错误消息")

    private String errorMsg;

 

    @ApiModelProperty("操作时间")

    private Date operTime;

}

Copy after login

2、引入依赖

1

2

3

4

5

6

7

8

9

<dependency>

    <groupId>com.alibaba</groupId>

    <artifactId>fastjson</artifactId>

    <version>2.0.9</version>

</dependency>

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-aop</artifactId>

</dependency>

Copy after login

3、自定义用户操作日志注解

MyLog.java

1

2

3

4

5

6

7

8

9

10

11

12

13

import java.lang.annotation.*;

 

@Target({ElementType.PARAMETER, ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface MyLog {

    // 自定义模块名,eg:登录

    String title() default "";

    // 方法传入的参数

    String optParam() default "";

    // 操作类型,eg:INSERT, UPDATE...

    BusinessType businessType() default BusinessType.OTHER; 

}

Copy after login

BusinessType.java — 操作类型枚举类

1

2

3

4

5

6

7

8

9

10

11

12

public enum BusinessType {

    // 其它

    OTHER,

    // 查找

    SELECT,

    // 新增

    INSERT,

    // 修改

    UPDATE,

    // 删除

    DELETE,

}

Copy after login

4、自定义用户操作日志切面

LogAspect.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

import com.alibaba.fastjson.JSONObject;

import iot.sixiang.license.entity.SysOperLog;

import iot.sixiang.license.handler.IotLicenseException;

import iot.sixiang.license.jwt.UserUtils;

import iot.sixiang.license.service.SysOperLogService;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

import org.aspectj.lang.JoinPoint;

import org.aspectj.lang.Signature;

import org.aspectj.lang.annotation.AfterReturning;

import org.aspectj.lang.annotation.AfterThrowing;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Pointcut;

import org.aspectj.lang.reflect.MethodSignature;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

 

import java.lang.reflect.Method;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

 

@Aspect

@Component

@Slf4j

public class LogAspect {

    /**

     * 该Service及其实现类相关代码请自行实现,只是一个简单的插入数据库操作

     */

    @Autowired

    private SysOperLogService sysOperLogService;

     

    /**

     * @annotation(MyLog类的路径) 在idea中,右键自定义的MyLog类-> 点击Copy Reference

     */

    @Pointcut("@annotation(xxx.xxx.xxx.MyLog)")

    public void logPointCut() {

        log.info("------>配置织入点");

    }

 

    /**

     * 处理完请求后执行

     *

     * @param joinPoint 切点

     */

    @AfterReturning(pointcut = "logPointCut()")

    public void doAfterReturning(JoinPoint joinPoint) {

        handleLog(joinPoint, null);

    }

 

    /**

     * 拦截异常操作

     *

     * @param joinPoint 切点

     * @param e         异常

     */

    @AfterThrowing(value = "logPointCut()", throwing = "e")

    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {

        handleLog(joinPoint, e);

    }

 

    private void handleLog(final JoinPoint joinPoint, final Exception e) {

 

        // 获得MyLog注解

        MyLog controllerLog = getAnnotationLog(joinPoint);

        if (controllerLog == null) {

            return;

        }

        SysOperLog operLog = new SysOperLog();

        // 操作状态(0正常 1异常)

        operLog.setStatus(0);

        // 操作时间

        operLog.setOperTime(new Date());

        if (e != null) {

            operLog.setStatus(1);

            // IotLicenseException为本系统自定义的异常类,读者若要获取异常信息,请根据自身情况变通

            operLog.setErrorMsg(StringUtils.substring(((IotLicenseException) e).getMsg(), 0, 2000));

        }

 

        // UserUtils.getUri();获取方法上的路径 如:/login,本文实现方法如下:

        // 1、在拦截器中 String uri = request.getRequestURI();

        // 2、用ThreadLocal存放uri,UserUtils.setUri(uri);

        // 3、UserUtils.getUri();

        String uri = UserUtils.getUri();

        operLog.setUri(uri);

        // 处理注解上的参数

        getControllerMethodDescription(joinPoint, controllerLog, operLog);

        // 保存数据库

        sysOperLogService.addOperlog(operLog.getTitle(), operLog.getBusinessType(), operLog.getUri(), operLog.getStatus(), operLog.getOptParam(), operLog.getErrorMsg(), operLog.getOperTime());

    }

 

    /**

     * 是否存在注解,如果存在就获取,不存在则返回null

     * @param joinPoint

     * @return

     */

    private MyLog getAnnotationLog(JoinPoint joinPoint) {

        Signature signature = joinPoint.getSignature();

        MethodSignature methodSignature = (MethodSignature) signature;

        Method method = methodSignature.getMethod();

        if (method != null) {

            return method.getAnnotation(MyLog.class);

        }

        return null;

    }

 

    /**

     * 获取Controller层上MyLog注解中对方法的描述信息

     * @param joinPoint 切点

     * @param myLog 自定义的注解

     * @param operLog 操作日志实体类

     */

    private void getControllerMethodDescription(JoinPoint joinPoint, MyLog myLog, SysOperLog operLog) {

        // 设置业务类型(0其它 1新增 2修改 3删除)

        operLog.setBusinessType(myLog.businessType().ordinal());

        // 设置模块标题,eg:登录

        operLog.setTitle(myLog.title());

        // 对方法上的参数进行处理,处理完:userName=xxx,password=xxx

        String optParam = getAnnotationValue(joinPoint, myLog.optParam());

        operLog.setOptParam(optParam);

 

    }

 

    /**

     * 对方法上的参数进行处理

     * @param joinPoint

     * @param name

     * @return

     */

    private String getAnnotationValue(JoinPoint joinPoint, String name) {

        String paramName = name;

        // 获取方法中所有的参数

        Map<String, Object> params = getParams(joinPoint);

        // 参数是否是动态的:#{paramName}

        if (paramName.matches("^#\\{\\D*\\}")) {

            // 获取参数名,去掉#{ }

            paramName = paramName.replace("#{", "").replace("}", "");

            // 是否是复杂的参数类型:对象.参数名

            if (paramName.contains(".")) {

                String[] split = paramName.split("\\.");

                // 获取方法中对象的内容

                Object object = getValue(params, split[0]);

                // 转换为JsonObject

                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object);

                // 获取值

                Object o = jsonObject.get(split[1]);

                return String.valueOf(o);

            } else {// 简单的动态参数直接返回

                StringBuilder str = new StringBuilder();

                String[] paraNames = paramName.split(",");

                for (String paraName : paraNames) {

                     

                    String val = String.valueOf(getValue(params, paraName));

                    // 组装成 userName=xxx,password=xxx,

                    str.append(paraName).append("=").append(val).append(",");

                }

                // 去掉末尾的,

                if (str.toString().endsWith(",")) {

                    String substring = str.substring(0, str.length() - 1);

                    return substring;

                } else {

                    return str.toString();

                }

            }

        }

        // 非动态参数直接返回

        return name;

    }

 

    /**

     * 获取方法上的所有参数,返回Map类型, eg: 键:"userName",值:xxx  键:"password",值:xxx

    * @param joinPoint

     * @return

     */

    public Map<String, Object> getParams(JoinPoint joinPoint) {

        Map<String, Object> params = new HashMap<>(8);

        // 通过切点获取方法所有参数值["zhangsan", "123456"]

        Object[] args = joinPoint.getArgs();

        // 通过切点获取方法所有参数名 eg:["userName", "password"]

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        String[] names = signature.getParameterNames();

        for (int i = 0; i < args.length; i++) {

            params.put(names[i], args[i]);

        }

        return params;

    }

 

    /**

     * 从map中获取键为paramName的值,不存在放回null

     * @param map

     * @param paramName

     * @return

     */

    private Object getValue(Map<String, Object> map, String paramName) {

        for (Map.Entry<String, Object> entry : map.entrySet()) {

            if (entry.getKey().equals(paramName)) {

                return entry.getValue();

            }

        }

        return null;

    }

}

Copy after login

5、MyLog注解的使用

1

2

3

4

5

@GetMapping("login")

@MyLog(title = "登录", optParam = "#{userName},#{password}", businessType = BusinessType.OTHER)

public DataResult login(@RequestParam("userName") String userName, @RequestParam("password") String password) {

 ...

}

Copy after login

6、最终效果

How to use SpringBoot+Aop to record user operation logs

The above is the detailed content of How to use SpringBoot+Aop to record user operation logs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

See all articles