/
LoggingAppender.java
359 lines (322 loc) · 11.4 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
/*
* 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.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.common.base.Strings;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
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 StackDriver Cloud Logging.
*
* <p>Appender configuration in logback.xml:
*
* <ul>
* <li><appender name="CLOUD" class="com.google.cloud.logging.logback.LoggingAppender">
* <li><log>application.log</log> (Optional, defaults to "java.log" : Stackdriver log
* name)
* <li><level>ERROR</level> (Optional, defaults to "INFO" : logs at or above this
* level)
* <li><flushLevel>WARNING</flushLevel> (Optional, defaults to "ERROR")
* <li><resourceType></resourceType> (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>
* <li><credentialsFile>/path/to/credentials/file</credentialsFile> (Optional,
* defaults to the default credentials of the environment)
* <li>(Optional) add custom labels to log entries using {@link LoggingEnhancer} classes.
* <li><enhancer>com.example.enhancer1</enhancer>
* <li><enhancer>com.example.enhancer2</enhancer>
* <li></appender>
* </ul>
*/
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 STACKTRACE = "fullStacktrace";
private volatile Logging logging;
private LoggingOptions loggingOptions;
private List<LoggingEnhancer> loggingEnhancers;
private List<LoggingEventEnhancer> loggingEventEnhancers;
private WriteOption[] defaultWriteOptions;
private Level flushLevel;
private String log;
private String resourceType;
private String credentialsFile;
private Set<String> enhancerClassNames = new HashSet<>();
private Set<String> loggingEventEnhancerClassNames = new HashSet<>();
/**
* Batched logging requests get immediately flushed for logs at or above this level.
*
* <p>Defaults to Error if not set.
*
* @param flushLevel Logback log level
*/
public void setFlushLevel(Level flushLevel) {
this.flushLevel = flushLevel;
}
/**
* Sets the log filename.
*
* @param log filename
*/
public void setLog(String log) {
this.log = log;
}
/**
* Sets the name of the monitored resource (Optional).
*
* <p>Must be a <a href="https://cloud.google.com/logging/docs/api/v2/resource-list">supported</a>
* resource type. gae_app, gce_instance and container are auto-detected.
*
* <p>Defaults to "global"
*
* @param resourceType name of the monitored resource
*/
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
/**
* Sets the credentials file to use to create the {@link LoggingOptions}. The credentials returned
* by {@link GoogleCredentials#getApplicationDefault()} will be used if no custom credentials file
* has been set.
*
* @param credentialsFile The credentials file to use.
*/
public void setCredentialsFile(String credentialsFile) {
this.credentialsFile = credentialsFile;
}
/** 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);
}
Level getFlushLevel() {
return (flushLevel != null) ? flushLevel : Level.ERROR;
}
String getLogName() {
return (log != null) ? log : "java.log";
}
MonitoredResource getMonitoredResource(String projectId) {
return MonitoredResourceUtil.getResource(projectId, resourceType);
}
List<LoggingEnhancer> getLoggingEnhancers() {
return getEnhancers(enhancerClassNames);
}
List<LoggingEventEnhancer> getLoggingEventEnhancers() {
return getEnhancers(loggingEventEnhancerClassNames);
}
<T> List<T> getEnhancers(Set<String> classNames) {
List<T> loggingEnhancers = new ArrayList<>();
if (classNames != null) {
for (String enhancerClassName : classNames) {
if (enhancerClassName != null) {
T enhancer = getEnhancer(enhancerClassName);
if (enhancer != null) {
loggingEnhancers.add(enhancer);
}
}
}
}
return loggingEnhancers;
}
private <T> T getEnhancer(String enhancerClassName) {
try {
Class<T> clz = (Class<T>) Loader.loadClass(enhancerClassName.trim());
return clz.newInstance();
} catch (Exception ex) {
// If we cannot create the enhancer we fallback to null
}
return null;
}
/** Initialize and configure the cloud logging service. */
@Override
public synchronized void start() {
if (isStarted()) {
return;
}
MonitoredResource resource = getMonitoredResource(getProjectId());
defaultWriteOptions =
new WriteOption[] {WriteOption.logName(getLogName()), WriteOption.resource(resource)};
getLogging().setFlushSeverity(severityFor(getFlushLevel()));
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) {
LogEntry logEntry = logEntryFor(e);
getLogging().write(Collections.singleton(logEntry), 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();
}
}
}
return logging;
}
/** Gets the {@link LoggingOptions} to use for this {@link LoggingAppender}. */
protected LoggingOptions getLoggingOptions() {
if (loggingOptions == null) {
if (Strings.isNullOrEmpty(credentialsFile)) {
loggingOptions = LoggingOptions.getDefaultInstance();
} else {
try {
loggingOptions =
LoggingOptions.newBuilder()
.setCredentials(
GoogleCredentials.fromStream(new FileInputStream(credentialsFile)))
.build();
} 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);
}
}
}
return loggingOptions;
}
private LogEntry logEntryFor(ILoggingEvent e) {
StringBuilder payload = new StringBuilder(e.getFormattedMessage()).append('\n');
writeStack(e.getThrowableProxy(), "", payload);
Level level = e.getLevel();
LogEntry.Builder builder =
LogEntry.newBuilder(Payload.StringPayload.of(e.getMessage().trim()))
.setTimestamp(e.getTimeStamp())
.setSeverity(severityFor(level));
builder
.addLabel(LEVEL_NAME_KEY, level.toString())
.addLabel(LEVEL_VALUE_KEY, String.valueOf(level.toInt()))
.addLabel(LOGGER_NAME_KEY, e.getLoggerName());
.addLabel(STACKTRACE, payload.toString().trim());
for (Map.Entry<String, String> entry : e.getMDCPropertyMap().entrySet()) {
if (null != entry.getKey() && null != entry.getValue()) {
builder.addLabel(entry.getKey(), entry.getValue());
}
}
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;
}
}
}