Repository navigation
refactor(logging): migrate from logr/zap to stdlib slog for native trace correlation - #223
Merged
Merged
Conversation
…ace correlation logr's sink API is context-free, so a log line cannot see the active span — the reason #222's OTLP logs carry no trace correlation. Move the agent, registrar, CNI server and registry logging to stdlib log/slog, whose Handle(ctx, record) is context-aware: the otelslog bridge now populates trace_id/span_id natively on the OTLP LogRecord from the ctx passed to the *Context log methods. Foundation (common/log, common/manager): - common/log builds *slog.Logger over a fanout handler: stderr JSON (timestamp/ level/logger/caller/message parity with the old zap output) + an optional extra handler (otelslog), each gated by a shared level. Named() replaces WithName; V(n) collapses to slog Debug. - common/manager.SetupManagerLogging returns a *slog.Logger and wires the otelslog OTLP handler when --logs-enabled is set. controller-runtime is logr-only, so it rides logr.FromSlogHandler over the same handler — one output pipeline. - common/telemetry.SetupLogs is reused; only the bridge changes (otelzap -> otelslog). Components: every logr.Logger field/param becomes *slog.Logger. Calls use the ...Context(ctx, ...) variants wherever a ctx is in scope (handlers, traced funcs) so spanned operations carry trace_id; ctx-less sites (background goroutines, constructors) use the plain methods. logr.Error(err, msg, kv) -> slog Error(msg, "error", err, kv). Holdouts kept on logr (no spans, use the controller-runtime global logger): common/file and the cni-install binary (bridged to the same slog handler). The CNI plugin keeps its own separate zap logging stack. Drops the otelzap dependency added in #222. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_01Pihqn5RmVPhV9HTdBnqbvY
This was referenced Jun 18, 2026
bpalermo
added a commit
that referenced
this pull request
Sep 16, 2026
…40→15 MiB) via common/signals + slog (#772) (#777) * perf(cni-install,prober): drop controller-runtime for one signal handler (#772) `cni/cmd/cni-install/main.go` and `prober/cmd/prober/main.go` imported `sigs.k8s.io/controller-runtime` for a single call to `ctrl.SetupSignalHandler()`. That one import links the whole Kubernetes client stack — client-go, api, apimachinery, apiextensions-apiserver, kube-openapi, all 13 go-openapi/swag modules, prometheus/client_golang, json-iterator, fxamacker/cbor — into an init container that copies a file and writes a conflist, and into a black-box HTTP prober with no Kubernetes API access at all. The dependency-tree review measured 11.45 MiB of symbols attributed to `k8s.io/api` alone in cni-install, a package it never calls: it arrives through controller-runtime's root-package init. New `//common/signals` (zero external modules — that is the point of it) provides the same contract in ~30 lines of stdlib: - `NotifyContext(parent)` — first SIGINT/SIGTERM cancels the context, a second one `os.Exit(1)`s. That is exactly what controller-runtime's handler does, so operator-visible behaviour is unchanged. Unlike controller-runtime's it takes a parent context and may be called more than once per process. - `NotifyContextFunc(parent, onSecond)` — same, with the caller deciding what the second signal means. `agent/cmd/mesh-dns` had grown its own copy of this (a `signal.NotifyContext` plus a 15-line `awaitSecondSignal` goroutine) and now uses the shared helper. It is the caller that needs `NotifyContextFunc`: for mesh-DNS a second signal does not exit, it cuts the #729 lame-duck window short so the resolver closes its SO_REUSEPORT listeners in order instead of discarding the datagrams already queued to them. That behaviour is preserved exactly; the notification stays registered after cancellation (as `signal.NotifyContext` leaves it), so a third signal is swallowed by the full buffered channel rather than killing the process mid-drain. Measured, `bazel build` default config, `stat -Lc%s` and `go version -m | grep -c '^\tdep'` (hermetic SDK): cni-install 26,514,732 B (25.29 MiB) -> 5,698,860 B (5.43 MiB), -78.5% 65 modules -> 9 prober 42,346,572 B (40.38 MiB) -> 19,007,404 B (18.13 MiB), -55.1% 78 modules -> 41 `bazel query 'deps(//cni/cmd/cni-install:cni-install)'` now matches `controller_runtime` 0 times (was 170) and `client_go` 0 times (was 2232); its external `go_library` closure, minus the 66 nogo x/tools targets that appear on every target in this repo, is 31 — the size the review predicted for the work the binary actually does. The prober keeps 6 controller-runtime targets via `pkg/log/zap`, removed in the next commit. Verification: `bazel test //common/signals/... //cni/... //prober/... //agent/cmd/mesh-dns/...` (13 targets, all pass, including the three container structure tests); `bazel run //:gazelle` (regenerated the three BUILD.bazel dep lists, no further churn); `bazel run //:format.check`; `bazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation` over the same packages. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr * perf(prober): log through //common/log (slog) instead of controller-runtime zap (#772) `prober/internal/cmd/root.go` imported `sigs.k8s.io/controller-runtime/pkg/log/zap` for a single `zap.New()` producing the `logr.Logger` that `prober.New` took. It was the prober's SECOND path to controller-runtime — the first one went in the previous commit — and both had to go before either paid off: a black-box HTTP prober with no Kubernetes API access was linking the whole client stack for two log statements. It is also a leftover from the logr/zap -> slog migration (#223). `//common/log` has been the convention since, with zero external modules and 39 reverse deps. - `prober.New` takes `*slog.Logger` instead of `logr.Logger`. - `p.log.Error(err, "telemetry shutdown")` inverts to `p.log.Error("telemetry shutdown", "error", err)` — `"error"` is this repo's key for the error attribute (202 call sites, 0 using `"err"`), and it happens to be the key zap's logr adapter emitted too, so that JSON field is unchanged. - The four `logr.Discard()` in `prober_test.go` become `slog.New(slog.DiscardHandler)`. Log-key audit before changing the record shape, since the prober feeds the soak SLI. Checked the GitOps repo `bpalermo/k8s-talos-main` (Prometheus rules + rules_test, otel-collector values, VictoriaLogs config), `charts/prober`, `docs/`, `e2e/soak/` and the aether-soak skill. Result: NOTHING consumes prober log lines. Every prober consumer reads the metric `aether_probe_requests_total` and its `tier`/`target`/`result`/`node` labels (AetherProberHTTPErrorBurst, MeshDNSResolutionFailing and their unit tests), plus `aether_probe_request_duration_seconds`. Those are untouched by this commit. The only log-grep observable documented anywhere for the soak is an AGENT line (`e2e/soak/README.md`, the #682 dependency-set message), not a prober one. So the two messages ("prober starting", "telemetry shutdown"), their attribute keys (targets/rate/egress/error) and the "level"/"caller" JSON keys are all kept identical; only slog's "timestamp"/"message" replace zap's "ts"/"msg", which nothing reads. The level is unchanged too (zap.New() defaults to production/Info, as does log.NewLogger(false)); the prober has no --debug flag and gains none here. Measured (default config, `stat -Lc%s`, `go version -m | grep -c '^\tdep'`): prober after the previous commit 19,007,404 B (18.13 MiB), 41 modules after this one 15,906,508 B (15.17 MiB), 23 modules vs. main @ 3c8f9c7 42,346,572 B (40.38 MiB), 78 modules -> -62.4% `bazel query 'deps(//prober/cmd/prober:prober)'` now matches `controller_runtime` 0 times (was 174) and `client_go` 0 times (was 2232). Its external `go_library` closure, minus the 66 nogo x/tools targets present on every target in this repo, is 183 — the review's prediction was ~185. Verification: `bazel build //... //test/e2e:e2e_test`; `bazel test //... --test_output=errors` (99 targets, all pass, including the cni-install, prober and mesh-dns container structure tests and both charts/prober chart tests); `bazel run //:format.check`; `bazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation //...`; `bazel run //:gazelle` and `bazel mod tidy` both no-churn; `scripts/go-deps-audit.sh` exit 0 (go-logr/logr stays in the build list — the OTel SDK uses it). Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
logr's sink API is context-free, so a log line can't see the active span — the reason #222's OTLP logs carry no trace correlation. This migrates the agent, registrar, CNI server, and registry logging to stdliblog/slog, whoseHandle(ctx, record)is context-aware. Theotelslogbridge now populatestrace_id/span_idnatively on the OTLP LogRecord from the ctx passed to the*Contextlog methods.Foundation (
common/log,common/manager)common/logbuilds a*slog.Loggerover a fanout handler: stderr JSON (withtimestamp/level/logger/caller/messageparity with the old zap output) + an optional extra handler (otelslog), each gated by a shared level.Named()replacesWithName;V(n)collapses to slogDebug.common/manager.SetupManagerLoggingreturns a*slog.Loggerand wires the otelslog OTLP handler when--logs-enabledis set. controller-runtime is logr-only, so it rideslogr.FromSlogHandlerover the same handler — one output pipeline, format and OTLP export shared.common/telemetry.SetupLogsis reused as-is; only the bridge changes (otelzap → otelslog).Components
Every
logr.Loggerfield/param →*slog.Logger. Calls use the...Context(ctx, …)variants wherever actxis in scope (gRPC handlers, traced funcs) so spanned operations carrytrace_id; ctx-less sites (background goroutines, constructors) use the plain methods.logr.Error(err, msg, kv)→ slogError(msg, "error", err, kv).Holdouts (intentional)
Kept on logr — no request spans, and they use the controller-runtime global logger:
common/fileand the cni-install binary (bridged to the same slog handler for output). The CNI plugin keeps its own separate zap logging stack (distinct binary, no mesh spans).Drops the
otelzapdependency added in #222.Scope / mechanics
~94 files. The bulk was a scripted mechanical transform (
.V(n).Info→Debug,logr.Errorreshaping scoped to logger receivers to avoidstatus.Error/testify false positives,WithValues→With,WithName→Named,logr.Discard()→slog.New(slog.DiscardHandler)), then a context pass upgrading to...Contextwherectxexists, with the compiler reverting ctx-less sites. No behavior change beyond the logging API.Test
bazel build //...andbazel test //...green (41/41).--config=lintandmake format-checkclean.Post-merge: deploy to talos-main (logs enabled since #222) and confirm via the grafana MCP that spanned operations (registrar
RegisterEndpoint, CNI pod add, sync cycle) now carry a populatedtrace_idin VictoriaLogs, andkubectl logsshape is unchanged.🤖 Generated with Claude Code