spring aop实现日志收集

概述

使用spring aop 来实现日志的统一收集功能

详细

使用spring aop 来实现日志的统一收集功能。

spring aop 配置

首先,我们定义2种注解,一种是给service用的,一种是给Controller用的。

给service使用的aop扫描
1
2
3
4
5
6
7
8
9
<aop:aspectj-autoproxy />
 
<context:annotation-config />
 
<context:component-scan base-package="com.demodashi">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
 
<tx:annotation-driven />
给Controller使用的aop扫描
1
2
3
4
5
6
7
8
9
<aop:aspectj-autoproxy />
<aop:aspectj-autoproxy proxy-target-class="true" />
 
<!-- 扫描web包,应用Spring的注解 -->
<context:component-scan  base-package="com.demodashi">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    <context:exclude-filter type="annotation" expression="javax.inject.Named" />
    <context:exclude-filter type="annotation" expression="javax.inject.Inject" />
</context:component-scan>

 

java实现

实现思路,先定义两个注解类,一个给service类用的,一个给从controller类用的,然后使用切面类,对这两个注解进行绑定监控。结果就是,当使用注解绑定某个service类或者controller类的某个方法时,这个切面类就能监控到,并且能获取到这个service方法的相关输入,输出参数等。这样,就能实现了aop日志了。

给controller使用的注解类
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.demodashi.aop.annotation;
import java.lang.annotation.*;   
     
/** 
 *自定义注解 拦截Controller 
 */   
     
@Target({ElementType.PARAMETER, ElementType.METHOD})   
@Retention(RetentionPolicy.RUNTIME)   
@Documented   
public  @interface ControllerLogAnnotation {   
    String description()  default "";   
}
给service使用的注解类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.demodashi.aop.annotation;
import java.lang.annotation.*;   
     
/** 
 *自定义注解 拦截service 
 */   
     
@Target({ElementType.PARAMETER, ElementType.METHOD})   
@Retention(RetentionPolicy.RUNTIME)   
@Documented   
public  @interface ServiceLogAnnotation {   
     
    String description()  default "";   
}
日志切面类
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package com.demodashi.aop;
 
import java.lang.reflect.Method;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
import com.alibaba.fastjson.JSONObject;
import com.demodashi.aop.annotation.ControllerLogAnnotation;
import com.demodashi.aop.annotation.ServiceLogAnnotation;
import com.demodashi.base.UserVO;
 
/**
 * 切点类  
 * @author xgchen
 *
 */
@Aspect   
@Component   
public  class SystemLogAspect {   
     
    public SystemLogAspect(){
    }
     
