Skip to content

Commit

Permalink
Merge pull request #455 from zanmagerl/logging-stdout
Browse files Browse the repository at this point in the history
Add option to configure GCP logging extension's logging target
  • Loading branch information
loicmathieu authored Jul 5, 2023
2 parents 5e17872 + 78bac84 commit a19a0d2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.Map;
import java.util.Optional;

import com.google.cloud.logging.LoggingHandler.LogTarget;
import com.google.cloud.logging.Severity;
import com.google.cloud.logging.Synchronicity;

Expand Down Expand Up @@ -74,6 +75,14 @@ public class LoggingConfiguration {
@ConfigItem
public StructuredConfig structured;

/**
* Configures if logs should be written to stdout or stderr instead of using Google Cloud Operations API.
* Useful if app is deployed to managed Google Cloud Platform environment with installed logger agent.
* Possible values: STDOUT, STDERR and CLOUD_LOGGING.
*/
@ConfigItem(defaultValue = "CLOUD_LOGGING")
public LogTarget logTarget;

@ConfigGroup
public static class StructuredConfig {

Expand Down Expand Up @@ -198,4 +207,5 @@ public enum LogFormat {
TEXT,
JSON
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,20 @@ public void doPublish(ExtLogRecord record) {
TraceInfo trace = traceExtractor.extract(record);
LogEntry logEntry = transform(record, trace);
if (logEntry != null) {
l.write(ImmutableList.of(logEntry), defaultWriteOptions);
switch (config.logTarget) {
case STDOUT:
System.out.println(logEntry.toStructuredJsonString());
break;
case STDERR:
System.err.println(logEntry.toStructuredJsonString());
break;
case CLOUD_LOGGING:
l.write(ImmutableList.of(logEntry), defaultWriteOptions);
break;
}
}
} catch (Exception ex) {
getErrorManager().error("Failed to publish record to GCP", ex, ErrorManager.WRITE_FAILURE);
getErrorManager().error("Failed to write logs", ex, ErrorManager.WRITE_FAILURE);
}
}

Expand Down Expand Up @@ -138,7 +148,7 @@ private void initDefaultWriteOptions() {
private MonitoredResource createMonitoredResource() {
MonitoredResource.Builder b = MonitoredResource.newBuilder(this.config.resource.type);
if (this.config.resource.label != null) {
this.config.resource.label.forEach((k, v) -> b.addLabel(k, v));
this.config.resource.label.forEach(b::addLabel);
}
return b.build();
}
Expand Down

0 comments on commit a19a0d2

Please sign in to comment.