-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path181.java
More file actions
198 lines (180 loc) · 8.34 KB
/
Copy path181.java
File metadata and controls
198 lines (180 loc) · 8.34 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.common.http.policy;
import com.azure.common.http.HttpHeader;
import com.azure.common.http.HttpHeaders;
import com.azure.common.http.HttpPipelineCallContext;
import com.azure.common.http.HttpPipelineNextPolicy;
import com.azure.common.http.HttpRequest;
import com.azure.common.http.HttpResponse;
import com.azure.common.implementation.util.FluxUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
/**
* The Pipeline policy that handles logging of HTTP requests and responses.
*/
public class HttpLoggingPolicy implements HttpPipelinePolicy {
private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
private final HttpLogDetailLevel detailLevel;
private final boolean prettyPrintJSON;
private static final int MAX_BODY_LOG_SIZE = 1024 * 16;
/**
* Creates an HttpLoggingPolicy with the given log level.
*
* @param detailLevel The HTTP logging detail level.
*/
public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) {
this(detailLevel, false);
}
/**
* Creates an HttpLoggingPolicy with the given log level and pretty printing setting.
*
* @param detailLevel The HTTP logging detail level.
* @param prettyPrintJSON If true, pretty prints JSON message bodies when logging.
* If the detailLevel does not include body logging, this flag does nothing.
*/
public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) {
this.detailLevel = detailLevel;
this.prettyPrintJSON = prettyPrintJSON;
}
@Override
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
//
Optional<Object> data = context.getData("caller-method");
String callerMethod;
if (!data.isPresent() || data.get() == null) {
callerMethod = "";
} else {
callerMethod = (String) data.get();
}
//
final Logger logger = LoggerFactory.getLogger(callerMethod);
final long startNs = System.nanoTime();
//
Mono<Void> logRequest = logRequest(logger, context.httpRequest());
Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs);
//
return logRequest.then(next.process()).flatMap(logResponseDelegate)
.doOnError(throwable -> log(logger, "<-- HTTP FAILED: " + throwable));
}
private Mono<Void> logRequest(final Logger logger, final HttpRequest request) {
if (detailLevel.shouldLogURL()) {
log(logger, String.format("--> %s %s", request.httpMethod(), request.url()));
}
if (detailLevel.shouldLogHeaders()) {
for (HttpHeader header : request.headers()) {
log(logger, header.toString());
}
}
//
Mono<Void> reqBodyLoggingMono = Mono.empty();
//
if (detailLevel.shouldLogBody()) {
if (request.body() == null) {
log(logger, "(empty body)");
log(logger, "--> END " + request.httpMethod());
} else {
boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type"));
final long contentLength = getContentLength(request.headers());
if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) {
try {
Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufStream(request.body(), true);
reqBodyLoggingMono = collectedBytes.flatMap(bytes -> {
String bodyString = new String(bytes, StandardCharsets.UTF_8);
bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString);
log(logger, String.format("%s-byte body:%n%s", contentLength, bodyString));
log(logger, "--> END " + request.httpMethod());
return Mono.empty();
});
} catch (Exception e) {
reqBodyLoggingMono = Mono.error(e);
}
} else {
log(logger, contentLength + "-byte body: (content not logged)");
log(logger, "--> END " + request.httpMethod());
}
}
}
return reqBodyLoggingMono;
}
private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final Logger logger, final URL url, final long startNs) {
return (HttpResponse response) -> {
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
//
String contentLengthString = response.headerValue("Content-Length");
String bodySize;
if (contentLengthString == null || contentLengthString.isEmpty()) {
bodySize = "unknown-length";
} else {
bodySize = contentLengthString + "-byte";
}
HttpResponseStatus responseStatus = HttpResponseStatus.valueOf(response.statusCode());
if (detailLevel.shouldLogURL()) {
log(logger, String.format("<-- %s %s %s (%s ms, %s body)", response.statusCode(), responseStatus.reasonPhrase(), url, tookMs, bodySize));
}
if (detailLevel.shouldLogHeaders()) {
for (HttpHeader header : response.headers()) {
log(logger, header.toString());
}
}
if (detailLevel.shouldLogBody()) {
long contentLength = getContentLength(response.headers());
final String contentTypeHeader = response.headerValue("Content-Type");
if ((contentTypeHeader == null || !"application/octet-stream".equalsIgnoreCase(contentTypeHeader))
&& contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) {
final HttpResponse bufferedResponse = response.buffer();
return bufferedResponse.bodyAsString().map(bodyStr -> {
bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr);
log(logger, "Response body:\n" + bodyStr);
log(logger, "<-- END HTTP");
return bufferedResponse;
});
} else {
log(logger, "(body content not logged)");
log(logger, "<-- END HTTP");
}
} else {
log(logger, "<-- END HTTP");
}
return Mono.just(response);
};
}
private String prettyPrintIfNeeded(Logger logger, String contentType, String body) {
String result = body;
if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) {
try {
final Object deserialized = PRETTY_PRINTER.readTree(body);
result = PRETTY_PRINTER.writeValueAsString(deserialized);
} catch (Exception e) {
log(logger, "Failed to pretty print JSON: " + e.getMessage());
}
}
return result;
}
/**
* Process the log using an SLF4j logger and an HTTP message.
*
* @param logger the SLF4j logger with the context of the request
* @param s the message for logging
*/
private void log(Logger logger, String s) {
logger.info(s);
}
private long getContentLength(HttpHeaders headers) {
long contentLength = 0;
try {
contentLength = Long.parseLong(headers.value("content-length"));
} catch (NumberFormatException | NullPointerException ignored) {
}
return contentLength;
}
}