Debian Codegraph @

logging/logger.go

raw
1 // Package logging wires the nebula runtime-reconfigurable slog handler used
2 // by nebula.Main and the nebula CLI binaries. Callers build a logger with
3 // NewLogger, then call ApplyConfig at startup and from a config reload
4 // callback to push logging.level, logging.format, and
5 // logging.disable_timestamp changes onto the logger without rebuilding it.
6 package logging
7
8 import (
9 "context"
10 "fmt"
11 "io"
12 "log/slog"
13 "strings"
14 "sync/atomic"
15 "time"
16 )
17
18 // Config is the subset of *config.C that ApplyConfig reads. Declaring it
19 // here keeps the logging package from depending on config directly, which
20 // would cycle through the shared test helpers (test.NewLogger imports
21 // logging, and config's tests import test). *config.C satisfies this
22 // interface structurally with no adapter.
23 type Config interface {
24 GetString(key, def string) string
25 GetBool(key string, def bool) bool
26 }
27
28 // LevelTrace is a custom slog level below Debug, used when logging.level is
29 // "trace". slog has no builtin trace level; the value is one step below
30 // slog.LevelDebug in slog's 4-point spacing.
31 const LevelTrace = slog.Level(-8)
32
33 // NewLogger returns a *slog.Logger whose level, format, and timestamp
34 // emission can be reconfigured at runtime via ApplyConfig and the SSH debug
35 // commands. The default configuration is info-level text output so log
36 // calls made before ApplyConfig runs still produce output. Timestamps
37 // follow slog's default RFC3339Nano format; set logging.disable_timestamp
38 // in config to suppress them.
39 //
40 // ApplyConfig and the SSH commands discover the reconfig surface via
41 // structural type-assertion on l.Handler(), so replacement implementations
42 // (tests, platform-specific sinks) need only implement the subset of
43 // {SetLevel(slog.Level), SetFormat(string) error, SetDisableTimestamp(bool)}
44 // they care about. Callers that pass a plain *slog.Logger without these
45 // methods get a silent no-op; reconfiguration is always opt-in.
46 func NewLogger(w io.Writer) *slog.Logger {
47 return slog.New(NewHandler(w))
48 }
49
50 // NewHandler builds the *Handler that NewLogger wraps. Exported for
51 // platform-specific sinks (notably cmd/nebula-service/logs_windows.go)
52 // that want to wrap the handler with extra behavior, such as tagging each
53 // record with its Event Log severity, while still benefiting from all the
54 // level / format / timestamp / WithAttrs machinery implemented here.
55 func NewHandler(w io.Writer) *Handler {
56 root := &handlerRoot{}
57 root.level.Set(slog.LevelInfo)
58 opts := &slog.HandlerOptions{Level: &root.level}
59 return &Handler{
60 root: root,
61 text: slog.NewTextHandler(w, opts),
62 json: slog.NewJSONHandler(w, opts),
63 }
64 }
65
66 // handlerRoot carries the reconfiguration state shared by every logger
67 // derived from a NewHandler call. All fields are consulted on the log
68 // path and updated lock-free.
69 type handlerRoot struct {
70 level slog.LevelVar
71 disableTimestamp atomic.Bool
72 // jsonMode picks which of the pre-derived inner handlers Handler.Handle
73 // dispatches to. Flipping it propagates instantly to every derived logger
74 // without rebuilding or chain-replaying anything.
75 jsonMode atomic.Bool
76 }
77
78 // Handler is the slog.Handler returned by NewHandler. It holds two
79 // pre-derived slog handlers -- one text, one json -- both built from the
80 // same accumulated WithAttrs/WithGroup state. Handle picks which one to
81 // dispatch to based on handlerRoot.jsonMode, so a SetFormat call takes
82 // effect immediately across the whole process without having to rebuild
83 // any derived loggers.
84 type Handler struct {
85 root *handlerRoot
86 text slog.Handler
87 json slog.Handler
88 }
89
90 func (h *Handler) Enabled(_ context.Context, l slog.Level) bool {
91 return h.root.level.Level() <= l
92 }
93
94 func (h *Handler) Handle(ctx context.Context, r slog.Record) error {
95 if h.root.disableTimestamp.Load() {
96 r.Time = time.Time{}
97 }
98 if h.root.jsonMode.Load() {
99 return h.json.Handle(ctx, r)
100 }
101 return h.text.Handle(ctx, r)
102 }
103
104 func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
105 if len(attrs) == 0 {
106 return h
107 }
108 return &Handler{
109 root: h.root,
110 text: h.text.WithAttrs(attrs),
111 json: h.json.WithAttrs(attrs),
112 }
113 }
114
115 func (h *Handler) WithGroup(name string) slog.Handler {
116 if name == "" {
117 return h
118 }
119 return &Handler{
120 root: h.root,
121 text: h.text.WithGroup(name),
122 json: h.json.WithGroup(name),
123 }
124 }
125
126 // SetLevel updates the effective log level. Propagates to every derived
127 // logger via the shared LevelVar.
128 func (h *Handler) SetLevel(level slog.Level) { h.root.level.Set(level) }
129
130 // GetLevel reports the current log level.
131 func (h *Handler) GetLevel() slog.Level { return h.root.level.Level() }
132
133 // SetFormat flips the output format atomically. Valid formats are "text"
134 // and "json". Every derived logger sees the new format on its next Handle
135 // call; no rebuild or registration is required.
136 func (h *Handler) SetFormat(format string) error {
137 switch format {
138 case "text":
139 h.root.jsonMode.Store(false)
140 case "json":
141 h.root.jsonMode.Store(true)
142 default:
143 return fmt.Errorf("unknown log format `%s`. possible formats: %s", format, []string{"text", "json"})
144 }
145 return nil
146 }
147
148 // GetFormat reports the currently selected format name.
149 func (h *Handler) GetFormat() string {
150 if h.root.jsonMode.Load() {
151 return "json"
152 }
153 return "text"
154 }
155
156 // SetDisableTimestamp toggles whether Handle zeroes r.Time before
157 // dispatching (slog's builtin text/json handlers skip emitting the time
158 // attribute on a zero time).
159 func (h *Handler) SetDisableTimestamp(v bool) { h.root.disableTimestamp.Store(v) }
160
161 // ApplyConfig reads logging.level, logging.format, and (optionally)
162 // logging.disable_timestamp from c and applies them to l. The reconfig
163 // surface is discovered via structural type-assertion on l.Handler(), so
164 // foreign handlers silently opt out of whichever capabilities they do not
165 // implement.
166 //
167 // nebula.Main does NOT call this function on your behalf; callers that want
168 // config-driven log level / format / timestamp updates invoke it at
169 // startup and register it as a reload callback themselves. This keeps the
170 // library from mutating an embedder's logger without their say-so.
171 func ApplyConfig(l *slog.Logger, c Config) error {
172 h := l.Handler()
173
174 lvl, err := ParseLevel(strings.ToLower(c.GetString("logging.level", "info")))
175 if err != nil {
176 return err
177 }
178 if ls, ok := h.(interface{ SetLevel(slog.Level) }); ok {
179 ls.SetLevel(lvl)
180 }
181
182 format := strings.ToLower(c.GetString("logging.format", "text"))
183 if fs, ok := h.(interface{ SetFormat(string) error }); ok {
184 if err := fs.SetFormat(format); err != nil {
185 return err
186 }
187 }
188
189 if ts, ok := h.(interface{ SetDisableTimestamp(bool) }); ok {
190 ts.SetDisableTimestamp(c.GetBool("logging.disable_timestamp", false))
191 }
192 return nil
193 }
194
195 // ParseLevel converts a config-string level name ("trace", "debug", "info",
196 // "warn"/"warning", "error", "fatal"/"panic") to a slog.Level. "fatal" and
197 // "panic" are accepted for backwards compatibility with pre-slog configs
198 // and both map to slog.LevelError.
199 func ParseLevel(s string) (slog.Level, error) {
200 switch s {
201 case "trace":
202 return LevelTrace, nil
203 case "debug":
204 return slog.LevelDebug, nil
205 case "info":
206 return slog.LevelInfo, nil
207 case "warn", "warning":
208 return slog.LevelWarn, nil
209 case "error":
210 return slog.LevelError, nil
211 case "fatal", "panic":
212 return slog.LevelError, nil
213 default:
214 return 0, fmt.Errorf("not a valid logging level: %q", s)
215 }
216 }
217
218 // LevelName returns a human-readable name for a slog.Level matching the
219 // strings accepted by ParseLevel.
220 func LevelName(l slog.Level) string {
221 switch {
222 case l <= LevelTrace:
223 return "trace"
224 case l <= slog.LevelDebug:
225 return "debug"
226 case l <= slog.LevelInfo:
227 return "info"
228 case l <= slog.LevelWarn:
229 return "warn"
230 default:
231 return "error"
232 }
233 }