gcp
v0.3.0
Documentation
pkg.go.dev ↗Package gcp provides a slog handler that formats log records for Google Cloud Logging structured logging.
Cloud Logging ingests JSON written to stdout/stderr on Cloud Run and GKE, but only promotes fields to first-class status when the keys match its expected names. The default slog.JSONHandler uses the wrong ones:
slog default Cloud Logging expects ────────────────────────────────────────────────────────────────── level → severity (with GCP severity strings, see below) msg → message source → logging.googleapis.com/sourceLocation
This package also defines six severity levels that map 1:1 to Cloud Logging's severity enum, and remaps the trace_id / span_id fields injected by github.com/dio/logging into the logging.googleapis.com/* fields that Cloud Logging uses to link log entries to Cloud Trace spans.
Severity levels
Cloud Logging defines more severity levels than slog's four. This package exposes them as slog.Level constants that fit into slog's numeric space:
Level Value Cloud Logging severity ────────────────────────────────────────────── LevelDebug -4 DEBUG LevelInfo 0 INFO LevelNotice 2 NOTICE LevelWarning 4 WARNING LevelError 8 ERROR LevelEmergency 12 EMERGENCY
Use them anywhere slog.Level is accepted:
logger.Log(ctx, gcp.LevelNotice, "quota threshold reached") logger.Log(ctx, gcp.LevelEmergency, "data loss detected")
Usage
import (
"log/slog"
"os"
log "github.com/dio/logging"
"github.com/dio/logging/gcp"
"github.com/tetratelabs/telemetry/scope"
)
scope.UseLogger(log.New(slog.New(gcp.NewHandler(os.Stderr, "my-project", nil))))
Constants
LevelDebug (6 declarations)
const ( LevelDebug = slog.Level(-4) // DEBUG LevelInfo = slog.Level(0) // INFO LevelNotice = slog.Level(2) // NOTICE (normal but significant events) LevelWarning = slog.Level(4) // WARNING (might cause problems) LevelError = slog.Level(8) // ERROR (likely to cause problems) LevelEmergency = slog.Level(12) // EMERGENCY (system is unusable) )
GCP severity levels as slog.Level constants. These fit into slog's numeric int space and map 1:1 to Cloud Logging severity. https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity
Functions
HTTPRequest
func HTTPRequest(method, url string, status int, latency time.Duration) slog.Attr
HTTPRequest returns an slog.Attr that the GCP sink renders as the canonical Cloud Logging httpRequest structured field. Add it to any log line that summarizes an HTTP request and the Cloud Logging UI will surface Method, URL, Status, and Latency columns plus filter chips:
logger.LogAttrs(ctx, slog.LevelInfo, "request handled",
gcp.HTTPRequest("GET", "/api/echo", 200, 45*time.Millisecond),
slog.String("route", "/api/echo"),
)
The emitted JSON shape:
{
"severity": "INFO",
"message": "request handled",
"httpRequest": {
"requestMethod": "GET",
"requestUrl": "/api/echo",
"status": 200,
"latency": "0.045s"
}
}
For requests where you have additional fields like userAgent or remoteIp, use HTTPRequestFull.
HTTPRequestFull
func HTTPRequestFull( method, url string, status int, latency time.Duration, userAgent, remoteIP, referer, protocol string, requestSize, responseSize int64, ) slog.Attr
HTTPRequestFull returns the same httpRequest attr as HTTPRequest plus any of the optional fields Cloud Logging recognises. Pass empty strings or zero for fields you do not want to emit.
https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#HttpRequest
NewHandler
func NewHandler(w io.Writer, projectID string, opts *slog.HandlerOptions) slog.Handler
NewHandler returns a slog.Handler that writes GCP Cloud Logging compatible JSON to w. It is a slog.NewJSONHandler with ReplaceAttr applied.
projectID is your GCP project ID (e.g. "my-project-123"). It is used to build the logging.googleapis.com/trace field: "projects/my-project-123/traces/<trace_id>".
Pass an empty string to opt into auto-detection:
- GOOGLE_CLOUD_PROJECT env (App Engine, Cloud Functions, gcloud CLI)
- GCLOUD_PROJECT env (legacy)
- GCP metadata server http://metadata.google.internal (Cloud Run, GKE, GCE, App Engine flex), 200ms timeout, cached for the process lifetime
If none of the above resolve a project, the trace correlation rewrite is skipped (logs still emit valid Cloud Logging JSON, they just do not link to Cloud Trace spans).
If opts is nil, defaults are used. If opts.ReplaceAttr is already set it is chained after the GCP remapping so both run.
NewLabelsHandler
func NewLabelsHandler(inner slog.Handler, labelKeys ...string) slog.Handler
NewLabelsHandler wraps a slog.Handler so that any attribute whose key matches labelKeys is emitted under logging.googleapis.com/labels instead of as a flat jsonPayload field.
Use this for bounded, low-cardinality values you want indexed for fast filtering in the Cloud Logging UI: customer, environment, region, service_plane. Do NOT add unbounded keys (request_id, user_id) — Cloud Logging indexes labels and bills you per series regardless of cardinality. Use plain attrs (or SetLogAttrs in the parent package) for unbounded values.
base := gcp.NewHandler(os.Stderr, "", nil)
h := gcp.NewLabelsHandler(base, "customer", "environment", "region")
logger := slog.New(h)
logger.Info("hit",
slog.String("customer", "acme"),
slog.String("environment", "prod"),
slog.Int("rows", 42),
)
// → {
// "severity": "INFO",
// "message": "hit",
// "rows": 42,
// "logging.googleapis.com/labels": {
// "customer": "acme",
// "environment": "prod"
// }
// }
The 64-label cap is GCP's. Past that, overflow keys stay in jsonPayload (still emitted, just not indexed). The handler logs one stderr warning when overflow first occurs so you know to trim the label set.
NewOperationHandler
func NewOperationHandler(inner slog.Handler) slog.Handler
NewOperationHandler wraps a slog.Handler so log records inherit the Operation attached to the record's context via WithOperation.
Typical use:
base := gcp.NewHandler(os.Stderr, "", nil)
h := gcp.NewOperationHandler(base)
logger := slog.New(h)
// In middleware:
ctx = gcp.WithOperation(ctx, gcp.Operation{ID: reqID, Producer: "auth"})
// Anywhere downstream:
logger.InfoContext(ctx, "cache miss")
// → carries logging.googleapis.com/operation = {id: reqID, producer: "auth"}
The handler omits First/Last on the context-derived operation; mark bookend entries explicitly with OperationStart and OperationEnd as per-call slog.Attrs so the Cloud Logging UI groups the request correctly.
OperationEnd
func OperationEnd(id, producer string) slog.Attr
OperationEnd returns an slog.Attr that marks the LAST log entry of an operation. Add it to the log line that records the end of a request:
logger.LogAttrs(ctx, slog.LevelInfo, "request handled",
gcp.OperationEnd(reqID, "auth"))
OperationStart
func OperationStart(id, producer string) slog.Attr
OperationStart returns an slog.Attr that marks the FIRST log entry of an operation. Add it to the log line that records the start of a request:
logger.LogAttrs(ctx, slog.LevelInfo, "request received",
gcp.OperationStart(reqID, "auth"))
ReplaceAttr
func ReplaceAttr(projectID string) func([]string, slog.Attr) slog.Attr
ReplaceAttr returns an slog ReplaceAttr function that remaps slog keys to GCP Cloud Logging field names and converts OTel trace_id / span_id to the logging.googleapis.com/* fields Cloud Logging expects.
projectID accepts an empty string for auto-detection. See NewHandler for the resolution order.
Use this when you need to compose with an existing slog.HandlerOptions:
opts := &slog.HandlerOptions{
AddSource: true,
ReplaceAttr: gcp.ReplaceAttr("my-project"),
}
slog.New(slog.NewJSONHandler(os.Stderr, opts))
ResolveProjectID
func ResolveProjectID(explicit string) string
ResolveProjectID returns the GCP project ID using the standard chain:
- explicit value (if non-empty), returned as-is
- GOOGLE_CLOUD_PROJECT env (App Engine, Cloud Functions, gcloud CLI)
- GCLOUD_PROJECT env (legacy)
- GCP metadata server via cloud.google.com/go/compute/metadata (Cloud Run, GKE, GCE, App Engine flex), 200ms timeout, cached for the process lifetime
On non-GCP environments steps 2-4 fail and ResolveProjectID returns "". Callers should pass the result into NewHandler; an empty value disables the trace correlation rewrite (logs still emit valid Cloud Logging JSON, they just do not link to Cloud Trace).
The metadata fetch happens at most once per process. Both success and failure are cached so non-GCP environments do not pay the timeout repeatedly.
WithOperation
func WithOperation(ctx context.Context, op Operation) context.Context
WithOperation attaches an Operation to ctx. Subsequent log entries emitted with logger.Context(ctx) carry the operation grouping field when the GCP handler is wrapped with NewOperationHandler.
In a typical request flow:
- Middleware sets the operation on the request context once.
- Application code logs normally; operations are emitted automatically.
- The bookend log lines should set First=true and Last=true. Use the helpers OperationStart and OperationEnd to emit those.
Types
Operation
type Operation struct {
// ID is the operation identifier. Required.
ID string
// Producer is the producer of the operation, often the service name.
// Optional but recommended.
Producer string
// First marks the first log entry of the operation. The Cloud Logging
// UI uses this to position the request marker.
First bool
// Last marks the last log entry of the operation. The UI uses this
// to know when to stop grouping.
Last bool
}
Operation describes a Cloud Logging operation, used to group log entries that share an ID under one expandable entry in the Cloud Logging UI.
https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntryOperation
OperationFromContext
func OperationFromContext(ctx context.Context) Operation
OperationFromContext returns the Operation stored in ctx by WithOperation, or the zero Operation if none is set.