如何在 GCP Stackdriver 日志记录 UI 中嵌套 LogEntries?

How to nest LogEntries in GCP Stackdriver logging UI?

使用 GCP 日志记录客户端或 API 术语,如何嵌套日志条目,如图所示?

这个use-case在AppEngline Logs docs中有解释。

确保在您发送的请求和应用日志中也将 traceId 字段设置为 non-null 值。这是 Scala 中的示例代码:

import com.google.cloud.MonitoredResource
import com.google.cloud.logging.Payload._
import com.google.cloud.logging._
import collection.JavaConverters._
import org.threeten.bp.Duration

val logging = LoggingOptions.getDefaultInstance().getService()
val traceId = "keasdfwxcbrbntpoiuwehrtiojsadf";

var firstEntry = {
  LogEntry.newBuilder(StringPayload.of("string-payload-one"))
    .setSeverity(Severity.ERROR)
    .setLogName("app")
    .setTimestamp(1519955138399L)
    .setResource(MonitoredResource.newBuilder("global").build())
    .setLabels(Map("environment" -> "testing").asJava)
    .setTrace(traceId)
    .build()
}

var midEntry = {
  LogEntry.newBuilder(StringPayload.of("string-payload-two"))
    .setSeverity(Severity.INFO)
    .setLogName("request")
    .setResource(MonitoredResource.newBuilder("global").build())
    .setHttpRequest(HttpRequest.newBuilder().setStatus(200).setRequestUrl("/about-us").setLatency(Duration.ofMillis(1234)).build())
    .setTimestamp(1519955137906L)
    .setLabels(Map("environment" -> "testing").asJava)
    .setTrace(traceId)
    .build()
}

var lastEntry = {
  LogEntry.newBuilder(StringPayload.of("string-payload-three"))
    .setSeverity(Severity.ERROR)
    .setLogName("app")
    .setResource(MonitoredResource.newBuilder("global").build())
    .setTimestamp(1519955138523L)
    .setLabels(Map("environment" -> "testing").asJava)
    .setTrace(traceId)
    .build()
}

logging.write(List(firstEntry, midEntry, lastEntry).asJava)

最后,日志条目应该显示在它们各自的日志中,并且 "cross-logged" 作为它们的请求的子项,如下所示: