forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccessLogHandler.java
More file actions
346 lines (321 loc) · 9.31 KB
/
AccessLogHandler.java
File metadata and controls
346 lines (321 loc) · 9.31 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
340
341
342
343
344
345
346
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
/**
* <h1>Access Log Handler</h1>
* <p>
* Log incoming requested using the
* <a href="https://en.wikipedia.org/wiki/Common_Log_Format">NCSA format</a> (a.k.a common log
* format).
* </p>
*
* If you run behind a reverse proxy that has been configured to send the X-Forwarded-* header,
* please consider to set {@link Router#setTrustProxy(boolean)} option.
*
* <h2>usage</h2>
*
* <pre>{@code
* {
* decorator(new AccessLogHandler());
*
* ...
* }
* }</pre>
*
* <p>
* Output looks like:
* </p>
*
* <pre>
* 127.0.0.1 - - [04/Oct/2016:17:51:42 +0000] "GET / HTTP/1.1" 200 2
* </pre>
*
* <p>
* You probably want to configure the <code>AccessLogHandler</code> logger to save output into a new file:
* </p>
*
* <pre>
* <appender name="ACCESS" class="ch.qos.logback.core.rolling.RollingFileAppender">
* <file>access.log</file>
* <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
* <fileNamePattern>access.%d{yyyy-MM-dd}.log</fileNamePattern>
* </rollingPolicy>
*
* <encoder>
* <pattern>%msg%n</pattern>
* </encoder>
* </appender>
*
* <logger name="io.jooby.AccessLogHandler" additivity="false">
* <appender-ref ref="ACCESS" />
* </logger>
* </pre>
*
* <p>
* By defaults it log the available user context: {@link Context#getUser()}. To override this:
* </p>
*
* <pre>{@code
* {
*
* decorator("*", new AccessLogHandler(ctx -> {
* // retrieve user ID from context.
* }));
* }
* }</pre>
*
* <h2>custom log function</h2>
* <p>
* By default it uses the underlying logging system: <a href="http://logback.qos.ch">logback</a>.
* That's why we previously show how to configure the <code>io.jooby.AccessLogHandler</code> in
* <code>logback.xml</code>.
* </p>
*
* <p>
* If you want to log somewhere else and/or use a different method then:
* </p>
*
* <pre>{@code
* {
* use("*", new AccessLogHandler()
* .log(line -> {
* System.out.println(line);
* }));
* }
* }</pre>
*
* <p>
* This is just an example but of course you can log the <code>NCSA</code> line to database, jms
* queue, etc...
* </p>
*
* <h2>latency</h2>
*
* <pre>{@code
* {
* use("*", new RequestLogger()
* .latency());
* }
* }</pre>
*
* <p>
* It add a new entry at the last of the <code>NCSA</code> output that represents the number of
* <code>ms</code> it took to process the incoming release.
*
* <h2>request and response headers</h2>
* <p>
* You can add extra headers using the {@link AccessLogHandler#requestHeader(String...)} and
* {@link AccessLogHandler#responseHeader(String...)}
* </p>
*
* <h2>dateFormatter</h2>
*
* <pre>{@code
* {
* use("*", new RequestLogger()
* .dateFormatter(ts -> ...));
*
* // OR
* use("*", new RequestLogger()
* .dateFormatter(DateTimeFormatter...));
* }
* }</pre>
*
* <p>
* You can provide a function or an instance of {@link DateTimeFormatter}.
* </p>
*
* <p>
* The default formatter use the default server time zone, provided by
* {@link ZoneId#systemDefault()}. It's possible to just override the time zone (not the entirely
* formatter) too:
* </p>
*
* <pre>{@code
* {
* use("*", new RequestLogger()
* .dateFormatter(ZoneId.of("UTC"));
* }
* }</pre>
*
* @author edgar
* @since 2.5.2
*/
public class AccessLogHandler implements Route.Decorator {
private static final String USER_AGENT = "User-Agent";
private static final String REFERER = "Referer";
private static final DateTimeFormatter FORMATTER = DateTimeFormatter
.ofPattern("dd/MMM/yyyy:HH:mm:ss Z")
.withZone(ZoneId.systemDefault());
private static final String DASH = "-";
private static final char SP = ' ';
private static final char BL = '[';
private static final char BR = ']';
private static final char Q = '\"';
private static final Function<Context, String> USER_OR_DASH = ctx ->
Optional.ofNullable(ctx.getUser())
.map(Object::toString)
.orElse(DASH);
/** Default buffer size. */
private static final int MESSAGE_SIZE = 256;
/** The logging system. */
private final Logger log = LoggerFactory.getLogger(getClass());
private final Function<Context, String> userId;
private Consumer<String> logRecord = log::info;
private Function<Long, String> df;
private List<String> requestHeaders = Collections.emptyList();
private List<String> responseHeaders = Collections.emptyList();
/**
* Creates a new {@link AccessLogHandler} and use the given function and userId provider. Please
* note, if the user isn't present this function is allowed to returns <code>-</code> (dash
* character).
*
* @param userId User ID provider.
*/
public AccessLogHandler(@Nonnull Function<Context, String> userId) {
this.userId = requireNonNull(userId, "User ID provider required.");
dateFormatter(FORMATTER);
}
/**
* Creates a new {@link AccessLogHandler} without user identifier.
*/
public AccessLogHandler() {
this(USER_OR_DASH);
}
@Nonnull @Override public Route.Handler apply(@Nonnull Route.Handler next) {
long timestamp = System.currentTimeMillis();
return ctx -> {
// Take remote address here (less chances of loosing it on interrupted requests).
String remoteAddr = ctx.getRemoteAddress();
ctx.onComplete(context -> {
StringBuilder sb = new StringBuilder(MESSAGE_SIZE);
sb.append(remoteAddr);
sb.append(SP).append(DASH).append(SP);
sb.append(userId.apply(ctx));
sb.append(SP);
sb.append(BL).append(df.apply(timestamp)).append(BR);
sb.append(SP);
sb.append(Q).append(ctx.getMethod());
sb.append(SP);
sb.append(ctx.getRequestPath());
sb.append(ctx.queryString());
sb.append(SP);
sb.append(ctx.getProtocol());
sb.append(Q).append(SP);
sb.append(ctx.getResponseCode().value());
sb.append(SP);
long responseLength = ctx.getResponseLength();
sb.append(responseLength >= 0 ? responseLength : DASH);
long now = System.currentTimeMillis();
sb.append(SP);
sb.append(now - timestamp);
appendHeaders(sb, requestHeaders, h -> ctx.header(h).valueOrNull());
appendHeaders(sb, responseHeaders, h -> ctx.getResponseHeader(h));
logRecord.accept(sb.toString());
});
return next.apply(ctx);
};
}
private void appendHeaders(StringBuilder buff, List<String> requestHeaders,
Function<String, String> headers) {
for (String header : requestHeaders) {
String value = headers.apply(header);
if (value == null) {
buff.append(SP).append(Q).append(DASH).append(Q);
} else {
buff.append(SP).append(Q).append(value).append(Q);
}
}
}
/**
* Log an NCSA line to somewhere.
*
* <pre>{@code
* {
* use("*", new RequestLogger()
* .log(System.out::println)
* );
* }
* }</pre>
*
* @param log Log callback.
* @return This instance.
*/
public @Nonnull AccessLogHandler log(@Nonnull Consumer<String> log) {
this.logRecord = requireNonNull(log, "Consumer is required.");
return this;
}
/**
* Override the default date formatter.
*
* @param formatter New formatter to use.
* @return This instance.
*/
public @Nonnull AccessLogHandler dateFormatter(@Nonnull DateTimeFormatter formatter) {
return dateFormatter(ts -> formatter.format(Instant.ofEpochMilli(ts)));
}
/**
* Override the default date formatter.
*
* @param formatter New formatter to use.
* @return This instance.
*/
public @Nonnull AccessLogHandler dateFormatter(final Function<Long, String> formatter) {
requireNonNull(formatter, "Formatter required.");
this.df = formatter;
return this;
}
/**
* Keep the default formatter but use the provided timezone.
*
* @param zoneId Zone id.
* @return This instance.
*/
public @Nonnull AccessLogHandler dateFormatter(@Nonnull ZoneId zoneId) {
return dateFormatter(FORMATTER.withZone(zoneId));
}
/**
* Append <code>Referer</code> and <code>User-Agent</code> entries to the NCSA line.
*
* @return This instance.
*/
public @Nonnull AccessLogHandler extended() {
return requestHeader(USER_AGENT, REFERER);
}
/**
* Append request headers to the end of line.
*
* @param names Header names.
* @return This instance.
*/
public @Nonnull AccessLogHandler requestHeader(@Nonnull String... names) {
this.requestHeaders = Arrays.asList(names);
return this;
}
/**
* Append response headers to the end of line.
*
* @param names Header names.
* @return This instance.
*/
public @Nonnull AccessLogHandler responseHeader(@Nonnull String... names) {
this.responseHeaders = Arrays.asList(names);
return this;
}
}