Skip to content

Commit

Permalink
Add custom log enhancer to add more information to GCP LogEntry.
Browse files Browse the repository at this point in the history
  • Loading branch information
ekharkunov committed Oct 16, 2024
1 parent 34c5d68 commit 0d18a16
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.defold.extender.log;

import com.google.cloud.logging.LogEntry.Builder;
import com.google.cloud.logging.LoggingEnhancer;
import com.google.cloud.logging.logback.LoggingEventEnhancer;


import ch.qos.logback.classic.spi.ILoggingEvent;

public class ExtenderLogEnhancer implements LoggingEnhancer, LoggingEventEnhancer {
@Override
public void enhanceLogEntry(Builder builder) {
if (ExtenderLogEnhancerConfiguration.isInitialized()) {
builder.setResource(ExtenderLogEnhancerConfiguration.getMonitoredResource());
}
}

@Override
public void enhanceLogEntry(Builder builder, ILoggingEvent e) {
enhanceLogEntry(builder);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.defold.extender.log;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.google.cloud.MonitoredResource;
import com.google.cloud.spring.core.DefaultGcpProjectIdProvider;

@Component
public class ExtenderLogEnhancerConfiguration {

private String instanceName;
private String applicationName;
private String instanceLocation;
private String projectId;
private MonitoredResource monitoredResource;

private static ExtenderLogEnhancerConfiguration instance;
private ExtenderLogEnhancerConfiguration(@Autowired Environment env) {
if (instance != null) {
throw new IllegalStateException("ExtenderLogEnhancerConfiguration already initialized");
}
instance = this;
this.instanceName = env.getProperty("management.metrics.tags.instance", "unknown");
this.applicationName = env.getProperty("management.metrics.tags.application", "unknown");
this.instanceLocation = env.getProperty("extender.logging.instance-location", "europe-west1-b");
this.projectId = new DefaultGcpProjectIdProvider().getProjectId();
this.monitoredResource = MonitoredResource.newBuilder("generic_node")
.addLabel("project_id", projectId)
.addLabel("location", instanceLocation)
.addLabel("namespace", applicationName)
.addLabel("node_id", instanceName)
.build();
}

public static boolean isInitialized() {
return instance != null;
}

public static MonitoredResource getMonitoredResource() {
return instance != null ? instance.monitoredResource : null;
}
}

0 comments on commit 0d18a16

Please sign in to comment.