Debian Codegraph @

gcp/setup.go

raw symbols SCIP
1 package gcp
2
3 import (
4 "context"
5 "io"
6 "log/slog"
7 "os"
8 )
9
10 // LevelCritical is an extra log level supported by Cloud Logging.
11 const LevelCritical = slog.Level(12)
12
13 // Handler that outputs JSON understood by the structured log agent.
14 // See https://cloud.google.com/logging/docs/agent/logging/configuration#special-fields
15 type Handler struct {
16 handler slog.Handler
17 }
18
19 // NewHandler returns a new Handler that writes to stderr.
20 func NewHandler(level slog.Level) *Handler {
21 return NewHandlerForWriter(os.Stderr, level)
22 }
23
24 // NewHandlerForWriter returns a new Handler that writes to the given writer.
25 func NewHandlerForWriter(w io.Writer, level slog.Level) *Handler {
26 return &Handler{handler: slog.NewJSONHandler(w, &slog.HandlerOptions{
27 AddSource: true,
28 Level: level,
29 ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
30 if a.Key == slog.MessageKey {
31 a.Key = "message"
32 } else if a.Key == slog.SourceKey {
33 a.Key = "logging.googleapis.com/sourceLocation"
34 } else if a.Key == slog.LevelKey {
35 a.Key = "severity"
36 level, ok := a.Value.Any().(slog.Level)
37 if ok {
38 switch {
39 case level == LevelCritical:
40 a.Value = slog.StringValue("CRITICAL")
41 case level == slog.LevelWarn:
42 // Convert WARN -> WARNING for Cloud Batch
43 a.Value = slog.StringValue("WARNING")
44 }
45 }
46 }
47 return a
48 },
49 })}
50 }
51
52 func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool {
53 return h.handler.Enabled(ctx, level)
54 }
55
56 func (h *Handler) Handle(ctx context.Context, rec slog.Record) error {
57 if trace := TraceFromContext(ctx); trace != "" {
58 rec = rec.Clone()
59 // Add trace ID to the record so it is correlated with the request log
60 // See https://cloud.google.com/trace/docs/trace-log-integration
61 rec.Add("logging.googleapis.com/trace", slog.StringValue(trace))
62 }
63
64 return h.handler.Handle(ctx, rec)
65 }
66
67 func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
68 return &Handler{handler: h.handler.WithAttrs(attrs)}
69 }
70
71 func (h *Handler) WithGroup(name string) slog.Handler {
72 return &Handler{handler: h.handler.WithGroup(name)}
73 }