    //本地异常日志记录对象   
    private  static  final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);   
     
    //Service层切点   
    @Pointcut("@annotation(com.demodashi.aop.annotation.ServiceLogAnnotation)")   
    public  void serviceAspect() {
    }
     
    //Controller层切点   
    @Pointcut("@annotation(com.demodashi.aop.annotation.ControllerLogAnnotation)")   
    public  void controllerAspect() {   
    }
     
    /** 
     * 前置通知 用于拦截Controller层记录用户的操作 
     
     * @param joinPoint 切点 
     */
    @Before("controllerAspect()")
    public  void doBefore4control(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();   
        HttpSession session = request.getSession();   
        //读取session中的用户   
        UserVO user = (UserVO) session.getAttribute("USER");
        //请求的IP   
        String ip = request.getRemoteAddr();   
         try {   
            //*========控制台输出=========*//   
            System.out.println("=====control 前置通知开始=====");
            System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));   
            System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));   
            System.out.println("请求人ID:" + user.getId());
            System.out.println("请求人NAME:" + user.getName());
            System.out.println("请求IP:" + ip);   
            System.out.println("=====前置通知结束=====");   
        catch (Exception e) {
            //记录本地异常日志   
            logger.error("==前置通知异常==");
            logger.error("异常信息:{}", e.getMessage());   
        }
    }
     
    @Before("serviceAspect()")
    public  void doBefore4service(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();   
        HttpSession session = request.getSession();   
        //读取session中的用户   
        UserVO user = (UserVO) session.getAttribute("USER");   
        //获取请求ip   
        String ip = request.getRemoteAddr();
        //获取用户请求方法的参数并序列化为JSON格式字符串   
        String params = "";   
         if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {   
             for ( int i = 0; i < joinPoint.getArgs().length; i++) {   
                params += JSONObject.toJSON(joinPoint.getArgs()[i]).toString() + ";";
            
        }
        try {   
            /*========控制台输出=========*/   
            System.out.println("=====service 前置通知开始=====");
            System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));   
            System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));   
            System.out.println("请求人ID:" + user.getId());
            System.out.println("请求人NAME:" + user.getName());
            System.out.println("请求IP:" + ip);
            System.out.println("请求参数:" + params);
             
        catch (Exception ex) {   
            //记录本地异常日志   
            logger.error("==异常通知异常==");   
            logger.error("异常信息:{}", ex.getMessage());   
        }   
    }
     
    @AfterReturning(pointcut="serviceAspect()", returning="returnValue")
    public  void after4service(JoinPoint joinPoint, Object returnValue) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();   
        HttpSession session = request.getSession();   
        //读取session中的用户   
        UserVO user = (UserVO) session.getAttribute("USER");   
        //获取请求ip   
        String ip = request.getRemoteAddr();
        //获取用户请求方法的参数并序列化为JSON格式字符串   
        String params = "";
         if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {   
             for ( int i = 0; i < joinPoint.getArgs().length; i++) {   
                params += JSONObject.toJSON(joinPoint.getArgs()[i]).toString() + ";";
            
        }
        try {   
            /*========控制台输出=========*/   
            System.out.println("=====service 后置通知开始=====");
            System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));   
            System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));   
            System.out.println("请求人ID:" + user.getId());
            System.out.println("请求人NAME:" + user.getName());
            System.out.println("请求IP:" + ip);
            System.out.println("请求参数:" + params);
            System.out.println("返回值为:" + JSONObject.toJSON(returnValue).toString());
        catch (Exception ex) {   
            //记录本地异常日志   
            logger.error("==异常通知异常==");   
            logger.error("异常信息:{}", ex.getMessage());   
        }
    }
     
    /** 
     * 异常通知 用于拦截service层记录异常日志 
     
     * @param joinPoint 
     * @param e 
     */   
    @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")   
    public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {   
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();   
        HttpSession session = request.getSession();   
        //读取session中的用户   
        UserVO user = (UserVO) session.getAttribute("USER");
        //获取请求ip   
        String ip = request.getRemoteAddr();   
        //获取用户请求方法的参数并序列化为JSON格式字符串   
        String params = "";   
         if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {   
             for ( int i = 0; i < joinPoint.getArgs().length; i++) {   
                 params += JSONObject.toJSON(joinPoint.getArgs()[i]).toString() + ";";
            
        }
        try {   
            /*========控制台输出=========*/   
            System.out.println("=====异常通知开始=====");
            System.out.println("异常代码:" + e.getClass().getName());   
            System.out.println("异常信息:" + e.getMessage());   
            System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));   
            System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));   
            System.out.println("请求人ID:" + user.getId());
            System.out.println("请求人NAME:" + user.getName());
            System.out.println("请求IP:" + ip);
            System.out.println("请求参数:" + params);
             
            System.out.println("=====异常通知结束=====");   
        catch (Exception ex) {   
            //记录本地异常日志   
            logger.error("==异常通知异常==");   
            logger.error("异常信息:{}", ex.getMessage());   
        }   
         /*==========记录本地异常日志==========*/   
        logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params);   
     
    }   
     
     
    /** 
     * 获取注解中对方法的描述信息 用于service层注解 
     
     * @param joinPoint 切点 
     * @return 方法描述 
     * @throws Exception 
     */   
     public  static String getServiceMthodDescription(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();   
        String description = "";   
         for (Method method : methods) {   
             if (method.getName().equals(methodName)) {   
                Class[] clazzs = method.getParameterTypes();   
                 if (clazzs.length == arguments.length) {   
                    description = method.getAnnotation(ServiceLogAnnotation. class).description();   
                     break;   
                }   
            }   
        }   
         return description;   
    }   
     
    /** 
     * 获取注解中对方法的描述信息 用于Controller层注解 
     
     * @param joinPoint 切点 
     * @return 方法描述 
     * @throws Exception 
     */   
     public  static String getControllerMethodDescription(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();   
        String description = "";   
         for (Method method : methods) {   
             if (method.getName().equals(methodName)) {   
                Class[] clazzs = method.getParameterTypes();   
                 if (clazzs.length == arguments.length) {   
                    description = method.getAnnotation(ControllerLogAnnotation. class).description();   
                     break;   
                }   
            }   
        }   
         return description;   
    }   
}
aop使用

就是将注解绑定到具体的service方法上面,或者control方法,如下所示:

1
2
3
4
5
6
@ServiceLogAnnotation(description = "修改密码")
@Override
public UserVO changePassword(UserVO vo, String newPassword) {
    vo.setPassword(newPassword);
    return vo;
}
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
@ResponseBody
@RequestMapping("/editPassword.do")
@ControllerLogAnnotation(description = "接受修改密码的请求")
public Map changePassword(ModelMap modelMap, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String message = null;
    String result = null;
    Object vo = request.getSession().getAttribute("USER");
    if (vo == null) {
        message = "操作失败:对象不能为空!";
    } else if (StringUtils.isBlank(request.getParameter("newPassword"))) {
        message = "新登陆密码不能为空!";
    }
    if (message == null) {
        try {
            userApplication.changePassword((UserVO)vo, request.getParameter("newPassword"));
            message = "修改成功!";
            result = ConstantBean.SUCCESS;
        } catch (Exception e) {
            message = e.getMessage();
            result = ConstantBean.SYSERR;
        }
    } else {
        result = ConstantBean.SYSERR;
    }
     
    return toMap("data", message, "result", result);
}

运行起来

首把demo导入到eclipse后,运行的界面如下:

image.png

用户名 1001 密码 123

登陆后,修改密码,则看到eclipse控制台打印如下信息:

image.png

这样一个aop收集日志的功能了,这样的方式比直接把log写在具体的方法上要强多了,收集起来的log,可以直接写在本地,也可以接入elk方案。

接入elk方案可以参考本网站中的:《ELK + kafka 日志方案》

 

注:本文著作权归作者,由demo大师发表,拒绝转载,转载需要作者授权

 

posted on   demo例子集  阅读(466)  评论(0编辑  收藏  举报

(评论功能已被禁用)
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示