1. 程式人生 > >spring boot aop打印http請求回復日誌包含請求體

spring boot aop打印http請求回復日誌包含請求體

fig can roc Coding ltp 請求 ng- object ets

一.引入依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </
dependency>

二.代碼

AopLoggingApplication 
 1 package com.example;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 import org.springframework.boot.web.servlet.ServletComponentScan;
 6 
 7 @SpringBootApplication
8 @ServletComponentScan 9 public class AopLoggingApplication { 10 11 public static void main(String[] args) { 12 SpringApplication.run(AopLoggingApplication.class, args); 13 } 14 }
SomeFilter  
 1 package com.example.filter;
 2 
 3 import lombok.extern.slf4j.Slf4j;
 4 import org.springframework.web.filter.OncePerRequestFilter;
 5 import org.springframework.web.util.ContentCachingRequestWrapper;
 6 
 7 import javax.servlet.FilterChain;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.annotation.WebFilter;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 
14 @WebFilter
15 @Slf4j
16 public class SomeFilter  extends OncePerRequestFilter {
17     @Override
18     protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
19         log.debug("進入SomeFilter");
20         /**
21          * 因為請求體的流在進入aop時就被關閉了,從request拿到body會拋異常,stream closed.這裏這樣寫可以在aop裏面拿到請求體,具體參考org.springframework.web.filter.AbstractRequestLoggingFilter.
22          * 假如這個方法有更改request的操作 就把這段代碼寫在上面.
23          */
24         if(log.isDebugEnabled()){
25             httpServletRequest = new ContentCachingRequestWrapper(httpServletRequest, 1024);
26         }
27 
28         filterChain.doFilter(httpServletRequest, httpServletResponse);
29     }
30 }
HttpLoggingAspect 
 1 package com.example.aspect;
 2 
 3 import com.fasterxml.jackson.databind.ObjectMapper;
 4 import lombok.extern.slf4j.Slf4j;
 5 import org.aspectj.lang.JoinPoint;
 6 import org.aspectj.lang.ProceedingJoinPoint;
 7 import org.aspectj.lang.annotation.*;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
10 import org.springframework.stereotype.Component;
11 import org.springframework.web.context.request.RequestContextHolder;
12 import org.springframework.web.context.request.ServletRequestAttributes;
13 import org.springframework.web.util.ContentCachingRequestWrapper;
14 import org.springframework.web.util.WebUtils;
15 
16 import javax.servlet.http.HttpServletRequest;
17 import java.io.UnsupportedEncodingException;
18 import java.util.Arrays;
19 @Component
20 @Aspect
21 @Slf4j
22 @ConditionalOnProperty(name = "web-logging", havingValue = "debug")
23 public class HttpLoggingAspect {
24 
25     @Autowired
26     private ObjectMapper mapper;
27 
28     @Pointcut("execution(public * com.example..controller.*.*(..))")//兩個..代表所有子目錄,最後括號裏的兩個..代表所有參數
29     public void logPointCut() {
30     }
31 
32     @Before("logPointCut()")
33     public void doBefore(JoinPoint joinPoint) throws Throwable {
34         // 接收到請求,記錄請求內容
35         ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
36         HttpServletRequest request = attributes.getRequest();
37 
38         // 記錄下請求內容
39         log.debug("┌──────────請求──────────────────");
40         log.debug("┃控制器{}->方法{}-->參數{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), mapper.writeValueAsString(Arrays.toString(joinPoint.getArgs())));
41         log.debug("┃{}-->{}-->{}", request.getRemoteAddr(), request.getMethod(), request.getRequestURL());
42         log.debug("┃parameter{}", mapper.writeValueAsString(request.getParameterMap()));// 格式化輸出的json mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
43         log.debug("┃body{}",getPayload(request));
44         log.debug("└──────────────────────────────");
45 
46     }
47 
48     @Around("logPointCut()")
49     public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
50         long startTime = System.currentTimeMillis();
51         Object ob = pjp.proceed();// ob 為方法的返回值
52         log.debug("┌──────────回復──────────────────");
53         log.debug("┃耗時{}ms" ,(System.currentTimeMillis() - startTime));
54         return ob;
55     }
56 
57     @AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的參數名一致
58     public void doAfterReturning(Object ret) throws Throwable {
59         log.debug("┃返回" + ret);
60         log.debug("└──────────────────────────────");
61     }
62 
63     private String getPayload(HttpServletRequest request) {
64         ContentCachingRequestWrapper wrapper =  WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
65         if (wrapper != null) {
66             byte[] buf = wrapper.getContentAsByteArray();
67             if (buf.length > 0) {
68                 try {
69                     int length = Math.min(buf.length, 1024);//最大只打印1024字節
70                     return new String(buf, 0, length, wrapper.getCharacterEncoding());
71                 } catch (UnsupportedEncodingException var6) {
72                     return "[unknown]";
73                 }
74             }
75         }
76         return "";
77     }
78 }

測試用的TestController

 1 package com.example.controller;
 2 
 3 import org.springframework.web.bind.annotation.GetMapping;
 4 import org.springframework.web.bind.annotation.PostMapping;
 5 import org.springframework.web.bind.annotation.RequestBody;
 6 import org.springframework.web.bind.annotation.RestController;
 7 
 8 import java.util.Map;
 9 
10 @RestController
11 public class TestController {
12     @GetMapping("/")
13     public String hello(String name) {
14         return "Spring boot " + name;
15     }
16 
17     @PostMapping("/")
18     public Map<String, Object> hello(@RequestBody Map<String, Object> map){
19         return map;
20     }
21 }

配置文件application.properties

web-logging=debug #作為啟動web日誌的配置, 方便本地開發和上線
logging.level.com.example=debug

三.效果

1.=====================================================================

請求 GET http://localhost:8080?name=abc
回復Spring boot abc
日誌
 1 2018-10-10 21:55:46.873 DEBUG 53764 --- [nio-8080-exec-2] com.example.filter.SomeFilter            : 進入SomeFilter
 2 2018-10-10 21:55:46.914 DEBUG 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┌──────────請求──────────────────
 3 2018-10-10 21:55:46.929 DEBUG 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃控制器com.example.controller.TestController->方法hello-->參數"[abc]"
 4 2018-10-10 21:55:46.929 DEBUG 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃127.0.0.1-->GET-->http://localhost:8080/
 5 2018-10-10 21:55:47.087 DEBUG 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃parameter{"name":["abc"]}
 6 2018-10-10 21:55:47.087 DEBUG 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃body
 7 2018-10-10 21:55:47.087 DEBUG 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : └──────────────────────────────
 8 2018-10-10 21:55:47.095 DEBUG 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┌──────────回復──────────────────
 9 2018-10-10 21:55:47.095  INFO 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃耗時181ms
10 2018-10-10 21:55:47.096  INFO 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃返回Spring boot abc
11 2018-10-10 21:55:47.096 DEBUG 53764 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : └──────────────────────────────

2.=====================================================================

請求 POST http://localhost:8080 
參數 json類型
{"name":"spring boot"}

回復

{"name":"spring boot"}

日誌

2018-10-10 22:00:11.465 DEBUG 59444 --- [nio-8080-exec-2] com.example.filter.SomeFilter            : 進入SomeFilter
2018-10-10 22:00:11.659 DEBUG 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┌──────────請求──────────────────
2018-10-10 22:00:11.671 DEBUG 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃控制器com.example.controller.TestController->方法hello-->參數"[{name=spring boot}]"
2018-10-10 22:00:11.672 DEBUG 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃127.0.0.1-->POST-->http://localhost:8080/
2018-10-10 22:00:11.696 DEBUG 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃parameter{}
2018-10-10 22:00:11.696 DEBUG 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃body{"name":"spring boot"}
2018-10-10 22:00:11.696 DEBUG 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : └──────────────────────────────
2018-10-10 22:00:11.702 DEBUG 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┌──────────回復──────────────────
2018-10-10 22:00:11.703  INFO 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃耗時44ms
2018-10-10 22:00:11.703  INFO 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : ┃返回{name=spring boot}
2018-10-10 22:00:11.703 DEBUG 59444 --- [nio-8080-exec-2] com.example.aspect.HttpLoggingAspect     : └──────────────────────────────

github: https://github.com/tungss/aop-logging.git

spring boot aop打印http請求回復日誌包含請求體