github.com/zchee/zap-cloudlogging@v0.0.0-20220819025602-19b026d3900e/trace.go (about) 1 // Copyright 2022 The zap-cloudlogging Authors 2 // SPDX-License-Identifier: BSD-3-Clause 3 4 package zapcloudlogging 5 6 import ( 7 "context" 8 "fmt" 9 10 "cloud.google.com/go/compute/metadata" 11 "go.opentelemetry.io/otel/trace" 12 "go.uber.org/zap" 13 "go.uber.org/zap/zapcore" 14 ) 15 16 const ( 17 // TraceKey is the resource name of the trace associated with the log entry if any. For more information. 18 // 19 // trace field: 20 // - https://cloud.google.com/logging/docs/structured-logging#special-payload-fields 21 // - https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#FIELDS.trace 22 TraceKey = "logging.googleapis.com/trace" 23 24 // SpanKey is the span ID within the trace associated with the log entry. For more information. 25 // 26 // spanId field: 27 // - https://cloud.google.com/logging/docs/structured-logging#special-payload-fields 28 // - https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#FIELDS.span_id 29 SpanKey = "logging.googleapis.com/spanId" 30 31 // TraceSampledKey is the value of this field must be either true or false. For more information. 32 // 33 // trace_sampled field: 34 // - https://cloud.google.com/logging/docs/structured-logging#special-payload-fields 35 // - https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#FIELDS.trace_sampled 36 TraceSampledKey = "logging.googleapis.com/trace_sampled" 37 ) 38 39 // TraceField adds the correct Cloud Logging "trace", "span", "trace_sampled" fields from ctx. 40 // 41 // https://cloud.google.com/logging/docs/agent/logging/configuration#special-fields 42 func TraceField(ctx context.Context) []zapcore.Field { 43 projectID, err := metadata.ProjectID() 44 if err != nil { 45 panic(err) 46 } 47 48 spanCtx := trace.SpanContextFromContext(ctx) 49 50 return []zapcore.Field{ 51 zap.String(TraceKey, fmt.Sprintf("projects/%s/traces/%s", projectID, spanCtx.TraceID().String())), 52 zap.String(SpanKey, spanCtx.SpanID().String()), 53 zap.Bool(TraceSampledKey, spanCtx.IsSampled()), 54 } 55 }