spring boot给接口返回添加输入输出日志

Spring boot返回request、response 添加log

目前有个需求需要给接口返回添加输入输出日志,目前比价常用的方法就是使用过滤器,就可以很方便的拦截到输入请求和输出请求,那么在过滤器里面如何HttpServletRequest HttpServletRequest这两个对象输入和输出日志呢?

解决办法

事实上javax包里面本来就提供HttpServletRequstWrapper、HttpServletResponseWrapper两个包装类进行对请求、和放回进行拦截、我们实现这两个,这样我们就能够写一些单独的东西,就可以实现我们的效果

上代码

request代码如下:

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
public class RequestWrapper extends HttpServletRequestWrapper {
private static Logger logger = LoggerFactory.getLogger(RequestWrapper.class);
private final byte[] body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = getBodyString(request).getBytes(Charset.forName("UTF-8"));
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
//这里从body里面直接读了,没有去读inputStream了,很巧妙的方式
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
public String getBodyString(ServletRequest request) {
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = request.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
logger.warn("处理异常",e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
logger.warn("处理异常",e);
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
logger.warn("处理异常",e);
}
}
}
return sb.toString();
}
}

先写一个ResponseWrapper类来继承HttpServletResponseWrapper

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
package com.dzy.itar.pinpin.support.filter;
import org.apache.commons.io.output.TeeOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
public class ResponseWrapper extends HttpServletResponseWrapper {
private final ByteArrayOutputStream bos = new ByteArrayOutputStream();
private PrintWriter writer = new PrintWriter(bos);
private long id;
public ResponseWrapper(Long requestId, HttpServletResponse response) {
super(response);
this.id = requestId;
}
@Override
public ServletResponse getResponse() {
return this;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream() {
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
private TeeOutputStream tee = new TeeOutputStream(ResponseWrapper.super.getOutputStream(), bos);
@Override
public void write(int b) throws IOException {
tee.write(b);
}
};
}
@Override
public PrintWriter getWriter() throws IOException {
return new TeePrintWriter(super.getWriter(), writer);
}
public byte[] toByteArray(){
return bos.toByteArray();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
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
package com.dzy.itar.pinpin.support.filter;
import java.io.PrintWriter;
public class TeePrintWriter extends PrintWriter{
PrintWriter branch;
public TeePrintWriter(PrintWriter main, PrintWriter branch) {
super(main, true);
this.branch = branch;
}
public void write(char buf[], int off, int len) {
super.write(buf, off, len);
super.flush();
branch.write(buf, off, len);
branch.flush();
}
public void write(String s, int off, int len) {
super.write(s, off, len);
super.flush();
branch.write(s, off, len);
branch.flush();
}
public void write(int c) {
super.write(c);
super.flush();
branch.write(c);
branch.flush();
}
public void flush() {
super.flush();
branch.flush();
}
}
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
package com.dzy.itar.pinpin.support.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.atomic.AtomicLong;
@Component
public class LoggingFilter extends OncePerRequestFilter {
protected static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);
private static final String REQUEST_PREFIX = "Request: ";
private static final String RESPONSE_PREFIX = "Response: ";
private AtomicLong id = new AtomicLong(1);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, final FilterChain filterChain) throws ServletException, IOException {
if (logger.isDebugEnabled()) {
long requestId = id.incrementAndGet();
request = new RequestWrapper(requestId, request);
response = new ResponseWrapper(requestId, response);
}
try {
filterChain.doFilter(request, response);
// response.flushBuffer();
} finally {
if (logger.isDebugEnabled()) {
logRequest(request);
logResponse((ResponseWrapper) response);
}
}
}
private void logRequest(final HttpServletRequest request) {
StringBuilder msg = new StringBuilder();
msg.append(REQUEST_PREFIX);
if (request instanceof RequestWrapper) {
msg.append("request id=").append(((RequestWrapper) request).getId()).append("; ");
}
HttpSession session = request.getSession(false);
if (session != null) {
msg.append("session id=").append(session.getId()).append("; ");
}
if (request.getMethod() != null) {
msg.append("method=").append(request.getMethod()).append("; ");
}
if (request.getContentType() != null) {
msg.append("content type=").append(request.getContentType()).append("; ");
}
msg.append("uri=").append(request.getRequestURI());
if (request.getQueryString() != null) {
msg.append('?').append(request.getQueryString());
}
if (request instanceof RequestWrapper && !isMultipart(request) && !isBinaryContent(request)) {
RequestWrapper requestWrapper = (RequestWrapper) request;
try {
String charEncoding = requestWrapper.getCharacterEncoding() != null ? requestWrapper.getCharacterEncoding() :
"UTF-8";
msg.append("; payload=").append(new String(requestWrapper.toByteArray(), charEncoding));
} catch (UnsupportedEncodingException e) {
logger.warn("Failed to parse request payload", e);
}
}
logger.debug(msg.toString());
}
private boolean isBinaryContent(final HttpServletRequest request) {
if (request.getContentType() == null) {
return false;
}
return request.getContentType().startsWith("image") || request.getContentType().startsWith("video") || request.getContentType().startsWith("audio");
}
private boolean isMultipart(final HttpServletRequest request) {
return request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
}
private void logResponse(final ResponseWrapper response) {
StringBuilder msg = new StringBuilder();
msg.append(RESPONSE_PREFIX);
msg.append("request id=").append((response.getId()));
try {
msg.append("; payload=").append(new String(response.toByteArray(), response.getCharacterEncoding()));
} catch (UnsupportedEncodingException e) {
logger.warn("Failed to parse response payload", e);
}
logger.debug(msg.toString());
}
}

