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里面打印了出来

完毕

Compartir