码迷,mamicode.com
首页 > 编程语言 > 详细

spring boot aop打印http请求回复日志包含请求体

时间:2018-10-10 23:59:57      阅读:368      评论:0      收藏:0      [点我收藏+]

标签:class   one   括号   http请求   cal   更改   web   VID   tchar   

一.引入依赖

        <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请求回复日志包含请求体

标签:class   one   括号   http请求   cal   更改   web   VID   tchar   

原文地址:https://www.cnblogs.com/startnow/p/9769537.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!