You could use the Logback appender + Implement LoggingEnhacer
public class LogEnhancer implements LoggingEnhancer {
@Override
public void enhanceLogEntry(LogEntry.Builder logEntry) {
// add Labels
logEntry.addLabel("project", "conversational-services");
// Transform textPayload to JSONPayload
ObjectMapper mapper = new ObjectMapper();
Builder structBuilder = Struct.newBuilder();
String textPayload = logEntry.build().getPayload().getData().toString();
try {
// Validate JSON Payload
mapper.readTree(textPayload);
JsonFormat.parser().merge(textPayload, structBuilder);
logEntry.setPayload(JsonPayload.of(structBuilder.build()));
} catch (InvalidProtocolBufferException e) {
// Error reporting an error! FML
System.err.println(e.getMessage());
} catch (IOException e) {
// Do nothing (there is not a JSON Payload)
}
}
}
This class add labels and transform a JSON String in a JSONPayload
You need to specify the LoggingEnhacer on the logback.xml file
<!DOCTYPE configuration>
<configuration>
<appender name="CLOUD" class="com.google.cloud.logging.logback.LoggingAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<log>application.log</log>
<resourceType>gae_app</resourceType>
<!-- References to the LoggingEnhacer class -->
<enhancer>[path_for_your_logging_enhancer_class]</enhancer>
<flushLevel>WARN</flushLevel>
</appender>
<root level="info">
<appender-ref ref="CLOUD" />
</root>
</configuration>