欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot+aop切点记录请求和响应信息

程序员文章站 2022-08-05 20:16:29
本篇主要分享的是springboot中结合aop方式来记录请求参数和响应的数据信息;这里主要讲解两种切入点方式,一种方法切入,一种注解切入;首先创建个springboot测试工程并通过maven添加如下依赖: 先来说方法的切点方式,需要创建个名为LogAspect的组件类,然后用@Aspect注解修 ......

  本篇主要分享的是springboot中结合aop方式来记录请求参数和响应的数据信息;这里主要讲解两种切入点方式,一种方法切入,一种注解切入;首先创建个springboot测试工程并通过maven添加如下依赖:

        <!-- aop -->
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-aop</artifactid>
        </dependency>

        <!--阿里 fastjson依赖-->
        <dependency>
            <groupid>com.alibaba</groupid>
            <artifactid>fastjson</artifactid>
            <version>1.2.44</version>
        </dependency>

  先来说方法的切点方式,需要创建个名为logaspect的组件类,然后用@aspect注解修饰组件类,再通过设置方法切入点方式做公共日志记录,如下创建切入点:

    //切点入口 controller包下面所有类的所有方法
    private final string pointcut = "execution(* com.platform.controller..*(..))";

    //切点
    @pointcut(value = pointcut)
    public void log() {
    }

  这里的execution( com.platform.controller..(..))主要的意思是:切入点入口是controller包下面所有类的所有方法;再来通过@around环绕注解方法里面做请求参数和响应信息的记录,如下代码:

    @around(value = "log()")
    public object around(proceedingjoinpoint proceedingjoinpoint) throws throwable {
        object result = null;
        stringbuilder sblog = new stringbuilder("\n");
        try {
            sblog.append(string.format("类名:%s\r\n", proceedingjoinpoint.gettarget().getclass().getname()));

            methodsignature methodsignature = (methodsignature) proceedingjoinpoint.getsignature();
            sblog.append(string.format("方法:%s\r\n", methodsignature.getmethod().getname()));

            object[] args = proceedingjoinpoint.getargs();
            for (object o : args) {
                sblog.append(string.format("参数:%s\r\n", json.tojson(o)));
            }

            long starttime = system.currenttimemillis();
            result = proceedingjoinpoint.proceed();
            long endtime = system.currenttimemillis();
            sblog.append(string.format("返回:%s\r\n", json.tojson(result)));
            sblog.append(string.format("耗时:%ss", endtime - starttime));
        } catch (exception ex) {
            sblog.append(string.format("异常:%s", ex.getmessage()));
        } finally {
            logger.info(sblog.tostring());
        }
        return result;
    }

  此刻主要代码就完成了,再来我们配置下日志的记录方式;首先在 resources目录增加名为logback-spring.xml的文件,其配置信息如:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!--
 3   ~ author:shenniu003
 4   ~ copyright (c) 2018.
 5   -->
 6 
 7 <configuration debug="false" scan="true" scanperiod="1 seconds">
 8 
 9     <springproperty scope="context" name="appname" source="logging.logback.appname"/>
10     <springproperty scope="context" name="loglevel" source="logging.logback.level"/>
11     <springproperty scope="context" name="logpath" source="logging.logback.path"/>
12 
13     <property name="logpathall" value="${logpath}/${appname}.log"/>
14 
15     <contextname>logback</contextname>
16 
17     <appender name="console" class="ch.qos.logback.core.consoleappender">
18         <!-- <filter class="ch.qos.logback.classic.filter.thresholdfilter" >
19              <level>warn</level>
20          </filter>-->
21         <encoder>
22             <pattern>%d{hh:mm:ss.sss} %contextname [%thread] %-5level %logger{36} - %msg%n</pattern>
23         </encoder>
24     </appender>
25 
26     <appender name="file" class="ch.qos.logback.core.rolling.rollingfileappender">
27         <file>${logpathall}</file>
28         <rollingpolicy class="ch.qos.logback.core.rolling.timebasedrollingpolicy">
29             <filenamepattern>${logpathall}.%d{yyyy-mm-dd}.zip</filenamepattern>
30         </rollingpolicy>
31         <encoder>
32             <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
33             </pattern>
34         </encoder>
35     </appender>
36 
37     <root level="${loglevel}">
38         <appender-ref ref="console"/>
39         <appender-ref ref="file"/>
40     </root>
41 
42 </configuration>

  然后application.yml的配置信息如:

