-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathLoggingAppender.java
575 lines (528 loc) · 19.8 KB
/
LoggingAppender.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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/*
* Copyright 2017 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.logback;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import ch.qos.logback.core.util.Loader;
import com.google.api.core.InternalApi;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.MonitoredResource;
import com.google.cloud.logging.Instrumentation;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.Logging.WriteOption;
import com.google.cloud.logging.LoggingEnhancer;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.MonitoredResourceUtil;
import com.google.cloud.logging.Payload;
import com.google.cloud.logging.Severity;
import com.google.cloud.logging.Synchronicity;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* <a href="https://logback.qos.ch/">Logback</a> appender for Google Cloud Logging.
*
* <p>Appender configuration in <code>logback.xml</code>:
*
* <pre>
* <appender name="CLOUD" class="com.google.cloud.logging.logback.LoggingAppender">
* <!-- Optional: filter logs at and above this level -->
* <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
* <level>INFO</level>
* </filter>
*
* <!-- Optional: defaults to {@code "java.log"} -->
* <log>application.log</log>
*
* <!-- Optional: defaults to {@code "OFF"} -->
* <flushLevel>WARN</flushLevel>
*
* <!-- Optional: defaults to {@code ASYNC} -->
* <writeSynchronicity>SYNC</writeSynchronicity>
*
* <!-- Optional: defaults to {@code true} -->
* <autoPopulateMetadata>false</autoPopulateMetadata>
*
* <!-- Optional: defaults to {@code false} -->
* <redirectToStdout>true</redirectToStdout>
*
* <!-- Optional: auto detects on App Engine Flex, Standard, GCE and GKE, defaults to "global". See <a
* href=
* "https://cloud.google.com/logging/docs/api/v2/resource-list">supported resource types</a> -->
* <resourceType></resourceType>
*
* <!-- Optional: defaults to the default credentials of the environment -->
* <credentialsFile>/path/to/credentials/file</credentialsFile>
*
* <!-- Optional: defaults to the project id obtained during authentication process. Project id is also used to construct resource name of the log entries -->
* <logDestinationProjectId>String</logDestinationProjectId>
*
* <!-- Optional: add custom labels to log entries using {@link LoggingEnhancer} classes -->
* <enhancer>com.example.enhancers.TestLoggingEnhancer</enhancer>
* <enhancer>com.example.enhancers.AnotherEnhancer</enhancer>
*
* <!-- Optional: specifies if a batch's valid entries should be written even if some other entry failed due to an error. Defaults to {@code true} -->
* <partialSuccess>true</partialSuccess>
*
* <!-- Optional: In the asynchronous mode the call(s) to Logging API takes place asynchronously and few calls to `write()`
* method may be batched together to compose a single call to Logging API. In order to control the batching settings,
* the `logbackBatchingSettings` section can be used as shown below.
* See [BatchingSettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.batching.BatchingSettings)
* for more info regarding parameters shown below -->
* <logbackBatchingSettings>
* <elementCountThreshold>100</elementCountThreshold>
* <requestByteThreshold>1000</requestByteThreshold>
* <delayThreshold>500</delayThreshold>
* <maxOutstandingElementCount>10000</maxOutstandingElementCount>
* <maxOutstandingRequestBytes>100000</maxOutstandingRequestBytes>
* <limitExceededBehavior>Ignore</limitExceededBehavior>
* </logbackBatchingSettings>
* </appender>
* </pre>
*/
public class LoggingAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
private static final String LEVEL_NAME_KEY = "levelName";
private static final String LEVEL_VALUE_KEY = "levelValue";
private static final String LOGGER_NAME_KEY = "loggerName";
private static final String TYPE =
"type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent";
private static final List<LoggingEventEnhancer> DEFAULT_LOGGING_EVENT_ENHANCERS =
ImmutableList.of(new MDCEventEnhancer());
public static final String JAVA_LOGBACK_LIBRARY_NAME = "java-logback";
// Using release-please annotations to update DEFAULT_INSTRUMENTATION_VERSION with latest version.
// See
// https://github.com/googleapis/release-please/blob/main/docs/customizing.md#updating-arbitrary-files
// {x-version-update-start:google-cloud-logging-logback:current}
public static final String DEFAULT_INSTRUMENTATION_VERSION = "0.132.4-alpha";
// {x-version-update-end}
private static boolean instrumentationAdded = false;
private static final Object instrumentationLock = new Object();
private volatile Logging logging;
private LoggingOptions loggingOptions;
private MonitoredResource monitoredResource;
private List<LoggingEnhancer> loggingEnhancers;
private List<LoggingEventEnhancer> loggingEventEnhancers;
private WriteOption[] defaultWriteOptions;
private Level flushLevel;
private String log;
private String resourceType;
private String credentialsFile;
private String logDestinationProjectId;
private boolean autoPopulateMetadata = true;
private boolean redirectToStdout = false;
private boolean partialSuccess = true;
private Synchronicity writeSyncFlag = Synchronicity.ASYNC;
private final Set<String> enhancerClassNames = new HashSet<>();
private final Set<String> loggingEventEnhancerClassNames = new HashSet<>();
private LogbackBatchingSettings logbackBatchingSettings = null;
/**
* Sets a threshold for log severity level to flush all log entries that were batched so far.
*
* <p>Defaults to OFF.
*
* @param flushLevel Logback log level
*/
public void setFlushLevel(Level flushLevel) {
this.flushLevel = flushLevel;
}
/**
* Sets the LOG_ID part of the <a
* href="https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#FIELDS.log_name">log
* name</a> for which the logs are ingested.
*
* @param log LOG_ID part of the name
*/
public void setLog(String log) {
this.log = log;
}
/**
* Sets the name of the monitored resource (Optional). If not define the appender will try to
* identify the resource type automatically. Currently support resource types include "gae_app",
* "gce_instance", "k8s_container", "cloud_run_revision" and "cloud_function". If the appender
* fails to identify the resource type, it will be set to "global".
*
* <p>Must be a one of the <a href=
* "https://cloud.google.com/logging/docs/api/v2/resource-list">supported</a> resource types.
*
* @param resourceType the name of the monitored resource.
*/
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
/**
* Sets the path to the <a
* href="https://cloud.google.com/iam/docs/creating-managing-service-account-keys">credential
* file</a>. If not set the appender will use {@link GoogleCredentials#getApplicationDefault()} to
* authenticate.
*
* @param credentialsFile the path to the credentials file.
*/
public void setCredentialsFile(String credentialsFile) {
this.credentialsFile = credentialsFile;
}
/**
* Sets project ID to be used to customize log destination name for written log entries.
*
* @param projectId The project ID to be used to construct the resource destination name for log
* entries.
*/
public void setLogDestinationProjectId(String projectId) {
this.logDestinationProjectId = projectId;
}
/**
* Sets the log ingestion mode. It can be one of the {@link Synchronicity} values.
*
* <p>Default to {@code Synchronicity.ASYNC}
*
* @param flag the new ingestion mode.
*/
public void setWriteSynchronicity(Synchronicity flag) {
this.writeSyncFlag = flag;
}
/**
* Sets the automatic population of metadata fields for ingested logs.
*
* <p>Default to {@code true}.
*
* @param flag the metadata auto-population flag.
*/
public void setAutoPopulateMetadata(boolean flag) {
autoPopulateMetadata = flag;
}
/**
* Sets the redirect of the appender's output to STDOUT instead of ingesting logs to Cloud Logging
* using Logging API.
*
* <p>Default to {@code false}.
*
* @param flag the redirect flag.
*/
public void setRedirectToStdout(boolean flag) {
redirectToStdout = flag;
}
/**
* Sets the {@link LogbackBatchingSettings} to be used for the asynchronous mode call(s) to
* Logging API
*
* <p>Default to {@code null}.
*
* @param batchingSettings the {@link LogbackBatchingSettings} to be used for asynchronous mode
* call(s) to Logging API
*/
public void setLogbackBatchingSettings(LogbackBatchingSettings batchingSettings) {
logbackBatchingSettings = batchingSettings;
}
/**
* Sets the flag indicating if a batch's valid entries should be written even if some other entry
* failed due to an error.
*
* <p>Default to {@code true}.
*
* @param flag the partialSuccess flag.
*/
public void setPartialSuccess(boolean flag) {
partialSuccess = flag;
}
/** Add extra labels using classes that implement {@link LoggingEnhancer}. */
public void addEnhancer(String enhancerClassName) {
this.enhancerClassNames.add(enhancerClassName);
}
public void addLoggingEventEnhancer(String enhancerClassName) {
this.loggingEventEnhancerClassNames.add(enhancerClassName);
}
/**
* Returns the current value of the ingestion mode.
*
* <p>The method is deprecated. Use appender configuration to set up the ingestion
*
* @return a {@link Synchronicity} value of the ingestion module.
*/
@Deprecated
public Synchronicity getWriteSynchronicity() {
return (this.writeSyncFlag != null) ? this.writeSyncFlag : Synchronicity.ASYNC;
}
private void setupMonitoredResource() {
if (monitoredResource == null && autoPopulateMetadata) {
monitoredResource = MonitoredResourceUtil.getResource(getProjectId(), resourceType);
}
}
@InternalApi("Visible for testing")
void setupMonitoredResource(MonitoredResource monitoredResource) {
this.monitoredResource = monitoredResource;
}
private Level getFlushLevel() {
return (flushLevel != null) ? flushLevel : Level.OFF;
}
private String getLogName() {
return (log != null) ? log : "java.log";
}
private List<LoggingEnhancer> getLoggingEnhancers() {
return getEnhancers(enhancerClassNames, LoggingEnhancer.class);
}
private List<LoggingEventEnhancer> getLoggingEventEnhancers() {
if (loggingEventEnhancerClassNames.isEmpty()) {
return DEFAULT_LOGGING_EVENT_ENHANCERS;
} else {
return getEnhancers(loggingEventEnhancerClassNames, LoggingEventEnhancer.class);
}
}
private <T> List<T> getEnhancers(Set<String> classNames, Class<T> classOfT) {
List<T> enhancers = new ArrayList<>();
if (classNames != null) {
for (String className : classNames) {
if (className != null) {
try {
T enhancer =
Loader.loadClass(className.trim())
.asSubclass(classOfT)
.getDeclaredConstructor()
.newInstance();
enhancers.add(enhancer);
} catch (Exception ex) {
// invalid className: ignore
}
}
}
}
return enhancers;
}
/** Initialize and configure the cloud logging service. */
@Override
public synchronized void start() {
if (isStarted()) {
return;
}
setupMonitoredResource();
defaultWriteOptions =
new WriteOption[] {
WriteOption.logName(getLogName()),
WriteOption.resource(monitoredResource),
WriteOption.partialSuccess(partialSuccess)
};
Level flushLevel = getFlushLevel();
if (flushLevel != Level.OFF) {
getLogging().setFlushSeverity(severityFor(flushLevel));
}
loggingEnhancers = new ArrayList<>();
List<LoggingEnhancer> resourceEnhancers = MonitoredResourceUtil.getResourceEnhancers();
loggingEnhancers.addAll(resourceEnhancers);
loggingEnhancers.addAll(getLoggingEnhancers());
loggingEventEnhancers = new ArrayList<>();
loggingEventEnhancers.addAll(getLoggingEventEnhancers());
super.start();
}
String getProjectId() {
return getLoggingOptions().getProjectId();
}
@Override
protected void append(ILoggingEvent e) {
List<LogEntry> entriesList = new ArrayList<>();
entriesList.add(logEntryFor(e));
// Check if instrumentation was already added - if not, create a log entry with instrumentation
// data
if (!setInstrumentationStatus(true)) {
entriesList.add(
Instrumentation.createDiagnosticEntry(
JAVA_LOGBACK_LIBRARY_NAME, DEFAULT_INSTRUMENTATION_VERSION));
}
Iterable<LogEntry> entries = entriesList;
if (autoPopulateMetadata) {
entries =
getLogging()
.populateMetadata(
entries,
monitoredResource,
"com.google.cloud.logging",
"jdk",
"sun",
"java",
"ch.qos.logback");
}
if (redirectToStdout) {
for (LogEntry entry : entries) {
System.out.println(entry.toStructuredJsonString());
}
} else {
getLogging().write(entries, defaultWriteOptions);
}
}
@Override
public synchronized void stop() {
if (logging != null) {
try {
logging.close();
} catch (Exception ex) {
// ignore
}
}
logging = null;
super.stop();
}
Logging getLogging() {
if (logging == null) {
synchronized (this) {
if (logging == null) {
logging = getLoggingOptions().getService();
logging.setWriteSynchronicity(writeSyncFlag);
}
}
}
return logging;
}
/** Flushes any pending asynchronous logging writes. */
@Deprecated
public void flush() {
if (!isStarted()) {
return;
}
synchronized (this) {
getLogging().flush();
}
}
/** Gets the {@link LoggingOptions} to use for this {@link LoggingAppender}. */
protected LoggingOptions getLoggingOptions() {
if (loggingOptions == null) {
LoggingOptions.Builder builder = LoggingOptions.newBuilder();
builder.setProjectId(logDestinationProjectId);
if (!Strings.isNullOrEmpty(credentialsFile)) {
try {
builder.setCredentials(
GoogleCredentials.fromStream(new FileInputStream(credentialsFile)));
} catch (IOException e) {
throw new RuntimeException(
String.format(
"Could not read credentials file %s. Please verify that the file exists and is a valid Google credentials file.",
credentialsFile),
e);
}
}
// opt-out metadata auto-population to control it in the appender code
builder.setAutoPopulateMetadata(false);
builder.setBatchingSettings(
this.logbackBatchingSettings != null ? this.logbackBatchingSettings.build() : null);
loggingOptions = builder.build();
}
return loggingOptions;
}
private LogEntry logEntryFor(ILoggingEvent e) {
StringBuilder payload = new StringBuilder().append(e.getFormattedMessage()).append('\n');
writeStack(e.getThrowableProxy(), "", payload);
Level level = e.getLevel();
Severity severity = severityFor(level);
Map<String, Object> jsonContent = new HashMap<>();
jsonContent.put("message", payload.toString().trim());
if (severity == Severity.ERROR) {
jsonContent.put("@type", TYPE);
}
LogEntry.Builder builder =
LogEntry.newBuilder(Payload.JsonPayload.of(jsonContent))
.setTimestamp(Instant.ofEpochMilli(e.getTimeStamp()))
.setSeverity(severity);
builder
.addLabel(LEVEL_NAME_KEY, level.toString())
.addLabel(LEVEL_VALUE_KEY, String.valueOf(level.toInt()))
.addLabel(LOGGER_NAME_KEY, e.getLoggerName());
if (loggingEnhancers != null) {
for (LoggingEnhancer enhancer : loggingEnhancers) {
enhancer.enhanceLogEntry(builder);
}
}
if (loggingEventEnhancers != null) {
for (LoggingEventEnhancer enhancer : loggingEventEnhancers) {
enhancer.enhanceLogEntry(builder, e);
}
}
return builder.build();
}
@InternalApi("Visible for testing")
static void writeStack(IThrowableProxy throwProxy, String prefix, StringBuilder payload) {
if (throwProxy == null) {
return;
}
payload
.append(prefix)
.append(throwProxy.getClassName())
.append(": ")
.append(throwProxy.getMessage())
.append('\n');
StackTraceElementProxy[] trace = throwProxy.getStackTraceElementProxyArray();
if (trace == null) {
trace = new StackTraceElementProxy[0];
}
int commonFrames = throwProxy.getCommonFrames();
int printFrames = trace.length - commonFrames;
for (int i = 0; i < printFrames; i++) {
payload.append(" ").append(trace[i]).append('\n');
}
if (commonFrames != 0) {
payload.append(" ... ").append(commonFrames).append(" common frames elided\n");
}
writeStack(throwProxy.getCause(), "caused by: ", payload);
}
/**
* Transforms Logback logging levels to Cloud severity.
*
* @param level Logback logging level
* @return Cloud severity level
*/
private static Severity severityFor(Level level) {
switch (level.toInt()) {
// TRACE
case 5000:
return Severity.DEBUG;
// DEBUG
case 10000:
return Severity.DEBUG;
// INFO
case 20000:
return Severity.INFO;
// WARNING
case 30000:
return Severity.WARNING;
// ERROR
case 40000:
return Severity.ERROR;
default:
return Severity.DEFAULT;
}
}
/**
* The package-private helper method used to set the flag which indicates if instrumentation info
* already written or not.
*
* @return The value of the flag before it was set.
*/
static boolean setInstrumentationStatus(boolean value) {
if (instrumentationAdded == value) return instrumentationAdded;
synchronized (instrumentationLock) {
boolean current = instrumentationAdded;
instrumentationAdded = value;
return current;
}
}
}