Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

google-cloud-logging-logback: Allow user to specify custom LoggingOptions #4729

Merged
merged 5 commits into from
Apr 2, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,23 @@ Authentication
See the [Authentication](https://github.com/googleapis/google-cloud-java#authentication)
section in the base directory's README.

You can also specify custom credentials and other options by creating a subclass of `com.google.cloud.logging.logback.LoggingAppender` and override the method `createLoggingOptions()`. Your logback.xml configuration file must reference your subclass instead of `com.google.cloud.logging.logback.LoggingAppender`.

olavloite marked this conversation as resolved.
Show resolved Hide resolved
```java
public class CustomLoggingAppender extends LoggingAppender {
@Override
public LoggingOptions createLoggingOptions() {
try {
return LoggingOptions.newBuilder()
.setCredentials(GoogleCredentials.fromStream(
new FileInputStream("/path/to/credentials.json")))
.build();
} catch (IOException e) {
throw new RuntimeException("Could not find credentials", e);
}
}
}
```

Limitations
-----------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
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;
Expand All @@ -32,6 +33,9 @@
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;
Expand All @@ -55,6 +59,8 @@
* 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>&lt;credentialsFile&gt;/path/to/credentials/file&lt;/credentialsFile&gt; (Optional,
* defaults to the default credentials of the environment)
* <li>(Optional) add custom labels to log entries using {@link LoggingEnhancer} classes.
* <li>&lt;enhancer&gt;com.example.enhancer1&lt;/enhancer&gt;
* <li>&lt;enhancer&gt;com.example.enhancer2&lt;/enhancer&gt;
Expand All @@ -74,6 +80,7 @@ public class LoggingAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
private Level flushLevel;
private String log;
private String resourceType;
private String credentialsFile;
private Set<String> enhancerClassNames = new HashSet<>();
private Set<String> loggingEventEnhancerClassNames = new HashSet<>();

Expand Down Expand Up @@ -111,6 +118,17 @@ 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);
Expand Down Expand Up @@ -186,7 +204,7 @@ public synchronized void start() {
}

String getProjectId() {
return LoggingOptions.getDefaultInstance().getProjectId();
return createLoggingOptions().getProjectId();
}

@Override
Expand All @@ -212,13 +230,32 @@ Logging getLogging() {
if (logging == null) {
synchronized (this) {
if (logging == null) {
logging = LoggingOptions.getDefaultInstance().getService();
logging = createLoggingOptions().getService();
}
}
}
return logging;
}

/** Creates the {@link LoggingOptions} to use for this {@link LoggingAppender}. */
LoggingOptions createLoggingOptions() {
olavloite marked this conversation as resolved.
Show resolved Hide resolved
if (Strings.isNullOrEmpty(credentialsFile)) {
return LoggingOptions.getDefaultInstance();
} else {
try {
return 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);
}
}
}

private LogEntry logEntryFor(ILoggingEvent e) {
StringBuilder payload = new StringBuilder(e.getFormattedMessage()).append('\n');
writeStack(e.getThrowableProxy(), "", payload);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.fail;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.filter.ThresholdFilter;
Expand Down Expand Up @@ -211,6 +212,19 @@ public void testMdcValuesAreConvertedToLabels() {
assertThat(capturedArgument.getValue().iterator().next()).isEqualTo(logEntry);
}

@Test
public void testCreateLoggingOptions() {
final String nonExistentFile = "/path/to/non/existent/file";
LoggingAppender appender = new LoggingAppender();
appender.setCredentialsFile(nonExistentFile);
try {
appender.createLoggingOptions();
fail("Expected exception");
} catch (Exception e) {
assertThat(e.getMessage().contains(nonExistentFile));
}
}

private LoggingEvent createLoggingEvent(Level level, long timestamp) {
LoggingEvent loggingEvent = new LoggingEvent();
loggingEvent.setMessage("this is a test");
Expand Down