forked from docker-java/docker-java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLoggingFilter.java
More file actions
339 lines (288 loc) · 13.1 KB
/
Copy pathLoggingFilter.java
File metadata and controls
339 lines (288 loc) · 13.1 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package com.github.dockerjava.jaxrs.filter;
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2011-2014 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* http://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Priority;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Universal logging filter.
*
* Can be used on client or server side. Has the highest priority.
*
* @author Pavel Bucek (pavel.bucek at oracle.com)
* @author Martin Matula (martin.matula at oracle.com)
*/
@PreMatching
@Priority(Integer.MIN_VALUE)
@SuppressWarnings("ClassWithMultipleLoggers")
public class LoggingFilter implements ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter,
ClientResponseFilter, WriterInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class.getName());
private static final String NOTIFICATION_PREFIX = "* ";
private static final String REQUEST_PREFIX = "> ";
private static final String RESPONSE_PREFIX = "< ";
private static final String ENTITY_LOGGER_PROPERTY = LoggingFilter.class.getName() + ".entityLogger";
private static final Comparator<Map.Entry<String, List<String>>> COMPARATOR = new Comparator<Map.Entry<String, List<String>>>() {
@Override
public int compare(final Map.Entry<String, List<String>> o1, final Map.Entry<String, List<String>> o2) {
return o1.getKey().compareToIgnoreCase(o2.getKey());
}
};
private static final int DEFAULT_MAX_ENTITY_SIZE = 8 * 1024;
//
@SuppressWarnings("NonConstantLogger")
private final Logger logger;
private final AtomicLong aid = new AtomicLong(0);
private final Boolean printEntity;
private final int maxEntitySize;
/**
* Create a logging filter logging the request and response to a default JDK logger, named as the fully qualified class name of this
* class. Entity logging is turned off by default.
*/
public LoggingFilter() {
this(LOGGER, false);
}
/**
* Create a logging filter with custom logger and custom settings of entity logging.
*
* @param logger
* the logger to log requests and responses.
* @param printEntity
* if true, entity will be logged as well up to the default maxEntitySize, which is 8KB
*/
@SuppressWarnings("BooleanParameter")
public LoggingFilter(final Logger logger, final Boolean printEntity) {
this.logger = logger;
this.printEntity = printEntity;
this.maxEntitySize = DEFAULT_MAX_ENTITY_SIZE;
}
/**
* Creates a logging filter with custom logger and entity logging turned on, but potentially limiting the size of entity to be buffered
* and logged.
*
* @param logger
* the logger to log requests and responses.
* @param maxEntitySize
* maximum number of entity bytes to be logged (and buffered) - if the entity is larger, logging filter will print (and
* buffer in memory) only the specified number of bytes and print "...more..." string at the end.
*/
public LoggingFilter(final Logger logger, final int maxEntitySize) {
this.logger = logger;
this.printEntity = true;
this.maxEntitySize = maxEntitySize;
}
private void log(final StringBuilder b) {
if (logger != null) {
logger.debug(b.toString());
}
}
private StringBuilder prefixId(final StringBuilder b, final long id) {
b.append(Long.toString(id)).append(" ");
return b;
}
private void printRequestLine(final StringBuilder b, final String note, final long id, final String method,
final URI uri) {
prefixId(b, id).append(NOTIFICATION_PREFIX).append(note).append(" on thread ")
.append(Thread.currentThread().getName()).append("\n");
prefixId(b, id).append(REQUEST_PREFIX).append(method).append(" ").append(uri.toASCIIString()).append("\n");
}
private void printResponseLine(final StringBuilder b, final String note, final long id, final int status) {
prefixId(b, id).append(NOTIFICATION_PREFIX).append(note).append(" on thread ")
.append(Thread.currentThread().getName()).append("\n");
prefixId(b, id).append(RESPONSE_PREFIX).append(Integer.toString(status)).append("\n");
}
private void printPrefixedHeaders(final StringBuilder b, final long id, final String prefix,
final MultivaluedMap<String, String> headers) {
for (final Map.Entry<String, List<String>> headerEntry : getSortedHeaders(headers.entrySet())) {
final List<?> val = headerEntry.getValue();
final String header = headerEntry.getKey();
if (val.size() == 1) {
prefixId(b, id).append(prefix).append(header).append(": ").append(val.get(0)).append("\n");
} else {
final StringBuilder sb = new StringBuilder();
Boolean add = false;
for (final Object s : val) {
if (add) {
sb.append(',');
}
add = true;
sb.append(s);
}
prefixId(b, id).append(prefix).append(header).append(": ").append(sb.toString()).append("\n");
}
}
}
private Set<Map.Entry<String, List<String>>> getSortedHeaders(final Set<Map.Entry<String, List<String>>> headers) {
final TreeSet<Map.Entry<String, List<String>>> sortedHeaders = new TreeSet<Map.Entry<String, List<String>>>(
COMPARATOR);
sortedHeaders.addAll(headers);
return sortedHeaders;
}
private InputStream logInboundEntity(final StringBuilder b, InputStream stream) throws IOException {
if (!stream.markSupported()) {
stream = new BufferedInputStream(stream);
}
stream.mark(maxEntitySize + 1);
final byte[] entity = new byte[maxEntitySize + 1];
final int entitySize = Math.max(0, stream.read(entity));
b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize)));
if (entitySize > maxEntitySize) {
b.append("...more...");
}
b.append('\n');
stream.reset();
return stream;
}
@Override
public void filter(final ClientRequestContext context) throws IOException {
final long id = aid.incrementAndGet();
final StringBuilder b = new StringBuilder();
printRequestLine(b, "Sending client request", id, context.getMethod(), context.getUri());
printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getStringHeaders());
if (printEntity && context.hasEntity()) {
final OutputStream stream = new LoggingStream(b, context.getEntityStream());
context.setEntityStream(stream);
context.setProperty(ENTITY_LOGGER_PROPERTY, stream);
// not calling log(b) here - it will be called by the interceptor
} else {
log(b);
}
}
@Override
public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext)
throws IOException {
final long id = aid.incrementAndGet();
final StringBuilder b = new StringBuilder();
printResponseLine(b, "Client response received", id, responseContext.getStatus());
printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getHeaders());
if (printEntity && responseContext.hasEntity()) {
responseContext.setEntityStream(logInboundEntity(b, responseContext.getEntityStream()));
}
log(b);
}
@Override
public void filter(final ContainerRequestContext context) throws IOException {
final long id = aid.incrementAndGet();
final StringBuilder b = new StringBuilder();
printRequestLine(b, "Server has received a request", id, context.getMethod(), context.getUriInfo()
.getRequestUri());
printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getHeaders());
if (printEntity && context.hasEntity()) {
context.setEntityStream(logInboundEntity(b, context.getEntityStream()));
}
log(b);
}
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
throws IOException {
final long id = aid.incrementAndGet();
final StringBuilder b = new StringBuilder();
printResponseLine(b, "Server responded with a response", id, responseContext.getStatus());
printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getStringHeaders());
if (printEntity && responseContext.hasEntity()) {
final OutputStream stream = new LoggingStream(b, responseContext.getEntityStream());
responseContext.setEntityStream(stream);
requestContext.setProperty(ENTITY_LOGGER_PROPERTY, stream);
// not calling log(b) here - it will be called by the interceptor
} else {
log(b);
}
}
@Override
public void aroundWriteTo(final WriterInterceptorContext writerInterceptorContext) throws IOException,
WebApplicationException {
final LoggingStream stream = (LoggingStream) writerInterceptorContext.getProperty(ENTITY_LOGGER_PROPERTY);
writerInterceptorContext.proceed();
if (stream != null) {
log(stream.getStringBuilder());
}
}
private class LoggingStream extends OutputStream {
private final StringBuilder b;
private final OutputStream inner;
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
LoggingStream(final StringBuilder b, final OutputStream inner) {
this.b = b;
this.inner = inner;
}
StringBuilder getStringBuilder() {
// write entity to the builder
final byte[] entity = baos.toByteArray();
b.append(new String(entity, 0, Math.min(entity.length, maxEntitySize)));
if (entity.length > maxEntitySize) {
b.append("...more...");
}
b.append('\n');
return b;
}
@Override
public void write(final int i) throws IOException {
if (baos.size() <= maxEntitySize) {
baos.write(i);
}
inner.write(i);
}
}
}