-
Notifications
You must be signed in to change notification settings - Fork 37
/
LoggingHandler.java
484 lines (443 loc) · 17.3 KB
/
LoggingHandler.java
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/*
* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.logging;
import static com.google.common.base.MoreObjects.firstNonNull;
import com.google.cloud.MonitoredResource;
import com.google.cloud.logging.Logging.WriteOption;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.logging.ErrorManager;
import java.util.logging.Filter;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* A logging handler that outputs logs generated with {@link java.util.logging.Logger} to Cloud
* Logging.
*
* <p>Java logging levels (see {@link java.util.logging.Level}) are mapped to the following Google
* Cloud Logging severities:
*
* <table summary="Mapping of Java logging level to Cloud Logging severities">
* <tr>
* <th width="50%">Java Level</th>
* <th>Cloud Logging Severity</th>
* </tr>
* <tr>
* <td>SEVERE</td>
* <td>ERROR</td>
* </tr>
* <tr>
* <td>WARNING</td>
* <td>WARNING</td>
* </tr>
* <tr>
* <td>INFO</td>
* <td>INFO</td>
* </tr>
* <tr>
* <td>CONFIG</td>
* <td>INFO</td>
* </tr>
* <tr>
* <td>FINE</td>
* <td>DEBUG</td>
* </tr>
* <tr>
* <td>FINER</td>
* <td>DEBUG</td>
* </tr>
* <tr>
* <td>FINEST</td>
* <td>DEBUG</td>
* </tr>
* </table>
*
* <p>Original Java logging levels are added as labels (with {@code levelName} and {@code
* levelValue} keys, respectively) to the corresponding Cloud Logging {@link LogEntry}. You can read
* entry labels using {@link LogEntry#getLabels()}. To use logging levels that correspond to Cloud
* Logging severities you can use {@link LoggingLevel}.
*
* <p><b>Configuration</b>: By default each {@code LoggingHandler} is initialized using the
* following {@code LogManager} configuration properties (that you can set in the {@code
* logging.properties} file). If properties are not defined (or have invalid values) then the
* specified default values are used.
*
* <ul>
* <li>{@code com.google.cloud.logging.LoggingHandler.log} the log name (defaults to {@code
* java.log}).
* <li>{@code com.google.cloud.logging.LoggingHandler.level} specifies the default level for the
* handler (defaults to {@code Level.INFO}).
* <li>{@code com.google.cloud.logging.LoggingHandler.filter} specifies the name of a {@link
* Filter} class to use (defaults to no filter).
* <li>{@code com.google.cloud.logging.LoggingHandler.formatter} specifies the name of a {@link
* Formatter} class to use (defaults to {@link SimpleFormatter}).
* <li>{@code com.google.cloud.logging.LoggingHandler.flushLevel} specifies the flush log level.
* When a log with this level is published, logs are transmitted to the Cloud Logging service
* (defaults to {@link LoggingLevel#ERROR}).
* <li>{@code com.google.cloud.logging.LoggingHandler.enhancers} specifies a comma separated list
* of {@link LoggingEnhancer} classes. This handler will call each enhancer list whenever it
* builds a {@link LogEntry} instance (defaults to empty list).
* <li>{@code com.google.cloud.logging.LoggingHandler.resourceType} the type name to use when
* creating the default {@link MonitoredResource} (defaults to auto-detected resource type,
* else "global").
* <li>{@code com.google.cloud.logging.Synchronicity} the synchronicity of the write method to use
* to write logs to the Cloud Logging service (defaults to {@link Synchronicity#ASYNC}).
* <li>{@code com.google.cloud.logging.LoggingHandler.autoPopulateMetadata} is a boolean flag that
* opts-out the population of the log entries metadata before the logs are sent to Cloud
* Logging (defaults to {@code true}).
* <li>{@code com.google.cloud.logging.LoggingHandler.redirectToStdout} is a boolean flag that
* opts-in redirecting the output of the handler to STDOUT instead of ingesting logs to Cloud
* Logging using Logging API (defaults to {@code true}). Redirecting logs can be used in
* Google Cloud environments with installed logging agent to delegate log ingestions to the
* agent. Redirected logs are formatted as one line Json string following the structured
* logging guidelines.
* </ul>
*
* <p>To add a {@code LoggingHandler} to an existing {@link Logger} and be sure to avoid infinite
* recursion when logging, use the {@link #addHandler(Logger, LoggingHandler)} method. Alternatively
* you can add the handler via {@code logging.properties}. For example using the following line:
*
* <pre>
* {@code com.example.mypackage.handlers=com.google.cloud.logging.LoggingHandler}
* </pre>
*
* @see <a href="https://cloud.google.com/logging/docs/structured-logging">Structured logging</a>
*/
public class LoggingHandler extends Handler {
private static final String LEVEL_NAME_KEY = "levelName";
private static final String LEVEL_VALUE_KEY = "levelValue";
private final List<LoggingEnhancer> enhancers;
private final LoggingOptions loggingOptions;
private volatile Logging logging;
// Logs with the same severity with the base could be more efficiently sent to
// Cloud.
// Defaults to level of the handler or Level.FINEST if the handler is set to
// Level.ALL.
// Currently there is no way to modify the base level, see
// https://github.com/googleapis/google-cloud-java/issues/1740 .
private final Level baseLevel;
private volatile Level flushLevel;
private volatile Boolean autoPopulateMetadata;
private volatile Boolean redirectToStdout;
private WriteOption[] defaultWriteOptions;
/** Creates an handler that publishes messages to Cloud Logging. */
public LoggingHandler() {
this(null, null, null);
}
/**
* Creates a handler that publishes messages to Cloud Logging.
*
* @param log the name of the log to which log entries are written
*/
public LoggingHandler(String log) {
this(log, null, null);
}
/**
* Creates a handler that publishes messages to Cloud Logging.
*
* @param log the name of the log to which log entries are written
* @param options options for the Cloud Logging service
*/
public LoggingHandler(String log, LoggingOptions options) {
this(log, options, null);
}
/**
* Creates a handler that publishes messages to Cloud Logging.
*
* @param log the name of the log to which log entries are written
* @param options options for the Cloud Logging service
* @param monitoredResource the monitored resource to which log entries refer. If it is null then
* a default resource is created based on the project ID and deployment environment.
*/
public LoggingHandler(String log, LoggingOptions options, MonitoredResource monitoredResource) {
this(log, options, monitoredResource, null, null);
}
/**
* Creates a handler that publishes messages to Cloud Logging.
*
* @param log the name of the log to which log entries are written
* @param options options for the Cloud Logging service
* @param monitoredResource the monitored resource to which log entries refer. If it is null then
* a default resource is created based on the project ID and deployment environment.
* @param enhancers List of {@link LoggingEnhancer} instances used to enhance any{@link LogEntry}
* instances built by this handler.
*/
public LoggingHandler(
String log,
LoggingOptions options,
MonitoredResource monitoredResource,
List<LoggingEnhancer> enhancers) {
this(log, options, monitoredResource, enhancers, null);
}
/**
* Creates a handler that publishes messages to Cloud Logging. Auto-population of the logs
* metadata can be opted-out in {@code options} argument or in the configuration file. At least
* one flag {@link LoggingOptions} or {@link LoggingConfig} has to be explicitly set to {@code
* false} in order to opt-out the metadata auto-population.
*
* @param log the name of the log to which log entries are written
* @param options options for the Cloud Logging service
* @param monitoredResource the monitored resource to which log entries refer. If it is null then
* a default resource is created based on the project ID and deployment environment.
* @param enhancers List of {@link LoggingEnhancer} instances used to enhance any{@link LogEntry}
* instances built by this handler.
* @param destination the log destination {@link LogDestinationName} (see 'logName' parameter in
* https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry)
*/
public LoggingHandler(
String log,
LoggingOptions options,
MonitoredResource monitoredResource,
List<LoggingEnhancer> enhancers,
LogDestinationName destination) {
try {
loggingOptions = options != null ? options : LoggingOptions.getDefaultInstance();
LoggingConfig config = new LoggingConfig(getClass().getName());
setFilter(config.getFilter());
setFormatter(config.getFormatter());
Level level = config.getLogLevel();
setLevel(level);
baseLevel = level.equals(Level.ALL) ? Level.FINEST : level;
flushLevel = config.getFlushLevel();
Boolean f1 = loggingOptions.getAutoPopulateMetadata();
Boolean f2 = config.getAutoPopulateMetadata();
autoPopulateMetadata = isTrueOrNull(f1) && isTrueOrNull(f2);
redirectToStdout = firstNonNull(config.getRedirectToStdout(), Boolean.FALSE);
String logName = log != null ? log : config.getLogName();
MonitoredResource resource =
firstNonNull(
monitoredResource, config.getMonitoredResource(loggingOptions.getProjectId()));
List<WriteOption> writeOptions = new ArrayList<WriteOption>();
writeOptions.add(WriteOption.logName(logName));
if (resource != null) {
writeOptions.add(WriteOption.resource(resource));
}
writeOptions.add(
WriteOption.labels(
ImmutableMap.of(
LEVEL_NAME_KEY,
baseLevel.getName(),
LEVEL_VALUE_KEY,
String.valueOf(baseLevel.intValue()))));
if (destination != null) {
writeOptions.add(WriteOption.destination(destination));
}
defaultWriteOptions = Iterables.toArray(writeOptions, WriteOption.class);
logging = loggingOptions.getService();
logging.setFlushSeverity(severityFor(flushLevel));
logging.setWriteSynchronicity(config.getSynchronicity());
this.enhancers = new LinkedList<>();
List<LoggingEnhancer> enhancersParam =
firstNonNull(
enhancers,
firstNonNull(config.getEnhancers(), Collections.<LoggingEnhancer>emptyList()));
this.enhancers.addAll(enhancersParam);
// In the following line getResourceEnhancers() never returns null (@NotNull
// attribute)
List<LoggingEnhancer> loggingEnhancers = MonitoredResourceUtil.getResourceEnhancers();
this.enhancers.addAll(loggingEnhancers);
} catch (Exception ex) {
reportError(null, ex, ErrorManager.OPEN_FAILURE);
throw ex;
}
}
@Override
public void publish(LogRecord record) {
// check that the log record should be logged
if (!isLoggable(record)) {
return;
}
// HACK warning: this logger doesn't work like normal loggers; the log calls are
// issued
// from another class instead of by itself, so it can't be configured off like
// normal
// loggers. We have to check the source class name instead.
if ("io.netty.handler.codec.http2.Http2FrameLogger".equals(record.getSourceClassName())) {
return;
}
LogEntry logEntry;
try {
logEntry = logEntryFor(record);
} catch (Exception ex) {
getErrorManager().error(null, ex, ErrorManager.FORMAT_FAILURE);
return;
}
if (logEntry != null) {
try {
Iterable<LogEntry> logEntries =
redirectToStdout
? Instrumentation.populateInstrumentationInfo(ImmutableList.of(logEntry)).y()
: ImmutableList.of(logEntry);
if (autoPopulateMetadata) {
logEntries =
logging.populateMetadata(
logEntries, getMonitoredResource(), "com.google.cloud.logging", "java");
}
if (redirectToStdout) {
logEntries.forEach(log -> System.out.println(log.toStructuredJsonString()));
} else {
logging.write(logEntries, defaultWriteOptions);
}
} catch (Exception ex) {
getErrorManager().error(null, ex, ErrorManager.WRITE_FAILURE);
}
}
}
private MonitoredResource getMonitoredResource() {
Optional<WriteOption> resourceOption =
Arrays.stream(defaultWriteOptions)
.filter(o -> o.getOptionType() == WriteOption.OptionType.RESOURCE)
.findFirst();
if (resourceOption.isPresent()) {
return (MonitoredResource) resourceOption.get().getValue();
}
return null;
}
private LogEntry logEntryFor(LogRecord record) throws Exception {
String payload = getFormatter().format(record);
Level level = record.getLevel();
LogEntry.Builder builder =
LogEntry.newBuilder(Payload.StringPayload.of(payload))
.setTimestamp(Instant.ofEpochMilli(record.getMillis()))
.setSeverity(severityFor(level));
if (!baseLevel.equals(level)) {
builder
.addLabel("levelName", level.getName())
.addLabel("levelValue", String.valueOf(level.intValue()));
}
for (LoggingEnhancer enhancer : enhancers) {
enhancer.enhanceLogEntry(builder);
}
return builder.build();
}
@Override
public void flush() {
try {
logging.flush();
} catch (Exception ex) {
getErrorManager().error(null, ex, ErrorManager.FLUSH_FAILURE);
}
}
/** Closes the handler and the associated {@link Logging} object. */
@Override
public synchronized void close() throws SecurityException {
if (logging != null) {
try {
logging.close();
} catch (Exception ex) {
// ignore
}
}
logging = null;
}
/** Get the flush log level. */
public Level getFlushLevel() {
return flushLevel;
}
/**
* Sets minimum logging level to log immediately and flush any pending writes.
*
* @param flushLevel minimum log level to trigger flush
*/
public void setFlushLevel(Level flushLevel) {
this.flushLevel = flushLevel;
logging.setFlushSeverity(severityFor(flushLevel));
}
/**
* Sets synchronicity of logging writes. By default, writes are asynchronous.
*
* @param synchronicity {@link Synchronicity}
*/
public void setSynchronicity(Synchronicity synchronicity) {
logging.setWriteSynchronicity(synchronicity);
}
/** Get the flush log level. */
public Synchronicity getSynchronicity() {
return logging.getWriteSynchronicity();
}
/** Sets the metadata auto population flag. */
public void setAutoPopulateMetadata(boolean value) {
this.autoPopulateMetadata = value;
}
/** Gets the metadata auto population flag. */
public Boolean getAutoPopulateMetadata() {
return this.autoPopulateMetadata;
}
/**
* Enable/disable redirection to STDOUT. If set to {@code true}, logs will be printed to STDOUT in
* the Json format that can be parsed by the logging agent. If set to {@code false}, logs will be
* ingested to Cloud Logging by calling Logging API.
*/
public void setRedirectToStdout(boolean value) {
this.redirectToStdout = value;
}
public Boolean getRedirectToStdout() {
return redirectToStdout;
}
/**
* Adds the provided {@code LoggingHandler} to {@code logger}. Use this method to register Cloud
* Logging handlers instead of {@link Logger#addHandler(Handler)} to avoid infinite recursion when
* logging.
*/
public static void addHandler(Logger logger, LoggingHandler handler) {
logger.addHandler(handler);
}
private static Severity severityFor(Level level) {
if (level instanceof LoggingLevel) {
return ((LoggingLevel) level).getSeverity();
}
switch (level.intValue()) {
// FINEST
case 300:
return Severity.DEBUG;
// FINER
case 400:
return Severity.DEBUG;
// FINE
case 500:
return Severity.DEBUG;
// CONFIG
case 700:
return Severity.INFO;
// INFO
case 800:
return Severity.INFO;
// WARNING
case 900:
return Severity.WARNING;
// SEVERE
case 1000:
return Severity.ERROR;
default:
return Severity.DEFAULT;
}
}
private static boolean isTrueOrNull(Boolean b) {
return b == null || b == Boolean.TRUE;
}
}