PrintWriter是一种写入字符的一种操作类,可以写入字符,TeePrintWriter继承了他,主要功能是把原始的字符流copy到branch里面。

LoggingFilter是一种filter,继承OncePerRequestFilter,每次请求都会经过他。

主要代码就是上面这样的,我把代码放到了这里大家可以下载借鉴

源码解析

SpringMVC在处理完毕请求之后,会调用AbstractMessageConverterMethodProcessor里的writeWithMessageConverters方法,然后会调用AbstractGenericHttpMessageConverter 的write方法,把返回的接口输出到HttpOutputMessage里面去,事实上,然后会调用WriteInternal方法

然后里面有getBody()方法,然后里面就调用到了我们的getOutputStream方法,终于走到我们写的方法了

然后我们就可以处理这个流了

主要是copy了一份,然后再filter里面打印了出来

完毕

Share

高并发的核心技术-幂等的实现方案

高并发的核心技术-幂等的实现方案

一、背景
我们实际系统中有很多操作,是不管做多少次,都应该产生一样的效果或返回一样的结果。
例如:

  1. 前端重复提交选中的数据,应该后台只产生对应这个数据的一个反应结果。
  2. 我们发起一笔付款请求,应该只扣用户账户一次钱,当遇到网络重发或系统bug重发,也应该只扣一次钱;
  3. 发送消息,也应该只发一次,同样的短信发给用户,用户会哭的;
  4. 创建业务订单,一次业务请求只能创建一个,创建多个就会出大问题。

等等很多重要的情况,这些逻辑都需要幂等的特性来支持。

Read More

Share

初级面试必备教程

##

##一、初级面试必备

####(1)基础部分

  • 1、Hmac加密算法

user_info表被锁住,有哪些数据库操作会锁表,因为只有update、delete这些操作会锁表,所以打算整改这些语句,有子查询的全部整改

Read More

Share

自己收集的面试题

1、描述一下你最近的的一个项目架构

资金平台平台重构+后台对账业务?

如何快速接入银行、怎么保证可扩展性

针对银行接口的变化有哪些考虑

怎么考虑调单情况?

2、描述一下http请求到服务器返回发生了哪些过程

3、数据库死锁?线上怎么定位?怎么解决

4、为什么mysql中主键要自增?

5、你了解哪些sql优化

Read More

Share

自定义注解

1、先上代码(定义注解)

1
2
3
4
5
6
7
8
9
10
@Constraint(validatedBy = DecimalValidator.class) //具体的实现
@Target( { java.lang.annotation.ElementType.METHOD,
java.lang.annotation.ElementType.FIELD })
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Documented
public @interface IsDecimal {
java.lang.String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

Read More

Share

耳鸣疗法

(1)梳头抹耳法:双手十指由前发际向后梳头,梳到头后部时,两掌心贴住耳廓后部,两手分别向左右两侧抹耳廓至面颊部为1次,连续108次。

(2)鸣天鼓法:两掌搓热,用两掌心分别贴住左右两耳,手指托住后脑部,食指压在中指上,使食指从中指上重重地滑落,经此弹击后颈发际处,可听到“咚咚”之声,如击天鼓,共击108次。

(3)掌心震耳(自行鼓膜按摩法):两手掌搓热,用搓热的两手掌心捂住两耳.手掌与耳朵完全封闭,然后两掌突然松开,听到“叭”的一声,起到震耳的作用。共108次。

Read More

Share

搭建SS服务器教程

安装脚本

首先我们下载脚本

1
2
wget --no-check-certificate
https://raw.githubusercontent.com/teddysun/shadowsocks_install/master/shadowsocks.sh

更改权限

1
chmod +x shadowsocks.sh

Read More

Share

如何利用apidoc编写rest风格的文档

一、ApiDoc是什么

事实上我们大多时候说的apidoc实际上是apidoc.js,是使用nodejs命令行模块来生成文档的

Read More

Share

单例模式大比拼

单例模式大比拼

分类

  • 1、饱汉模式
  • 2、懒汉模式
  • 3、最佳模式(多线程安全)

1、饱汉模式

1
2
3
4
5
6
7
8
public final class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}

Read More

Share

RocketMq小解

notify是淘宝的一个消息中间件,它用创新地方式解决了分布式事务的问题,用相对较低的成本,实现了跨微服务的最终一致性

消息系统的核心作用就是三点:解耦,异步和并行

Read More

Share