1 logging:
2   config: classpath:logback-spring.xml
3   logback:
4     level: info #info ,debug
5     path: /home/app/data/applogs/weblog
6     appname: web

  此刻日志和公共的aop记录类都完成了,我们需要创建个测试用例,其代码如:

1     @postmapping("/adduser")
2     public responseentity<mostudent> adduser(@requestbody mostudent mostudent) throws exception {
3         mostudent.setnumber(uuid.randomuuid().tostring());
4 //        throw new exception("错误了");
5         return new responseentity<>(mostudent, httpstatus.ok);
6     }

  最后,通过postman模拟post请求,能够得到如下的日志结果:

  springboot+aop切点记录请求和响应信息

  上面的方式切入点是所有方法,所有方法都记录日志可能有是不是需求想要的,此时可以通过注解的方式来标记想记录日志的方法;先来创建个日志注解:

 1 @target(elementtype.method)
 2 @retention(retentionpolicy.runtime)
 3 @documented
 4 public @interface logannotation {
 5     /**
 6      * 描述
 7      *
 8      * @return
 9      */
10     string des() default "";
11 }

  同样再来创建注解的切入点:

1     //匹配方法上包含此注解的方法
2     private final string annotationpointcut = "@annotation(com.platform.aop.logannotation)";
3 
4     //注解切点
5     @pointcut(value = annotationpointcut)
6     public void logannotation() {
7     }

  再通过@around注解绑定具体的操作方法:

 1     @around(value = "logannotation()")
 2     public object aroundannotation(proceedingjoinpoint proceedingjoinpoint) throws throwable {
 3         object result = null;
 4         stringbuilder sblog = new stringbuilder("\n");
 5         try {
 6             sblog.append(string.format("类名:%s\r\n", proceedingjoinpoint.gettarget().getclass().getname()));
 7 
 8             methodsignature methodsignature = (methodsignature) proceedingjoinpoint.getsignature();
 9             method method = methodsignature.getmethod();
10             logannotation logannotation = method.getannotation(logannotation.class);
11             if (logannotation != null && !logannotation.des().isempty()) {
12                 sblog.append(string.format("说明:%s\r\n", logannotation.des()));
13             }
14             sblog.append(string.format("方法:%s\r\n", method.getname()));
15 
16             object[] args = proceedingjoinpoint.getargs();
17             for (object o : args) {
18                 sblog.append(string.format("参数:%s\r\n", json.tojson(o)));
19             }
20 
21             long starttime = system.currenttimemillis();
22             result = proceedingjoinpoint.proceed();
23             long endtime = system.currenttimemillis();
24             sblog.append(string.format("返回:%s\r\n", json.tojson(result)));
25             sblog.append(string.format("耗时:%ss", endtime - starttime));
26         } catch (exception ex) {
27             sblog.append(string.format("异常:%s", ex.getmessage()));
28         } finally {
29             logger.info(sblog.tostring());
30         }
31         return result;
32     }

  这个方法里需要注意的是注解方式相比第一种其实就多了如下几行代码:

1             method method = methodsignature.getmethod();
2             logannotation logannotation = method.getannotation(logannotation.class);
3             if (logannotation != null && !logannotation.des().isempty()) {
4                 sblog.append(string.format("说明:%s\r\n", logannotation.des()));
5             }

  下面是注解测试用例:

1     @logannotation(des = "注解记录日志")
2     @postmapping("/adduser01")
3     public responseentity<mostudent> adduser01(@requestbody mostudent mostudent) throws exception {
4         mostudent.setnumber(uuid.randomuuid().tostring());
5         return new responseentity<>(mostudent, httpstatus.ok);
6     }

springboot+aop切点记录请求和响应信息

  如下是logaspect.java的所有代码:

springboot+aop切点记录请求和响应信息
  1 /*
  2  * author:shenniu003
  3  * copyright (c) 2018.
  4  */
  5 
  6 package com.platform.aop;
  7 
  8 import com.alibaba.fastjson.json;
  9 import org.aspectj.lang.proceedingjoinpoint;
 10 import org.aspectj.lang.annotation.*;
 11 import org.aspectj.lang.reflect.methodsignature;
 12 import org.slf4j.logger;
 13 import org.slf4j.loggerfactory;
 14 import org.springframework.stereotype.component;
 15 
 16 import java.lang.reflect.method;
 17 
 18 /**
 19  * created by administrator on 2018/11/5.
 20  * springboot+aop切点记录请求和响应信息
 21  */
 22 @component
 23 @aspect
 24 public class logaspect {
 25 
 26     //切点入口 controller包下面所有类的所有方法
 27     private final string pointcut = "execution(* com.platform.controller..*(..))";
 28 
 29     //匹配方法上包含此注解的方法
 30     private final string annotationpointcut = "@annotation(com.platform.aop.logannotation)";
 31 
 32     private logger logger = loggerfactory.getlogger(logaspect.class);
 33 
 34     //切点
 35     @pointcut(value = pointcut)
 36     public void log() {
 37     }
 38 
 39     @around(value = "log()")
 40     public object around(proceedingjoinpoint proceedingjoinpoint) throws throwable {
 41         object result = null;
 42         stringbuilder sblog = new stringbuilder("\n");
 43         try {
 44             sblog.append(string.format("类名:%s\r\n", proceedingjoinpoint.gettarget().getclass().getname()));
 45 
 46             methodsignature methodsignature = (methodsignature) proceedingjoinpoint.getsignature();
 47             sblog.append(string.format("方法:%s\r\n", methodsignature.getmethod().getname()));
 48 
 49             object[] args = proceedingjoinpoint.getargs();
 50             for (object o : args) {
 51                 sblog.append(string.format("参数:%s\r\n", json.tojson(o)));
 52             }
 53 
 54             long starttime = system.currenttimemillis();
 55             result = proceedingjoinpoint.proceed();
 56             long endtime = system.currenttimemillis();
 57             sblog.append(string.format("返回:%s\r\n", json.tojson(result)));
 58             sblog.append(string.format("耗时:%ss", endtime - starttime));
 59         } catch (exception ex) {
 60             sblog.append(string.format("异常:%s", ex.getmessage()));
 61         } finally {
 62             logger.info(sblog.tostring());
 63         }
 64         return result;
 65     }
 66 
 67     //注解切点
 68     @pointcut(value = annotationpointcut)
 69     public void logannotation() {
 70     }
 71 
 72     @around(value = "logannotation()")
 73     public object aroundannotation(proceedingjoinpoint proceedingjoinpoint) throws throwable {
 74         object result = null;
 75         stringbuilder sblog = new stringbuilder("\n");
 76         try {
 77             sblog.append(string.format("类名:%s\r\n", proceedingjoinpoint.gettarget().getclass().getname()));
 78 
 79             methodsignature methodsignature = (methodsignature) proceedingjoinpoint.getsignature();
 80             method method = methodsignature.getmethod();
 81             logannotation logannotation = method.getannotation(logannotation.class);
 82             if (logannotation != null && !logannotation.des().isempty()) {
 83                 sblog.append(string.format("说明:%s\r\n", logannotation.des()));
 84             }
 85             sblog.append(string.format("方法:%s\r\n", method.getname()));
 86 
 87             object[] args = proceedingjoinpoint.getargs();
 88             for (object o : args) {
 89                 sblog.append(string.format("参数:%s\r\n", json.tojson(o)));
 90             }
 91 
 92             long starttime = system.currenttimemillis();
 93             result = proceedingjoinpoint.proceed();
 94             long endtime = system.currenttimemillis();
 95             sblog.append(string.format("返回:%s\r\n", json.tojson(result)));
 96             sblog.append(string.format("耗时:%ss", endtime - starttime));
 97         } catch (exception ex) {
 98             sblog.append(string.format("异常:%s", ex.getmessage()));
 99         } finally {
100             logger.info(sblog.tostring());
101         }
102         return result;
103     }
104 }
view code