diff --git a/Taskfile.yaml b/Taskfile.yaml index 0ec6fbb47..667459fad 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -231,8 +231,9 @@ tasks: # fail to build. # # Those fixtures and every kustomization under config/ and deploy/, - # except Components, are rendered and checked for a LOG_LEVEL, - # LOG_FORMAT, --log-level or --log-format that internal/logging rejects. + # except Components, are rendered and checked for a LOG_LEVEL or + # --log-level that internal/logging rejects, and for the removed + # LOG_FORMAT and --log-format or the local-only --zap-devel. # The containerlab overlays under deploy/containerlab/resources build # only once the lab scripts copy config/ onto a node, so they are not # rendered here; their source YAML, inline patches included, is checked @@ -250,11 +251,11 @@ tasks: echo "FAIL: $dir does not build"; status=1; continue fi if ! printf '%s\n' "$out" | {{.LOCALBIN}}/check-log-settings -label "$dir" -; then - echo "FAIL: $dir sets an unsupported log level or format"; status=1 + echo "FAIL: $dir sets an unsupported log setting"; status=1 fi done if ! find config deploy tests/manifests -name '*.yaml' -print0 | xargs -0 {{.LOCALBIN}}/check-log-settings; then - echo "FAIL: source YAML sets an unsupported log level or format"; status=1 + echo "FAIL: source YAML sets an unsupported log setting"; status=1 fi for dir in tests/manifests/invalid/*/; do if {{.KUSTOMIZE}} build "$dir" > /dev/null 2>&1; then diff --git a/cmd/fabric-api/gateway.go b/cmd/fabric-api/gateway.go index 683481a18..7709c0809 100644 --- a/cmd/fabric-api/gateway.go +++ b/cmd/fabric-api/gateway.go @@ -404,7 +404,7 @@ func runGateway(parent context.Context, o *gatewayOptions) error { // manager shuts down. defer context.AfterFunc(ctx, gs.Stop)() - slog.Info("starting fabric-api gateway", "version", metadata.Version, "site", o.site, "cluster", o.clusterName, + slog.Info("starting fabric-api gateway", "version", metadata.Version, "site", o.site, "clusterName", o.clusterName, "cell", o.cell, "debug", debugAddr) return mgr.Start(ctx) } diff --git a/cmd/fabric-api/node.go b/cmd/fabric-api/node.go index 92659c094..d51469e90 100644 --- a/cmd/fabric-api/node.go +++ b/cmd/fabric-api/node.go @@ -253,7 +253,7 @@ func runNode(parent context.Context, o *nodeOptions) error { stopMetrics := serveMetrics(metricsAddr, metrics.Handler()) defer stopMetrics() - slog.Info("starting fabric-api node", "version", metadata.Version, "node", o.nodeName, "site", o.site, + slog.Info("starting fabric-api node", "version", metadata.Version, "nodeName", o.nodeName, "site", o.site, "listen", addr, "metrics", metricsAddr, "probeSources", sources, "expensiveQueries", o.enableExpensive) errc := make(chan error, 1) go func() { errc <- gs.Serve(lis) }() diff --git a/cmd/fabric-config-agent/main.go b/cmd/fabric-config-agent/main.go index 3f8a603ea..098088aab 100644 --- a/cmd/fabric-config-agent/main.go +++ b/cmd/fabric-config-agent/main.go @@ -233,7 +233,7 @@ func run(parent context.Context, opts *options, fn func(*fabricconfig.Agent, con opts.restCfg = restCfg - slog.Info("starting "+appName, "version", metadata.Version, "node", opts.nodeName, "namespace", opts.namespace, + slog.Info("starting "+appName, "version", metadata.Version, "nodeName", opts.nodeName, "podNamespace", opts.namespace, "activation", opts.activation, "configMaps", opts.configMaps) return fn(agent, ctx) } diff --git a/cmd/galactic-edge/main.go b/cmd/galactic-edge/main.go index cc725c749..19563ff06 100644 --- a/cmd/galactic-edge/main.go +++ b/cmd/galactic-edge/main.go @@ -194,7 +194,7 @@ func run(parent context.Context, o *options) error { if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { return err } - slog.Info("starting galactic-edge", "node", o.nodeName, "owner", a.Owner, + slog.Info("starting galactic-edge", "nodeName", o.nodeName, "owner", a.Owner, "version", metadata.Version) return mgr.Start(ctx) } diff --git a/cmd/galactic-gateway/encapsource.go b/cmd/galactic-gateway/encapsource.go index 380ce9f4a..6e3e9b115 100644 --- a/cmd/galactic-gateway/encapsource.go +++ b/cmd/galactic-gateway/encapsource.go @@ -81,10 +81,10 @@ func resolveEncapSource(ctx context.Context, reader client.Reader, nodeName, con switch { case errors.As(err, &listRoutersError{}): slog.Warn("Listing BGPRouters to derive the edge gateway SRv6 encapsulation source failed; retrying", - "node", nodeName, "retryIn", delay, "error", err) + "nodeName", nodeName, "retryIn", delay, "error", err) case errors.As(err, &noRouterYetError{}): slog.Info("Waiting for this node's BGPRouter to derive the edge gateway SRv6 encapsulation source", - "node", nodeName, "retryIn", delay) + "nodeName", nodeName, "retryIn", delay) default: return "", err } diff --git a/deploy/containerlab/scripts/verify-fabric-api.sh b/deploy/containerlab/scripts/verify-fabric-api.sh index 1f9df1e1e..1224b0df4 100755 --- a/deploy/containerlab/scripts/verify-fabric-api.sh +++ b/deploy/containerlab/scripts/verify-fabric-api.sh @@ -83,7 +83,7 @@ node_targets() { echo "${node} $(awk -v n="${node}" '$1 == n {print $2}' <<<"${certs}") ${hostip} ${frpod}" done } -q() { "${FA}" --log-format text --log-level warn query --cell "${site}" --operator lab-verify \ +q() { "${FA}" --log-level warn query --cell "${site}" --operator lab-verify \ --tls-cert "${creds}/tls.crt" --tls-key "${creds}/tls.key" --tls-ca "${creds}/ca.crt" "$@"; } # wait_info prints a node's Info, retrying for up to 90s: right after a diff --git a/docs/controller/README.md b/docs/controller/README.md index 5b886e9b3..6a54a2cc8 100644 --- a/docs/controller/README.md +++ b/docs/controller/README.md @@ -27,7 +27,7 @@ CLI defaults below describe the binary. Deployment overlays may override them; f | `--health-probe-bind-address` | `:8081` | Health and readiness listener | | `--leader-elect` | `true` | Elect one reconciler; cell webhook replicas all serve admission | -Logging takes `--log-level` (`LOG_LEVEL`) and `--log-format` (`LOG_FORMAT`); see [Logging](../observability/logging.md). +Logging takes `--log-level` (`LOG_LEVEL`) and the standard `--zap-*` flags; see [Logging](../observability/logging.md). ## Cell flags diff --git a/docs/fabric-api/configuration.md b/docs/fabric-api/configuration.md index 7b4b27d97..1e9bbf637 100644 --- a/docs/fabric-api/configuration.md +++ b/docs/fabric-api/configuration.md @@ -32,14 +32,14 @@ syntax (`10m`). ### Global (all subcommands) -| Flag | Env | Default | Meaning | -| ----------------- | ------------ | ------- | -------------------------------------------- | -| `--log-level` | `LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error` | -| `--log-format` | `LOG_FORMAT` | `json` | `json` or `text` | -| `--version`, `-V` | | | Print the version and exit (root only) | -| `--build-info` | | | Print build information and exit (root only) | - -[Logging](../observability/logging.md) describes what these two flags cover. +| Flag | Env | Default | Meaning | +| ----------------- | ----------- | ------- | -------------------------------------------- | +| `--log-level` | `LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error` | +| `--zap-*` | | | Standard zap flags, such as `--zap-devel` | +| `--version`, `-V` | | | Print the version and exit (root only) | +| `--build-info` | | | Print build information and exit (root only) | + +[Logging](../observability/logging.md) describes what the logging flags cover. Tracing is enabled only when `OTEL_EXPORTER_OTLP_ENDPOINT` or `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is set; the standard OpenTelemetry exporter diff --git a/docs/gateway/configuration.md b/docs/gateway/configuration.md index fca2ec1f9..2db43b727 100644 --- a/docs/gateway/configuration.md +++ b/docs/gateway/configuration.md @@ -9,7 +9,7 @@ flags, or a combination of both (CLI flags take precedence), with the `GALACTIC_GATEWAY` env prefix — the same three-tier precedence pattern `galactic-router` uses (see [docs/router/configuration.md](../router/configuration.md)). -Logging takes `--log-level` (`LOG_LEVEL`) and `--log-format` (`LOG_FORMAT`), without the `GALACTIC_GATEWAY` prefix; see [Logging](../observability/logging.md). +Logging takes `--log-level` (`LOG_LEVEL`), without the `GALACTIC_GATEWAY` prefix and the standard `--zap-*` flags; see [Logging](../observability/logging.md). | Option | Environment Variable | CLI Flag | Default | Required | | ------------------- | -------------------------------------- | ------------------------------- | ----------- | ------------- | diff --git a/docs/nat/configuration.md b/docs/nat/configuration.md index 77654a550..4a4e12e85 100644 --- a/docs/nat/configuration.md +++ b/docs/nat/configuration.md @@ -10,7 +10,7 @@ flags, or a combination of both (CLI flags take precedence), with the `galactic-router` and `galactic-gateway` use (see [docs/router/configuration.md](../router/configuration.md)). -Logging takes `--log-level` (`LOG_LEVEL`) and `--log-format` (`LOG_FORMAT`), without the `GALACTIC_NAT` prefix; see [Logging](../observability/logging.md). +Logging takes `--log-level` (`LOG_LEVEL`), without the `GALACTIC_NAT` prefix and the standard `--zap-*` flags; see [Logging](../observability/logging.md). | Option | Environment Variable | CLI Flag | Default | Required | | ------------------ | -------------------------------- | ------------------------- | ------------- | -------- | diff --git a/docs/observability/logging.md b/docs/observability/logging.md index c204917fa..5bbfa1a60 100644 --- a/docs/observability/logging.md +++ b/docs/observability/logging.md @@ -4,31 +4,40 @@ Every long-running Galactic binary (`galactic-router`, `galactic-gateway`, `galactic-nat`, `galactic-vrf`, `galactic-controller`, `galactic-edge`, `galactic-cni`, `fabric-router-controller`, `fabric-api` and `fabric-config-agent`) installs one logger at startup through -`internal/logging`. The same handler writes the binary's own `slog` lines, the -standard `log` package, controller-runtime (reconciler errors, cache and leader -election) and klog (client-go), so every line has one format and one level -threshold. For `galactic-cni` that covers the `install-cni` init container and -the `credential-refresh` daemon; for `fabric-config-agent`, the `frr-init` init -container and the `config-agent` sidecar. - -| Flag | Env | Default | Meaning | -| -------------- | ------------ | ------- | ---------------------------------- | -| `--log-level` | `LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error` | -| `--log-format` | `LOG_FORMAT` | `json` | `json` or `text` | - -An explicit flag wins over the environment variable. `--log-level` also -accepts what Go's `slog` parses beyond the four names: any case, and an offset -such as `info+2`. +`internal/logging`, which builds it with the shared Milo instrumentation +library ([`go.miloapis.com/instrumentation/logging`](https://github.com/milo-os/instrumentation)). +The same logger writes the binary's own `slog` lines, the standard `log` +package, controller-runtime (reconciler errors, cache and leader election), +klog (client-go) and the embedded GoBGP server in `galactic-router`, so every +line has one format and one level threshold. For `galactic-cni` that covers +the `install-cni` init container and the `credential-refresh` daemon; for +`fabric-config-agent`, the `frr-init` init container and the `config-agent` +sidecar. + +| Flag | Env | Default | Meaning | +| ------------------------ | ----------- | ------- | ----------------------------------------------- | +| `--log-level` | `LOG_LEVEL` | `info` | `debug`, `info`, `warn` or `error` | +| `--zap-devel` | | off | Console output for local runs | +| `--zap-log-level` | | | zap's level; overrides `--log-level` when given | +| `--zap-encoder` | | `json` | `json` or `console` | +| `--zap-stacktrace-level` | | `error` | Lowest level that carries a stack trace | +| `--zap-time-encoding` | | RFC3339 | zap's time encoding | + +The `--zap-*` flags are controller-runtime's standard zap flags, the same in +every Milo service. An explicit `--log-level` wins over `LOG_LEVEL`. +`--log-level` also accepts what Go's `slog` parses beyond the four names: any +case, and an offset such as `info+2`. An unsupported value stops the binary at startup, before it does anything else, whether it comes from the flag or the environment variable. A DaemonSet with one crash-loops on every node. `task test:manifests`, which CI runs, renders every kustomization under `config/` and `deploy/` and fails on an -unsupported value for a container running one of these binaries. -`hack/check-log-settings` applies the same rules (`internal/logging`'s -`ValidateLevel` and `ValidateFormat`) to any YAML, so downstream manifests -should run it on their rendered output, with a Galactic release that includes -it: +unsupported level for a container running one of these binaries. It also fails +on `--zap-devel`, which is for local runs only, and on the removed +`--log-format` flag and `LOG_FORMAT` variable. `hack/check-log-settings` +applies the same rules (`internal/logging`'s `ValidateLevel`) to any YAML, so +downstream manifests should run it on their rendered output, with a Galactic +release that includes it: ```sh kustomize build | go run go.datum.net/galactic/hack/check-log-settings@ - @@ -37,31 +46,80 @@ kustomize build | go run go.datum.net/galactic/hack/check-log-settings It recognizes a Galactic container by its image repository name, or by a command that runs one of these binaries: `fabric-config-agent` ships in the `fabric-router` image, run directly by `config-agent` and from a shell script -by `frr-init`. It checks only literal values, not ones read from a ConfigMap or Secret. An empty -`LOG_LEVEL` or `LOG_FORMAT` counts as unset. In source YAML that isn't +by `frr-init`. It checks only literal values, not ones read from a ConfigMap or +Secret. An empty `LOG_LEVEL` counts as unset. In source YAML that isn't rendered, such as the containerlab overlays, it reads strategic-merge patches but not JSON 6902 patches. -Production runs the defaults: one JSON object per line on stderr, with -`time`, `level` and `msg` keys. controller-runtime's lines also carry a -`logger` key naming the component. Its verbose lines (`V(1)` and up) appear -only at `--log-level=debug`. klog keeps its own verbosity setting, which these -flags don't change, so client-go's `klog.V(n)` lines stay off. +## Output + +Production runs the defaults: one JSON object per line on stderr. Every line +has these keys: + +| Key | Value | +| ------------------------- | ------------------------------------------------------------ | +| `ts` | RFC 3339 timestamp in UTC, to the nanosecond | +| `level` | `debug`, `info`, `warn` or `error` | +| `msg` | The message | +| `build_version` | The binary's release tag, from `internal/metadata.Version` | +| `instrumentation_version` | The instrumentation library's version linked into the binary | + +Lines may also carry `logger` (the component, such as controller-runtime's +`controller-runtime.client.config` or `gobgp`), `caller` (file and line of a +`slog` call), `error`, and `stacktrace` on `error` lines. controller-runtime's +verbose lines (`V(1)` and up) and `slog.Debug` lines appear only at +`--log-level=debug`, with level `debug`. klog keeps its own verbosity setting, +which these flags don't change, so client-go's `klog.V(n)` lines stay off. + +Galactic's own log keys avoid the names the collection pipeline reserves for +its labels, such as `node`, `namespace`, `pod` and `service`. A Kubernetes +object a line is about is `resource_name` and `resource_namespace`; other +values use specific names such as `nodeName` or `podNamespace`. +controller-runtime's reconciler lines still carry its own `namespace` and +`name` keys. A binary that fails after reading its flags logs the error as one `error` -line through the same handler, then exits 1. A bad flag or an invalid -`--log-level` or `--log-format` fails before the handler exists, so that one -line is Go's default text. +line through the same logger, then exits 1. A bad flag or an invalid +`--log-level` fails before the logger exists, so that one line is Go's default +text. -For local runs, `--log-format=text --log-level=debug` gives readable output -with the verbose lines. No binary enables controller-runtime's zap development -mode: `internal/logging`'s `TestBinariesUseThisPackage` fails when a command -under `cmd/` imports controller-runtime's zap package or calls `SetLogger` -itself, and `TestLongRunningBinariesInstallTheHandler` fails when a command -under `cmd/` doesn't import `internal/logging` at all. +For local runs, `--zap-devel --log-level=debug` gives console output with the +verbose lines. No binary turns on development mode itself: +`internal/logging`'s `TestLoggerAdopted` runs the instrumentation library's +logger check over the whole module, which fails on any logger not built by the +library and on development mode turned on in source. +`TestBinariesUseThisPackage` fails when a command under `cmd/` imports +controller-runtime's zap package or calls `SetLogger` itself, and +`TestLongRunningBinariesInstallTheHandler` fails when a command under `cmd/` +doesn't import `internal/logging` at all. Two kinds of command are exempt. The CNI plugins (`galactic-veth`, `galactic-tap`, `galactic-ipam`, `galactic-bgp` and `galactic-route`) run once -per CNI call and write JSON to their own log file; see the +per CNI call and write the same JSON lines to their own log file, through +`internal/logging.SetupFile`; see the [CNI environment variables](../cni/environment-variables.md). `galactic-usid` is a one-shot codec command in the debug image. + +## Changes from the slog format + +Releases before the instrumentation library wrote lines with Go's `slog` JSON +handler. Queries that read log fields need these changes: + +| Before | Now | +| ---------------------------------------- | ------------------------------------------------------------------- | +| `time`, local time zone | `ts`, UTC | +| `level` `DEBUG`, `INFO`, `WARN`, `ERROR` | `level` `debug`, `info`, `warn`, `error` | +| controller-runtime `err` | `error` | +| controller-runtime `logger` with `/` | `logger` with `.`, such as `controller-runtime.webhook` | +| no version | `build_version` and `instrumentation_version` | +| no source location or stack trace | `caller` on `slog` lines, `stacktrace` on `error` lines | +| `node` | `nodeName` | +| `namespace` | `resource_namespace`, or `podNamespace` for a pod's | +| `name` beside `namespace` | `resource_name` | +| `pod` | `podRef` or `podName` | +| `service` | `serviceName`, `serviceUID`, or `caller` for a Looking Glass caller | +| `endpoint` | `serviceEndpoint` | +| `instance` | `instanceName` | +| `cluster` | `clusterName` | +| `--log-format`, `LOG_FORMAT` | removed; `--zap-devel` for local console output | +| GoBGP lines discarded | GoBGP lines at the binary's level, logger `gobgp` | diff --git a/docs/router/configuration.md b/docs/router/configuration.md index 00751db08..1cc5330f9 100644 --- a/docs/router/configuration.md +++ b/docs/router/configuration.md @@ -14,7 +14,7 @@ flag name — the mapping is defined in `internal/config` (see `RouterConfig` and the `EnvRouter*` constants). Always use the exact name from the table below. -Logging takes `--log-level` (`LOG_LEVEL`) and `--log-format` (`LOG_FORMAT`), without the `GALACTIC_ROUTER` prefix; see [Logging](../observability/logging.md). +Logging takes `--log-level` (`LOG_LEVEL`), without the `GALACTIC_ROUTER` prefix and the standard `--zap-*` flags; see [Logging](../observability/logging.md). | Option | Environment Variable | CLI Flag | Default | | ------------------------ | ------------------------------------------ | ---------------------------- | --------------------------- | diff --git a/go.mod b/go.mod index 08d152b8e..8ede94ea9 100644 --- a/go.mod +++ b/go.mod @@ -29,11 +29,13 @@ require ( github.com/yosida95/uritemplate/v3 v3.0.2 go.datum.net/compute v0.12.11 go.datum.net/network-services-operator v0.32.31 + go.miloapis.com/instrumentation v0.6.0 go.miloapis.com/ipam v0.5.1 go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 go.opentelemetry.io/otel v1.47.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.47.0 go.opentelemetry.io/otel/sdk v1.47.0 + go.uber.org/zap v1.28.0 golang.org/x/crypto/x509roots/fallback v0.0.0-20261020153306-9f2b28d4331a golang.org/x/net v0.61.0 golang.org/x/sys v0.49.0 @@ -70,6 +72,7 @@ require ( github.com/fxamacker/cbor/v2 v2.9.0 // indirect github.com/gaissmai/bart v0.26.1 // indirect github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-logr/zapr v1.3.0 // indirect github.com/go-openapi/jsonpointer v1.0.0 // indirect github.com/go-openapi/jsonreference v1.0.0 // indirect github.com/go-openapi/swag v0.28.0 // indirect @@ -117,6 +120,7 @@ require ( go.opentelemetry.io/otel/metric v1.47.0 // indirect go.opentelemetry.io/otel/trace v1.47.0 // indirect go.opentelemetry.io/proto/otlp v1.11.0 // indirect + go.uber.org/multierr v1.11.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/crypto v0.58.0 // indirect diff --git a/go.sum b/go.sum index 01762d528..f0a9e9e8b 100644 --- a/go.sum +++ b/go.sum @@ -221,6 +221,8 @@ go.datum.net/compute v0.12.11 h1:bd/kcJMmuAP0pdLGV4OfOMKNg7GnYHVJwwJErYazBmE= go.datum.net/compute v0.12.11/go.mod h1:OydYUbFT+r76BB02bmBOltJR2nLEy080qofvdqk1LFU= go.datum.net/network-services-operator v0.32.31 h1:OcUCPnAYj6ENiVyO4Wd24UeTvicJ/nSYkg2OQ5+quPk= go.datum.net/network-services-operator v0.32.31/go.mod h1:7LfOP7awc5FZ8zID7wZEN8rQ/7qxyO3u+WIoIIA44os= +go.miloapis.com/instrumentation v0.6.0 h1:ZFNYToZWX+XJoYrLZ/VLALmqO2F3+mOUcIFeRzitbTc= +go.miloapis.com/instrumentation v0.6.0/go.mod h1:2cwTwVrzdim2RIRr+NvWX3XiZN24lD0uV8Gr/BFbHiw= go.miloapis.com/ipam v0.5.1 h1:jb8jghj0jSOIDEPNo6b2gg2S4SWhNVfW4GDstb0zSKQ= go.miloapis.com/ipam v0.5.1/go.mod h1:Jj7xg4lJi9psE0+4PuOg/GQOG8rG13h112xYoM994rc= go.miloapis.com/locations v0.0.1 h1:voJKqBzyLX5x96M3+5y/ga7fgq9/+vypTizd+bBvqUY= diff --git a/hack/check-log-settings/main.go b/hack/check-log-settings/main.go index c71cf6d9b..8483f9334 100644 --- a/hack/check-log-settings/main.go +++ b/hack/check-log-settings/main.go @@ -3,8 +3,10 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // Command check-log-settings fails when a manifest gives a Galactic container -// a LOG_LEVEL, LOG_FORMAT, --log-level or --log-format value that -// internal/logging rejects, which would stop the binary at startup. +// a LOG_LEVEL or --log-level value that internal/logging rejects, or the +// removed --log-format flag, either of which would stop the binary at startup. +// It also fails on the removed LOG_FORMAT variable, which no binary reads, and +// on --zap-devel, the local-only console format. // // It reads YAML streams from the named files, or from stdin for "-": rendered // kustomize output, or source YAML such as a patch file or a kustomization @@ -196,6 +198,16 @@ func inlinePatches(doc any) []string { return patches } +// envFormat is the variable that chose JSON or text output before the +// binaries moved to the instrumentation library's logger. +const envFormat = "LOG_FORMAT" + +var ( + errFormatRemoved = errors.New( + "removed: production output is always JSON; use --zap-devel for console output in local runs") + errDevel = errors.New("console output at debug level is for local runs only") +) + func checkContainer(c map[string]any) []string { name, _ := c["name"].(string) image, _ := c["image"].(string) @@ -221,10 +233,8 @@ func checkContainer(c map[string]any) []string { if err := logging.ValidateLevel(value); err != nil { report(key, value, err) } - case logging.EnvFormat: - if err := logging.ValidateFormat(value); err != nil { - report(key, value, err) - } + case envFormat: + report(key, value, errFormatRemoved) } } for _, key := range []string{"command", "args"} { @@ -232,6 +242,12 @@ func checkContainer(c map[string]any) []string { for i, a := range list { arg, _ := a.(string) flagName, value, found := strings.Cut(arg, "=") + if flagName == "--"+logging.DevelFlag { + if value != "false" { + findings = append(findings, fmt.Sprintf("container %s: %s: %v", name, arg, errDevel)) + } + continue + } if flagName != "--log-level" && flagName != "--log-format" { continue } @@ -244,11 +260,11 @@ func checkContainer(c map[string]any) []string { if strings.Contains(value, "$(") { continue } - validate := logging.ValidateLevel if flagName == "--log-format" { - validate = logging.ValidateFormat + report(flagName, value, errFormatRemoved) + continue } - if err := validate(value); err != nil { + if err := logging.ValidateLevel(value); err != nil { report(flagName, value, err) } } diff --git a/hack/check-log-settings/main_test.go b/hack/check-log-settings/main_test.go index be52a3dca..b8aa36708 100644 --- a/hack/check-log-settings/main_test.go +++ b/hack/check-log-settings/main_test.go @@ -16,7 +16,7 @@ func TestCheck(t *testing.T) { want []string }{ { - name: "unsupported env level on a Galactic image", + name: "unsupported env level and the removed format variable on a Galactic image", yaml: ` apiVersion: apps/v1 kind: DaemonSet @@ -31,10 +31,13 @@ spec: - {name: LOG_LEVEL, value: verbose} - {name: LOG_FORMAT, value: json} `, - want: []string{`DaemonSet galactic-router: container router: LOG_LEVEL "verbose"`}, + want: []string{ + `DaemonSet galactic-router: container router: LOG_FORMAT "json": removed`, + `DaemonSet galactic-router: container router: LOG_LEVEL "verbose"`, + }, }, { - name: "unsupported env format", + name: "removed env format", yaml: ` kind: Deployment metadata: {name: c} @@ -71,10 +74,23 @@ spec: containers: - name: n image: galactic-nat - args: [--log-level=debug, --log-format=text] + args: [--log-level=debug, --zap-devel=false] env: [{name: LOG_LEVEL, value: WARN}] `, }, + { + name: "development mode", + yaml: ` +containers: + - name: nat + image: galactic-nat + args: [--zap-devel] + - name: router + image: galactic-router + args: [--zap-devel=true] +`, + want: []string{`container nat: --zap-devel: console output`, `container router: --zap-devel=true: console output`}, + }, { name: "other images keep their own log settings", yaml: ` diff --git a/hack/fabric-api-loadtest/main.go b/hack/fabric-api-loadtest/main.go index 298516996..671bc85ed 100644 --- a/hack/fabric-api-loadtest/main.go +++ b/hack/fabric-api-loadtest/main.go @@ -483,7 +483,7 @@ func startSidecar(work, bin, searchSource string) error { for _, s := range [][]string{ {"cp", bin, routerC + ":/fabric-api"}, {"cp", filepath.Join(work, "node"), routerC + ":/tls"}, - {dockerExec, "-d", routerC, "sh", "-c", "/fabric-api --log-format text node --node-name r0 --namespace " + namespace + + {dockerExec, "-d", routerC, "sh", "-c", "/fabric-api node --node-name r0 --namespace " + namespace + " --pod-name r0 --cell " + cell + " --host-ip " + routerV4 + " --frr-socket-dir /var/run/frr" + " --tls-cert /tls/tls.crt --tls-key /tls/tls.key --tls-ca /tls/ca.crt --probe-source-interface ''" + " --enable-expensive-queries --expensive-breaker-cooldown 5s --search-source " + searchSource + diff --git a/internal/cloud/webhook/pod_webhook.go b/internal/cloud/webhook/pod_webhook.go index 0e783da83..a578084b0 100644 --- a/internal/cloud/webhook/pod_webhook.go +++ b/internal/cloud/webhook/pod_webhook.go @@ -120,7 +120,7 @@ func (i *PodInterfaceInjector) Handle(ctx context.Context, req admission.Request return admission.Errored(http.StatusInternalServerError, err) } ctrl.LoggerFrom(ctx).Info("injected network interfaces into pod", - "instance", instanceName, "interfaces", injected, + "instanceName", instanceName, "interfaces", injected, "networks", pod.Annotations[MultusNetworksAnnotation], "defaultNetwork", pod.Annotations[MultusDefaultNetworkAnnotation]) return admission.PatchResponseFromRaw(req.Object.Raw, patched) diff --git a/internal/cni/ops_add.go b/internal/cni/ops_add.go index f5dc03cc9..d2e245a32 100644 --- a/internal/cni/ops_add.go +++ b/internal/cni/ops_add.go @@ -50,7 +50,7 @@ func cmdAdd(args *skel.CmdArgs) (err error) { slog.Info("ADD: starting", "containerID", args.ContainerID, "netns", args.Netns, "ifName", args.IfName, "vpc", pluginConf.VPC, "vpcAttachment", pluginConf.VPCAttachment, - "namespace", namespace, "nodeName", nodeName) + "resource_namespace", namespace, "nodeName", nodeName) // Definition check, before any kernel state is created: a conflist missing // the BGP plugin would otherwise attach successfully with no path to its diff --git a/internal/cnibgp/bgp.go b/internal/cnibgp/bgp.go index 11df0aa3d..f38ed20c7 100644 --- a/internal/cnibgp/bgp.go +++ b/internal/cnibgp/bgp.go @@ -429,7 +429,7 @@ func publishBGPState( if op == controllerutil.OperationResultCreated { result.vrfInstanceCreated = true } - slog.Debug("BGP: BGPVRFInstance applied", "name", vrfName, "namespace", namespace, + slog.Debug("BGP: BGPVRFInstance applied", "resource_name", vrfName, "resource_namespace", namespace, "vrfID", vrfID, "routeTarget", rtValue, "router", bgp.routerName, "operation", op) // A collision means allocateArgument's read-then-write raced another @@ -516,7 +516,7 @@ func publishBGPState( if advOp == controllerutil.OperationResultCreated { result.advertisementCreated = true } - slog.Debug("BGP: BGPAdvertisement applied", "name", adv.Name, "namespace", namespace, + slog.Debug("BGP: BGPAdvertisement applied", "resource_name", adv.Name, "resource_namespace", namespace, "prefixes", mergedPrefixes, "addedPrefixes", prefixes, "containerID", args.ContainerID, "operation", advOp) slog.Info("ADD: BGP state published", "containerID", args.ContainerID, diff --git a/internal/cnibgp/config.go b/internal/cnibgp/config.go index 323236fee..fb4c0e2da 100644 --- a/internal/cnibgp/config.go +++ b/internal/cnibgp/config.go @@ -19,6 +19,7 @@ import ( "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/hostconf" + "go.datum.net/galactic/internal/logging" ) var ConfFile = config.DefaultConfFile @@ -120,8 +121,7 @@ func setupLogging(logPath, logLevel string) { slog.Warn("Failed to open log file, falling back to Stderr", "path", logPath, "err", err) return } - handler := slog.NewJSONHandler(file, &slog.HandlerOptions{Level: level}) - slog.SetDefault(slog.New(handler)) + logging.SetupFile(file, level) } // statusConf holds the minimal CNI config fields needed for STATUS validation. diff --git a/internal/cnibgp/ops_add.go b/internal/cnibgp/ops_add.go index 421147f39..53e31456c 100644 --- a/internal/cnibgp/ops_add.go +++ b/internal/cnibgp/ops_add.go @@ -36,7 +36,7 @@ func cmdAdd(args *skel.CmdArgs) (err error) { slog.Info("ADD: starting", "containerID", args.ContainerID, "vpc", pluginConf.VPC, "vpcAttachment", pluginConf.VPCAttachment, - "ifaceType", ifaceType, "namespace", namespace, "nodeName", nodeName) + "ifaceType", ifaceType, "resource_namespace", namespace, "nodeName", nodeName) tracker := &resourceTracker{ vpc: pluginConf.VPC, diff --git a/internal/cnibgp/ops_del.go b/internal/cnibgp/ops_del.go index 6bfa83f26..1d87c6b59 100644 --- a/internal/cnibgp/ops_del.go +++ b/internal/cnibgp/ops_del.go @@ -77,13 +77,14 @@ func deleteEndpointSliceBestEffort(args *skel.CmdArgs) { deleted, err := podslice.Delete(ctx, k8sClient, podNamespace, podName, args.ContainerID) if err != nil { slog.Error("DEL: failed to delete EndpointSlice, cleanup deferred to GC", - "err", err, "containerID", args.ContainerID, "podName", podName, "namespace", podNamespace) + "err", err, "containerID", args.ContainerID, "podName", podName, "podNamespace", podNamespace) return } if !deleted { slog.Info("DEL: EndpointSlice absent or written by another sandbox, left in place", - "containerID", args.ContainerID, "podName", podName, "namespace", podNamespace) + "containerID", args.ContainerID, "podName", podName, "podNamespace", podNamespace) return } - slog.Info("DEL: EndpointSlice deleted", "containerID", args.ContainerID, "podName", podName, "namespace", podNamespace) + slog.Info("DEL: EndpointSlice deleted", + "containerID", args.ContainerID, "podName", podName, "podNamespace", podNamespace) } diff --git a/internal/cnibgp/resource.go b/internal/cnibgp/resource.go index 711643110..a660219f9 100644 --- a/internal/cnibgp/resource.go +++ b/internal/cnibgp/resource.go @@ -86,9 +86,9 @@ func (rt *resourceTracker) cleanup(ctx context.Context) { } if err := rt.k8s.Delete(ctx, adv); client.IgnoreNotFound(err) != nil { slog.Error("Rollback: failed to delete BGPAdvertisement", "err", err, - "name", adv.Name, "namespace", rt.namespace) + "resource_name", adv.Name, "resource_namespace", rt.namespace) } else { - slog.Debug("Rollback: deleted BGPAdvertisement", "name", adv.Name, "namespace", rt.namespace) + slog.Debug("Rollback: deleted BGPAdvertisement", "resource_name", adv.Name, "resource_namespace", rt.namespace) } } @@ -101,9 +101,10 @@ func (rt *resourceTracker) cleanup(ctx context.Context) { } if err := rt.k8s.Delete(ctx, vrfInst); client.IgnoreNotFound(err) != nil { slog.Error("Rollback: failed to delete freshly-created BGPVRFInstance", "err", err, - "name", vrfInst.Name, "namespace", rt.namespace) + "resource_name", vrfInst.Name, "resource_namespace", rt.namespace) } else { - slog.Debug("Rollback: deleted freshly-created BGPVRFInstance", "name", vrfInst.Name, "namespace", rt.namespace) + slog.Debug("Rollback: deleted freshly-created BGPVRFInstance", + "resource_name", vrfInst.Name, "resource_namespace", rt.namespace) } } } diff --git a/internal/cnimaster/config.go b/internal/cnimaster/config.go index 6f045926f..1bb9a7ba4 100644 --- a/internal/cnimaster/config.go +++ b/internal/cnimaster/config.go @@ -19,6 +19,7 @@ import ( "go.datum.net/galactic/internal/cniipam" "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/hostconf" + "go.datum.net/galactic/internal/logging" ) // PluginConf is the CNI plugin configuration passed on stdin to either master @@ -142,9 +143,7 @@ func SetupLogging(logPath, logLevel string) { slog.Warn("Failed to open log file, falling back to Stderr", "path", logPath, "err", err) return } - // Use JSON handler for structured logging to file. - handler := slog.NewJSONHandler(file, &slog.HandlerOptions{Level: level}) - slog.SetDefault(slog.New(handler)) + logging.SetupFile(file, level) } // statusConf holds the minimal config fields STATUS validation needs. STATUS diff --git a/internal/cniroute/config.go b/internal/cniroute/config.go index 994f0d686..2c9a4b173 100644 --- a/internal/cniroute/config.go +++ b/internal/cniroute/config.go @@ -19,6 +19,7 @@ import ( "go.datum.net/galactic/internal/config" "go.datum.net/galactic/internal/hostconf" + "go.datum.net/galactic/internal/logging" ) var ConfFile = config.DefaultConfFile @@ -117,8 +118,7 @@ func setupLogging(logPath, logLevel string) { slog.Warn("Failed to open log file, falling back to Stderr", "path", logPath, "err", err) return } - handler := slog.NewJSONHandler(file, &slog.HandlerOptions{Level: level}) - slog.SetDefault(slog.New(handler)) + logging.SetupFile(file, level) } // statusConf holds the minimal CNI config fields needed for STATUS validation. diff --git a/internal/cnitap/ops_add.go b/internal/cnitap/ops_add.go index 71c9d5372..1b34b45e2 100644 --- a/internal/cnitap/ops_add.go +++ b/internal/cnitap/ops_add.go @@ -54,7 +54,7 @@ func cmdAdd(args *skel.CmdArgs) (err error) { slog.Info("ADD: starting", "containerID", args.ContainerID, "netns", args.Netns, "ifName", args.IfName, "vpc", pluginConf.VPC, "vpcAttachment", pluginConf.VPCAttachment, - "namespace", namespace, "nodeName", nodeName) + "resource_namespace", namespace, "nodeName", nodeName) // Definition check, before any kernel state is created: a conflist missing // the BGP plugin would otherwise attach successfully with no path to its diff --git a/internal/controller/egressshard_controller.go b/internal/controller/egressshard_controller.go index 93a04090d..d63079d10 100644 --- a/internal/controller/egressshard_controller.go +++ b/internal/controller/egressshard_controller.go @@ -186,7 +186,7 @@ func (r *EgressShardReconciler) Reconcile(ctx context.Context, req ctrl.Request) } if err := r.syncNode(ctx); err != nil { - logger.Error(err, "sync egress translation datapath", "node", r.NodeName) + logger.Error(err, "sync egress translation datapath", "nodeName", r.NodeName) return ctrl.Result{}, err } return ctrl.Result{}, nil @@ -650,7 +650,7 @@ func (r *EgressShardReconciler) SetupWithManager(mgr ctrl.Manager) error { } if err := r.syncNode(ctx); err != nil { // Not fatal: the next EgressShard event syncs again. - log.FromContext(ctx).Error(err, "initial egress translation datapath sync", "node", r.NodeName) + log.FromContext(ctx).Error(err, "initial egress translation datapath sync", "nodeName", r.NodeName) } return nil })); err != nil { @@ -680,7 +680,7 @@ func (r *EgressShardReconciler) SetupWithManager(mgr ctrl.Manager) error { func (r *EgressShardReconciler) nodeShardRequests(ctx context.Context) []ctrlreconcile.Request { shardList := &bgpv1alpha1.EgressShardList{} if err := r.List(ctx, shardList); err != nil { - log.FromContext(ctx).Error(err, "list EgressShards for datapath coverage change", "node", r.NodeName) + log.FromContext(ctx).Error(err, "list EgressShards for datapath coverage change", "nodeName", r.NodeName) return nil } var reqs []ctrlreconcile.Request diff --git a/internal/controller/networkgateway_controller.go b/internal/controller/networkgateway_controller.go index 01564c2b5..6852519f6 100644 --- a/internal/controller/networkgateway_controller.go +++ b/internal/controller/networkgateway_controller.go @@ -335,10 +335,10 @@ func (r *NetworkGatewayReconciler) Reconcile(ctx context.Context, req ctrl.Reque // most likely already gone. withdrawErr := withdrawNodeAdvertisements(ctx, r.Client, req.Namespace, req.Name) if withdrawErr != nil { - logger.Error(withdrawErr, "withdraw BGPAdvertisements for departed gateway node", "node", req.Name) + logger.Error(withdrawErr, "withdraw BGPAdvertisements for departed gateway node", "nodeName", req.Name) } if clearErr := clearNodeRuleConditions(ctx, r.Client, req.Namespace, req.Name); clearErr != nil { - logger.Error(clearErr, "clear Programmed conditions for departed gateway node", "node", req.Name) + logger.Error(clearErr, "clear Programmed conditions for departed gateway node", "nodeName", req.Name) withdrawErr = errors.Join(withdrawErr, clearErr) } @@ -460,9 +460,9 @@ func (r *NetworkGatewayReconciler) Reconcile(ctx context.Context, req ctrl.Reque switch { case routerErr != nil: - logger.Error(routerErr, "skipping BGPAdvertisement wiring", "node", r.NodeName) + logger.Error(routerErr, "skipping BGPAdvertisement wiring", "nodeName", r.NodeName) case routerName == "": - logger.Info("no BGPRouter targets this node; skipping BGPAdvertisement wiring", "node", r.NodeName) + logger.Info("no BGPRouter targets this node; skipping BGPAdvertisement wiring", "nodeName", r.NodeName) } advErr, ruleStatusErr := r.publishRuleOutcomes(ctx, gw.Namespace, outcomes, status, routerName) diff --git a/internal/controller/networkservice_controller.go b/internal/controller/networkservice_controller.go index dc5a27eef..a7bda5b85 100644 --- a/internal/controller/networkservice_controller.go +++ b/internal/controller/networkservice_controller.go @@ -387,7 +387,7 @@ func (r *NetworkServiceReconciler) SetupWithManager(mgr ctrl.Manager) error { func namespaceRules(ctx context.Context, c client.Client, namespace string) []ctrlreconcile.Request { list := &bgpv1alpha1.NetworkServiceList{} if err := c.List(ctx, list, client.InNamespace(namespace)); err != nil { - log.FromContext(ctx).Error(err, "list NetworkServices for VPC change", "namespace", namespace) + log.FromContext(ctx).Error(err, "list NetworkServices for VPC change", "resource_namespace", namespace) return nil } reqs := make([]ctrlreconcile.Request, 0, len(list.Items)) diff --git a/internal/controller/node_controller.go b/internal/controller/node_controller.go index 590cbded8..e31a627c3 100644 --- a/internal/controller/node_controller.go +++ b/internal/controller/node_controller.go @@ -58,7 +58,7 @@ func nodeToRouterRequests(ctx context.Context, c client.Client, obj client.Objec if err := c.List(ctx, routerList, client.MatchingFields{BGPRouterByTargetName: node.Name}, ); err != nil { - logger.Error(err, "list BGPRouters for node change", "node", node.Name) + logger.Error(err, "list BGPRouters for node change", "nodeName", node.Name) return nil } diff --git a/internal/controller/serviceroute_controller.go b/internal/controller/serviceroute_controller.go index ecd0cfda1..aa63f51ce 100644 --- a/internal/controller/serviceroute_controller.go +++ b/internal/controller/serviceroute_controller.go @@ -110,7 +110,7 @@ func (r *ServiceRoutePolicyReconciler) Reconcile(ctx context.Context, req ctrl.R start := time.Now() resultLabel := "success" defer func() { r.Metrics.ObserveReconcile(resultLabel, time.Since(start)) }() - logger := log.FromContext(ctx).WithValues("policy", req.String(), "node", r.NodeName) + logger := log.FromContext(ctx).WithValues("policy", req.String(), "nodeName", r.NodeName) r.mu.Lock() defer r.mu.Unlock() @@ -161,7 +161,7 @@ func (r *ServiceRoutePolicyReconciler) Reconcile(ctx context.Context, req ctrl.R return ctrl.Result{}, joined } resultLabel = reconcileResultError - logger.Error(err, "get ServiceEndpoint", "endpoint", policy.Spec.ServiceRef.Name) + logger.Error(err, "get ServiceEndpoint", "serviceEndpoint", policy.Spec.ServiceRef.Name) return ctrl.Result{}, fmt.Errorf("get ServiceEndpoint %s/%s: %w", policy.Namespace, policy.Spec.ServiceRef.Name, err) } if endpoint.DeletionTimestamp != nil { @@ -220,7 +220,7 @@ func (r *ServiceRoutePolicyReconciler) Reconcile(ctx context.Context, req ctrl.R r.setAccepted(ctx, policy, metav1.ConditionTrue, "Accepted", "policy is valid"), ) resultLabel = reconcileResultError - logger.Error(joined, "resolve service routing dependency", "endpoint", endpoint.Name) + logger.Error(joined, "resolve service routing dependency", "serviceEndpoint", endpoint.Name) return ctrl.Result{}, joined } joined := errors.Join( @@ -229,7 +229,7 @@ func (r *ServiceRoutePolicyReconciler) Reconcile(ctx context.Context, req ctrl.R r.setAccepted(ctx, policy, metav1.ConditionFalse, "Invalid", err.Error()), ) resultLabel = reconcileResultError - logger.Error(joined, "compile service eBPF policy", "endpoint", endpoint.Name) + logger.Error(joined, "compile service eBPF policy", "serviceEndpoint", endpoint.Name) return ctrl.Result{}, joined } if len(intents) != 0 { @@ -239,14 +239,14 @@ func (r *ServiceRoutePolicyReconciler) Reconcile(ctx context.Context, req ctrl.R // is otherwise skipped by replacePolicy. if err := r.Programmer.Initialize(); err != nil { resultLabel = reconcileResultError - logger.Error(err, "refresh service route maps", "endpoint", endpoint.Name) + logger.Error(err, "refresh service route maps", "serviceEndpoint", endpoint.Name) return ctrl.Result{}, fmt.Errorf("refresh service route maps: %w", err) } } - logger.Info("compiled service eBPF policy", "endpoint", endpoint.Name, "attachments", len(intents)) + logger.Info("compiled service eBPF policy", "serviceEndpoint", endpoint.Name, "attachments", len(intents)) if err := r.replacePolicyLocked(req.NamespacedName, intents); err != nil { resultLabel = reconcileResultError - logger.Error(err, "program service eBPF policy", "endpoint", endpoint.Name) + logger.Error(err, "program service eBPF policy", "serviceEndpoint", endpoint.Name) return ctrl.Result{}, err } programmed = len(intents) != 0 && inputDigest != "" diff --git a/internal/edge/masque/adapter.go b/internal/edge/masque/adapter.go index b999db624..1d27a9fe5 100644 --- a/internal/edge/masque/adapter.go +++ b/internal/edge/masque/adapter.go @@ -199,7 +199,7 @@ func (a *Adapter) Start(ctx context.Context) error { } a.log.Info("adopted attachment", "attachment", att.Name) } - a.log.Info("instance registered", "instance", inst.Name) + a.log.Info("instance registered", "instanceName", inst.Name) return nil } diff --git a/internal/edge/masque/attachment.go b/internal/edge/masque/attachment.go index c694d89eb..6b0a679bc 100644 --- a/internal/edge/masque/attachment.go +++ b/internal/edge/masque/attachment.go @@ -138,7 +138,7 @@ func (a *Adapter) prepareOnce(ctx context.Context, e *attachment, g *Grant) (str } return "attachment not created: " + err.Error(), nil } - a.log.Info("attachment requested", "attachment", created.Name, "service", g.Service.Name) + a.log.Info("attachment requested", "attachment", created.Name, "serviceName", g.Service.Name) return "attachment requested", nil case err != nil: return "attachment not read: " + err.Error(), nil diff --git a/internal/edge/masque/session.go b/internal/edge/masque/session.go index 8a1510d79..d3b6d5184 100644 --- a/internal/edge/masque/session.go +++ b/internal/edge/masque/session.go @@ -97,7 +97,7 @@ func (a *Adapter) newSession(g *Grant, e *attachment, r *route, began uint64) (c s.setDeadline(g.NotAfter) go s.refreshLoop() a.log.Info("request admitted", "session", s.info.ID, "connector", g.Connector, "principal", g.Principal, - "service", g.Service.UID, "attachment", e.name, "attachmentUID", e.uid, "route", r.name, "claimEpoch", + "serviceUID", g.Service.UID, "attachment", e.name, "attachmentUID", e.uid, "route", r.name, "claimEpoch", r.epoch, "instanceEpoch", l.Epoch) return s, nil } diff --git a/internal/fabric/gateway/service.go b/internal/fabric/gateway/service.go index e53abb2d2..7cb569088 100644 --- a/internal/fabric/gateway/service.go +++ b/internal/fabric/gateway/service.go @@ -807,7 +807,7 @@ func (s *Service) finish(caller identity.ID, req *servicev1.RunDiagnosticRequest elapsed := s.now().Sub(rec.started) s.Metrics.serviceRequest(req, errcode.Code(reason)) if rec.inventory == nil { - slog.Debug("Looking Glass request refused", "service", caller.Name, "project", req.GetProjectId(), + slog.Debug("Looking Glass request refused", "caller", caller.Name, "project", req.GetProjectId(), "requestID", req.GetRequestId(), labelOperation, op, labelReason, reason) return } @@ -815,7 +815,7 @@ func (s *Service) finish(caller identity.ID, req *servicev1.RunDiagnosticRequest s.Metrics.serviceDuration.WithLabelValues(op).Observe(elapsed.Seconds()) } attrs := []any{ - "service", caller.Name, "project", req.GetProjectId(), "requestID", req.GetRequestId(), + "caller", caller.Name, "project", req.GetProjectId(), "requestID", req.GetRequestId(), labelOperation, op, labelReason, reason, "routers", len(rec.inventory.Routers), "selected", selectedCount(rec.inventory.Routers), "duration", elapsed, } diff --git a/internal/gc/gc.go b/internal/gc/gc.go index bd7c0db43..2937ebb8f 100644 --- a/internal/gc/gc.go +++ b/internal/gc/gc.go @@ -354,12 +354,12 @@ func RemoveOrphanedCRDs(ctx context.Context, k8s client.Client, orphans []Orphan } if err := k8s.Delete(ctx, adv); err != nil { slog.Error("GC: failed to delete orphaned BGPAdvertisement", - "name", o.Name, "namespace", o.Namespace, "err", err) + "resource_name", o.Name, "resource_namespace", o.Namespace, "err", err) result.Errors++ continue } slog.Info("GC: removed orphaned BGPAdvertisement", - "name", o.Name, "namespace", o.Namespace, "containerID", o.ContainerID) + "resource_name", o.Name, "resource_namespace", o.Namespace, "containerID", o.ContainerID) result.OrphanedCRDsRemoved++ case "BGPVRFInstance": @@ -380,17 +380,17 @@ func RemoveOrphanedCRDs(ctx context.Context, k8s client.Client, orphans []Orphan } if errors.Is(err, maintenance.ErrInUse) { slog.Info("GC: kept BGPVRFInstance an edge attachment uses", - "name", o.Name, "namespace", o.Namespace, "vpc", o.VPC) + "resource_name", o.Name, "resource_namespace", o.Namespace, "vpc", o.VPC) continue } if err != nil { slog.Error("GC: failed to delete orphaned BGPVRFInstance", - "name", o.Name, "namespace", o.Namespace, "err", err) + "resource_name", o.Name, "resource_namespace", o.Namespace, "err", err) result.Errors++ continue } slog.Info("GC: removed orphaned BGPVRFInstance", - "name", o.Name, "namespace", o.Namespace) + "resource_name", o.Name, "resource_namespace", o.Namespace) result.OrphanedCRDsRemoved++ } } diff --git a/internal/installer/endpointslice_repair.go b/internal/installer/endpointslice_repair.go index e62572493..6ad4dff27 100644 --- a/internal/installer/endpointslice_repair.go +++ b/internal/installer/endpointslice_repair.go @@ -121,7 +121,7 @@ func repairEndpointSlices( statuses, err := networkStatuses(pod) if err != nil { slog.Warn("EndpointSlice repair: skipping pod with an unreadable network-status annotation", - "pod", client.ObjectKeyFromObject(pod), "err", err) + "podRef", client.ObjectKeyFromObject(pod), "err", err) result.Skipped++ continue } @@ -144,7 +144,7 @@ func repairEndpointSlices( att, addr, err := lastGalacticIPv6Attachment(ctx, k8s, nads, statuses, defaultNamespace) if err != nil { slog.Warn("EndpointSlice repair: skipping pod whose attachment cannot be resolved", - "pod", client.ObjectKeyFromObject(pod), "err", err) + "podRef", client.ObjectKeyFromObject(pod), "err", err) result.Skipped++ continue } @@ -155,14 +155,14 @@ func repairEndpointSlices( node, err := identities.get(ctx, k8s, att.namespace, nodeName) if err != nil { slog.Warn("EndpointSlice repair: skipping pod with no SRv6 identity to publish", - "pod", client.ObjectKeyFromObject(pod), "err", err) + "podRef", client.ObjectKeyFromObject(pod), "err", err) result.Skipped++ continue } sid, err := attachmentSID(ctx, k8s, node, att, nodeName) if err != nil { slog.Warn("EndpointSlice repair: skipping pod whose SRv6 SID cannot be computed", - "pod", client.ObjectKeyFromObject(pod), "err", err) + "podRef", client.ObjectKeyFromObject(pod), "err", err) result.Skipped++ continue } @@ -176,7 +176,7 @@ func repairEndpointSlices( } if created { slog.Info("EndpointSlice repair: recreated missing EndpointSlice", - "pod", client.ObjectKeyFromObject(pod), "vpc", att.vpc, "vpcAttachment", att.vpcAttachment) + "podRef", client.ObjectKeyFromObject(pod), "vpc", att.vpc, "vpcAttachment", att.vpcAttachment) result.Restored++ } } diff --git a/internal/installer/installer.go b/internal/installer/installer.go index 000b1d594..c7dbb8348 100644 --- a/internal/installer/installer.go +++ b/internal/installer/installer.go @@ -661,7 +661,7 @@ func startHashedEgress(ctx context.Context, g *egressGroup, namespace string) { } go g.watchShardReachability(ctx) slog.Info("Hashed egress mode: spreading tenant egress across the cluster's EgressShards", - "namespace", namespace, "hash", g.cfg.Hash, "pinIdle", g.cfg.PinIdle) + "resource_namespace", namespace, "hash", g.cfg.Hash, "pinIdle", g.cfg.PinIdle) } // loadEgressShardSIDs parses the host conflist's egress shard list for the diff --git a/internal/logging/logging.go b/internal/logging/logging.go index 3b22eb220..ac7f0738c 100644 --- a/internal/logging/logging.go +++ b/internal/logging/logging.go @@ -2,108 +2,168 @@ // // SPDX-License-Identifier: AGPL-3.0-or-later -// Package logging installs one process-wide logger for a Galactic binary. The -// same slog handler backs slog's default logger, the standard log package, -// controller-runtime's logger and klog, so every line a binary writes has one -// format and one level threshold. Production output is JSON at info level; -// readable debug output for local runs is the explicit opt-in -// --log-format=text --log-level=debug. +// Package logging installs one process-wide logger for a Galactic binary, +// built by go.miloapis.com/instrumentation/logging. The same logger backs +// slog's default logger, the standard log package, controller-runtime's logger +// and klog, so every line a binary writes has one format and one level +// threshold. Production output is JSON at info level, with UTC timestamps and +// the binary's and the library's versions on every line. Console output for +// local runs is the explicit opt-in --zap-devel. package logging import ( + "context" + goflag "flag" "fmt" "io" "log/slog" "os" - "slices" "github.com/go-logr/logr" "github.com/spf13/pflag" + "go.miloapis.com/instrumentation/buildinfo" + "go.miloapis.com/instrumentation/logging" + uberzap "go.uber.org/zap" + "go.uber.org/zap/zapcore" "k8s.io/klog/v2" - ctrl "sigs.k8s.io/controller-runtime" + crlog "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + + "go.datum.net/galactic/internal/metadata" ) const ( - // FormatJSON is the production format and the default. - FormatJSON = "json" - // FormatText is the human-readable format for local runs. - FormatText = "text" - - // EnvLevel and EnvFormat supply the flags' defaults. - EnvLevel = "LOG_LEVEL" - EnvFormat = "LOG_FORMAT" -) + // EnvLevel supplies --log-level's default. + EnvLevel = "LOG_LEVEL" -var ( - // Levels are the documented --log-level values. ValidateLevel also - // accepts what slog parses beyond them: any case, and an offset such as - // info+2. - Levels = []string{"debug", "info", "warn", "error"} - // Formats are the accepted --log-format values. - Formats = []string{FormatJSON, FormatText} - // Binaries are the commands under cmd/ that call Setup. A manifest check - // uses this list to find the containers whose LOG_LEVEL, LOG_FORMAT, - // --log-level and --log-format these rules govern: by image name, as most - // publish an image of their own, or by command, as fabric-config-agent - // ships in the fabric-router image. - Binaries = []string{ - "fabric-api", - "fabric-config-agent", - "fabric-router-controller", - "galactic-cni", - "galactic-controller", - "galactic-edge", - "galactic-gateway", - "galactic-nat", - "galactic-router", - "galactic-vrf", - } + // DevelFlag is the standard opt-in for console output at debug level. + DevelFlag = "zap-devel" ) -// Options holds the --log-level and --log-format flag values. +// Levels are the documented --log-level values. ValidateLevel also accepts +// what slog parses beyond them: any case, and an offset such as info+2. +var Levels = []string{"debug", "info", "warn", "error"} + +// Binaries are the commands under cmd/ that call Setup. A manifest check uses +// this list to find the containers whose LOG_LEVEL, --log-level and +// --zap-devel these rules govern: by image name, as most publish an image of +// their own, or by command, as fabric-config-agent ships in the fabric-router +// image. +var Binaries = []string{ + "fabric-api", + "fabric-config-agent", + "fabric-router-controller", + "galactic-cni", + "galactic-controller", + "galactic-edge", + "galactic-gateway", + "galactic-nat", + "galactic-router", + "galactic-vrf", +} + +// Options holds the --log-level value and controller-runtime's standard zap +// flags. type Options struct { - Level string - Format string + Level string + zap zap.Options } -// BindFlags adds --log-level and --log-format to fs, defaulting from -// LOG_LEVEL and LOG_FORMAT, then info and json. +// BindFlags adds --log-level, defaulting from LOG_LEVEL then info, and the +// standard zap flags (--zap-devel, --zap-encoder, --zap-log-level, +// --zap-stacktrace-level and --zap-time-encoding) to fs. An explicit +// --zap-log-level takes precedence over --log-level. func (o *Options) BindFlags(fs *pflag.FlagSet) { fs.StringVar(&o.Level, "log-level", envOr(EnvLevel, "info"), "Log level: debug, info, warn, error (env "+EnvLevel+")") - fs.StringVar(&o.Format, "log-format", envOr(EnvFormat, FormatJSON), - "Log format: json or text (env "+EnvFormat+")") + zfs := goflag.NewFlagSet("zap", goflag.ContinueOnError) + o.zap.BindFlags(zfs) + fs.AddGoFlagSet(zfs) } // Setup installs the logger o describes, writing to stderr. func (o *Options) Setup() error { - return Setup(os.Stderr, o.Level, o.Format) -} - -// Setup builds one slog handler writing to w and installs it as slog's -// default, which also routes the standard log package through it, and as -// controller-runtime's and klog's logger. controller-runtime's V(n) lines map -// to slog level -n, so they appear only at --log-level=debug or below. -// controller-runtime keeps the logger from its first SetLogger call, so a -// binary calls Setup once, before it builds a manager. -func Setup(w io.Writer, level, format string) error { - l, err := parseLevel(level) - if err != nil { - return err + return o.setup(os.Stderr) +} + +func (o *Options) setup(w io.Writer) error { + opts := o.zap + opts.DestWriter = w + if opts.Level == nil { + l, err := parseLevel(o.Level) + if err != nil { + return err + } + opts.Level = l } - if err := ValidateFormat(format); err != nil { - return err + install(&opts) + return nil +} + +// SetupFile installs the production logger at level, writing to w. The CNI +// plugins use it to log to their own file. +func SetupFile(w io.Writer, level slog.Level) { + install(&zap.Options{DestWriter: w, Level: zapLevel(level)}) +} + +// install sets the binary's version, builds the library's logger from opts +// and installs it as controller-runtime's and klog's logger and, through a +// slog bridge, as slog's default, which also routes the standard log package +// through it. controller-runtime keeps the logger from its first SetLogger +// call, so a binary installs it once, before it builds a manager. +func install(opts *zap.Options) { + buildinfo.SetVersion(metadata.Version) + opts.EncoderConfigOptions = append(opts.EncoderConfigOptions, verboseAsDebug) + logger := logging.New(opts) + crlog.SetLogger(logger) + klog.SetLogger(logger) + slog.SetDefault(slog.New(logr.ToSlogHandler(logr.New(wrap(logger.GetSink()))))) +} + +// slogSink passes slog's warn lines to zap whatever the threshold. logr has +// no warn level, so its slog bridge asks whether V(0) is enabled before it +// hands over a warn line, and at --log-level=warn it isn't. zap checks the +// level of every line the bridge hands over, so it still drops info lines. +type slogSink struct { + logr.LogSink + slog logr.SlogSink +} + +func wrap(sink logr.LogSink) logr.LogSink { + if ss, ok := sink.(logr.SlogSink); ok { + return slogSink{sink, ss} } - opts := &slog.HandlerOptions{Level: l} - var h slog.Handler = slog.NewJSONHandler(w, opts) - if format == FormatText { - h = slog.NewTextHandler(w, opts) + return sink +} + +// Init does nothing: the wrapped sink was initialized when the library built +// it, and initializing it again would add a second caller skip. +func (slogSink) Init(logr.RuntimeInfo) {} + +func (s slogSink) Enabled(level int) bool { + return level == 0 || s.LogSink.Enabled(level) +} + +func (s slogSink) WithValues(kv ...any) logr.LogSink { return wrap(s.LogSink.WithValues(kv...)) } +func (s slogSink) WithName(name string) logr.LogSink { return wrap(s.LogSink.WithName(name)) } + +func (s slogSink) Handle(ctx context.Context, r slog.Record) error { return s.slog.Handle(ctx, r) } + +func (s slogSink) WithAttrs(attrs []slog.Attr) logr.SlogSink { + return wrap(s.slog.WithAttrs(attrs).(logr.LogSink)).(logr.SlogSink) +} + +func (s slogSink) WithGroup(name string) logr.SlogSink { + return wrap(s.slog.WithGroup(name).(logr.LogSink)).(logr.SlogSink) +} + +// verboseAsDebug names every level below zap's debug level, which slog.Debug +// and controller-runtime's V(2) and up produce, debug instead of Level(-n). +func verboseAsDebug(c *zapcore.EncoderConfig) { + encode := c.EncodeLevel + c.EncodeLevel = func(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { + encode(max(l, zapcore.DebugLevel), enc) } - logger := slog.New(h) - slog.SetDefault(logger) - ctrl.SetLogger(logr.FromSlogHandler(h)) - klog.SetSlogLogger(logger) - return nil } // ValidateLevel returns the error Setup returns for level, or nil if Setup @@ -113,21 +173,25 @@ func ValidateLevel(level string) error { return err } -// ValidateFormat returns the error Setup returns for format, or nil if Setup -// accepts it. -func ValidateFormat(format string) error { - if !slices.Contains(Formats, format) { - return fmt.Errorf("--log-format must be %s or %s, not %q", FormatJSON, FormatText, format) +// parseLevel maps a --log-level value to the zap level that keeps its +// meaning. +func parseLevel(level string) (uberzap.AtomicLevel, error) { + var l slog.Level + if err := l.UnmarshalText([]byte(level)); err != nil { + return uberzap.AtomicLevel{}, fmt.Errorf("--log-level: %w", err) } - return nil + return zapLevel(l), nil } -func parseLevel(level string) (slog.Level, error) { - var l slog.Level - if err := l.UnmarshalText([]byte(level)); err != nil { - return 0, fmt.Errorf("--log-level: %w", err) +// zapLevel maps a slog level to the zap threshold that admits the same +// lines. Through the bridge, slog's info, warn and error become zap's info, +// warn and error, while a level below info passes through unchanged: +// slog.Debug arrives as zap level -4, and controller-runtime's V(n) as -n. +func zapLevel(l slog.Level) uberzap.AtomicLevel { + if l < slog.LevelInfo { + return uberzap.NewAtomicLevelAt(zapcore.Level(l)) } - return l, nil + return uberzap.NewAtomicLevelAt(zapcore.Level(l / 4)) } func envOr(key, def string) string { diff --git a/internal/logging/logging_test.go b/internal/logging/logging_test.go index 80e37dede..2b9bf271f 100644 --- a/internal/logging/logging_test.go +++ b/internal/logging/logging_test.go @@ -23,32 +23,39 @@ import ( "strconv" "strings" "testing" + "time" - "github.com/go-logr/logr" + "github.com/spf13/pflag" + "go.miloapis.com/instrumentation/instrumenttest" "k8s.io/klog/v2" ctrl "sigs.k8s.io/controller-runtime" + + "go.datum.net/galactic/internal/metadata" ) -// emitEnv makes the test binary run emitLines instead of its tests. -// controller-runtime keeps the first logger it is given, so the lines are -// written by a fresh process each time, whatever -count or -shuffle says. +// emitEnv makes the test binary run emitLines at the level it names instead +// of its tests. controller-runtime keeps the first logger it is given, so the +// lines are written by a fresh process each time, whatever -count or -shuffle +// says. const emitEnv = "GALACTIC_LOGGING_TEST_EMIT" func TestMain(m *testing.M) { - if os.Getenv(emitEnv) != "" { - emitLines() + if level := os.Getenv(emitEnv); level != "" { + emitLines(level) return } os.Exit(m.Run()) } -// emitLines installs the production logger on stdout and writes one line -// through each logger Setup covers. -func emitLines() { - if err := Setup(os.Stdout, "info", FormatJSON); err != nil { +// emitLines installs the logger at level on stdout and writes lines through +// each logger Setup covers. +func emitLines(level string) { + o := Options{Level: level} + if err := o.setup(os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } + slog.Debug("slog debug") slog.Info("from slog", "k", "v") ctrl.Log.WithName("controller-runtime").Info("from controller-runtime", "k", "v") ctrl.Log.V(1).Info("controller-runtime debug") @@ -58,90 +65,178 @@ func emitLines() { klog.Flush() } -func TestSetupRoutesEveryLoggerThroughOneJSONHandler(t *testing.T) { +// emitted runs emitLines at level in a fresh process and returns its lines, +// each parsed as JSON. +func emitted(t *testing.T, level string) []map[string]any { + t.Helper() cmd := exec.CommandContext(t.Context(), os.Args[0]) - cmd.Env = append(os.Environ(), emitEnv+"=1") + cmd.Env = append(os.Environ(), emitEnv+"="+level) out, err := cmd.Output() if err != nil { t.Fatalf("emitting process: %v", err) } - buf := bytes.NewBuffer(out) - - lines := strings.Split(strings.TrimSpace(buf.String()), "\n") - info, errLevel := slog.LevelInfo.String(), slog.LevelError.String() - want := []struct{ msg, level string }{ - {"from slog", info}, - {"from controller-runtime", info}, - {"from controller-runtime error", errLevel}, - {"from the log package", info}, - {"from klog", info}, - } - if len(lines) != len(want) { - t.Fatalf("got %d lines, want %d (V(1) must be dropped at info):\n%s", len(lines), len(want), buf.String()) - } - for i, line := range lines { + split := strings.Split(strings.TrimSpace(string(out)), "\n") + recs := make([]map[string]any, 0, len(split)) + for i, line := range split { var rec map[string]any if err := json.Unmarshal([]byte(line), &rec); err != nil { t.Fatalf("line %d is not JSON: %v\n%s", i, err, line) } - for _, key := range []string{slog.TimeKey, slog.LevelKey, slog.MessageKey} { - if _, ok := rec[key]; !ok { - t.Errorf("line %d has no %q field: %s", i, key, line) - } + recs = append(recs, rec) + } + return recs +} + +// The level names a line carries, which are also the --log-level values. +const ( + lvDebug = "debug" + lvInfo = "info" + lvWarn = "warn" + lvError = "error" +) + +type line struct{ msg, level string } + +func lines(recs []map[string]any) []line { + out := make([]line, 0, len(recs)) + for _, rec := range recs { + msg, _ := rec["msg"].(string) + level, _ := rec["level"].(string) + out = append(out, line{msg, level}) + } + return out +} + +func TestSetupRoutesEveryLoggerThroughTheLibrary(t *testing.T) { + recs := emitted(t, lvInfo) + + want := []line{ + {"from slog", lvInfo}, + {"from controller-runtime", lvInfo}, + {"from controller-runtime error", lvError}, + {"from the log package", lvInfo}, + {"from klog", lvInfo}, + } + if got := lines(recs); !slices.Equal(got, want) { + t.Fatalf("lines = %v, want %v (debug lines must be dropped at info)", got, want) + } + for i, rec := range recs { + if rec["build_version"] != metadata.Version { + t.Errorf("line %d build_version = %v, want %q", i, rec["build_version"], metadata.Version) } - if rec[slog.MessageKey] != want[i].msg || rec[slog.LevelKey] != want[i].level { - t.Errorf("line %d = %s %q, want %s %q", i, rec[slog.LevelKey], rec[slog.MessageKey], want[i].level, want[i].msg) + if v, _ := rec["instrumentation_version"].(string); v == "" { + t.Errorf("line %d has no instrumentation_version", i) } + ts, _ := rec["ts"].(string) + if _, err := time.Parse(time.RFC3339Nano, ts); err != nil || !strings.HasSuffix(ts, "Z") { + t.Errorf("line %d ts = %q, want an RFC 3339 UTC timestamp", i, ts) + } + } + if _, ok := recs[2]["stacktrace"]; !ok { + t.Error("error line has no stacktrace") + } +} + +func TestSetupDebugShowsVerboseLinesAsDebug(t *testing.T) { + want := []line{ + {"slog debug", lvDebug}, + {"from slog", lvInfo}, + {"from controller-runtime", lvInfo}, + {"controller-runtime debug", lvDebug}, + {"from controller-runtime error", lvError}, + {"from the log package", lvInfo}, + {"from klog", lvInfo}, + } + if got := lines(emitted(t, lvDebug)); !slices.Equal(got, want) { + t.Errorf("lines = %v, want %v", got, want) } } -func TestSetupDebugTextShowsVerboseLines(t *testing.T) { +func TestSetupLevels(t *testing.T) { + for _, tc := range []struct { + args []string + want []string + }{ + {nil, []string{lvInfo, lvWarn, lvError}}, + {[]string{"--log-level=warn"}, []string{lvWarn, lvError}}, + {[]string{"--log-level=ERROR"}, []string{lvError}}, + {[]string{"--log-level=debug", "--zap-log-level=error"}, []string{lvError}}, + } { + t.Run(strings.Join(tc.args, " "), func(t *testing.T) { + t.Cleanup(restoreDefaults(t)) + t.Setenv(EnvLevel, "") + var o Options + fs := pflag.NewFlagSet("test", pflag.ContinueOnError) + o.BindFlags(fs) + if err := fs.Parse(tc.args); err != nil { + t.Fatal(err) + } + var buf bytes.Buffer + if err := o.setup(&buf); err != nil { + t.Fatal(err) + } + slog.Debug(lvDebug) + slog.Info(lvInfo) + slog.Warn(lvWarn) + slog.Error(lvError) + + split := strings.Split(strings.TrimSpace(buf.String()), "\n") + got := make([]string, 0, len(split)) + for _, l := range split { + var rec map[string]any + if err := json.Unmarshal([]byte(l), &rec); err != nil { + t.Fatalf("line is not JSON: %v\n%s", err, l) + } + got = append(got, rec["msg"].(string)) + } + if !slices.Equal(got, tc.want) { + t.Errorf("lines = %v, want %v", got, tc.want) + } + }) + } +} + +func TestSetupFileWritesJSON(t *testing.T) { t.Cleanup(restoreDefaults(t)) var buf bytes.Buffer - if err := Setup(&buf, "debug", FormatText); err != nil { - t.Fatal(err) - } + SetupFile(&buf, slog.LevelWarn) + slog.Info("dropped") + slog.Warn("kept", "k", "v") - // controller-runtime keeps the first logger it is given, so this checks - // the installed handler through the same slog-to-logr bridge. - logr.FromSlogHandler(slog.Default().Handler()).V(1).Info("controller-runtime debug") - if got := buf.String(); !strings.Contains(got, `msg="controller-runtime debug"`) { - t.Errorf("debug text output missing the V(1) line: %q", got) + var rec map[string]any + if err := json.Unmarshal(buf.Bytes(), &rec); err != nil { + t.Fatalf("output is not one JSON line: %v\n%s", err, buf.String()) + } + if rec["msg"] != "kept" || rec["level"] != lvWarn || rec["build_version"] != metadata.Version { + t.Errorf("line = %v, want kept at warn with build_version %q", rec, metadata.Version) } } -func TestSetupRejectsInvalidOptions(t *testing.T) { - for _, tc := range []struct{ level, format string }{ - {"loud", FormatJSON}, - {"info", "console"}, - } { - if err := Setup(&bytes.Buffer{}, tc.level, tc.format); err == nil { - t.Errorf("Setup(%q, %q) succeeded, want an error", tc.level, tc.format) - } +func TestSetupRejectsInvalidLevel(t *testing.T) { + o := Options{Level: "loud"} + if err := o.setup(&bytes.Buffer{}); err == nil { + t.Error("setup with --log-level=loud succeeded, want an error") } } -func TestValidateMatchesSetup(t *testing.T) { +func TestValidateLevel(t *testing.T) { for _, level := range append(slices.Clone(Levels), "INFO", "info+2") { if err := ValidateLevel(level); err != nil { t.Errorf("ValidateLevel(%q) = %v, want nil", level, err) } } - for _, format := range Formats { - if err := ValidateFormat(format); err != nil { - t.Errorf("ValidateFormat(%q) = %v, want nil", format, err) - } - } for _, level := range []string{"loud", "verbose", "", "trace"} { if ValidateLevel(level) == nil { t.Errorf("ValidateLevel(%q) = nil, want an error", level) } } - for _, format := range []string{"console", "JSON", ""} { - if ValidateFormat(format) == nil { - t.Errorf("ValidateFormat(%q) = nil, want an error", format) - } - } +} + +// TestLoggerAdopted runs the instrumentation library's logger check over the +// whole module: every logger is built by its logging package, and nothing +// turns on development mode. +func TestLoggerAdopted(t *testing.T) { + instrumenttest.AssertStandardLogger(t) } // TestBinariesListsEveryCaller keeps Binaries, which the manifest check uses @@ -260,7 +355,7 @@ func TestLongRunningBinariesInstallTheHandler(t *testing.T) { case uses && unmanagedBinaries[d.Name()]: t.Errorf("cmd/%s imports %s; remove it from unmanagedBinaries", d.Name(), pkg) case !uses && !unmanagedBinaries[d.Name()]: - t.Errorf("cmd/%s doesn't import %s; call logging.Setup from its root command", d.Name(), pkg) + t.Errorf("cmd/%s doesn't import %s; call Options.Setup from its root command", d.Name(), pkg) } } } diff --git a/internal/nadpatch/nadpatch.go b/internal/nadpatch/nadpatch.go index 89c9c5b76..27882eb33 100644 --- a/internal/nadpatch/nadpatch.go +++ b/internal/nadpatch/nadpatch.go @@ -111,7 +111,7 @@ func AnnotateNAD(ctx context.Context, k8s client.Client, nadName, nadNamespace s } return fmt.Errorf("patch NetworkAttachmentDefinition %s/%s: %w", nadNamespace, nadName, err) } - slog.Debug("NAD annotated", "name", nadName, "namespace", nadNamespace, "annotations", annotations) + slog.Debug("NAD annotated", "resource_name", nadName, "resource_namespace", nadNamespace, "annotations", annotations) return nil } diff --git a/internal/runtime/gobgp/server.go b/internal/runtime/gobgp/server.go index 5003654db..4f145429e 100644 --- a/internal/runtime/gobgp/server.go +++ b/internal/runtime/gobgp/server.go @@ -9,20 +9,14 @@ package gobgp import ( "context" "fmt" - "io" "log/slog" "sync/atomic" gobgpserver "github.com/osrg/gobgp/v4/pkg/server" ) -const defaultLogLevel = "panic" - // Config holds configuration for the embedded GoBGP server. type Config struct { - // LogLevel controls GoBGP's internal log verbosity. - // Valid values: debug, info, warn, error, panic. Defaults to panic. - LogLevel string // APISocket, when non-empty, is the unix socket path the server serves // the GoBGP API on, read-only, for the gobgp CLI. Empty serves no API. APISocket string @@ -37,9 +31,6 @@ type Server struct { // newServer creates a Server with the given config. Call Start to run it. func newServer(cfg Config) *Server { - if cfg.LogLevel == "" { - cfg.LogLevel = defaultLogLevel - } return &Server{ cfg: cfg, ready: make(chan struct{}), @@ -92,14 +83,13 @@ func (s *Server) newBgpServer() *gobgpserver.BgpServer { } // buildServerOptions assembles the ServerOption slice for NewBgpServer. -// Exported for testing. +// GoBGP logs through the process's slog default, which internal/logging +// installs, under the name gobgp, so its lines share the binary's format and +// level. GoBGP's SetLogLevel API gets no level to change; the API socket +// refuses it anyway. Exported for testing. func (s *Server) buildServerOptions() []gobgpserver.ServerOption { - level := parseLogLevel(s.cfg.LogLevel) - levelVar := &slog.LevelVar{} - levelVar.Set(level) - logger := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: levelVar})) - opts := []gobgpserver.ServerOption{gobgpserver.LoggerOption(logger, levelVar)} - return opts + logger := slog.Default().With("logger", "gobgp") + return []gobgpserver.ServerOption{gobgpserver.LoggerOption(logger, nil)} } // WaitReady blocks until the GoBGP server is initialized or ctx is cancelled. @@ -111,18 +101,3 @@ func (s *Server) WaitReady(ctx context.Context) error { return fmt.Errorf("gobgp not ready: %w", ctx.Err()) } } - -func parseLogLevel(level string) slog.Level { - switch level { - case "debug": - return slog.LevelDebug - case "info": - return slog.LevelInfo - case "warn": - return slog.LevelWarn - case "error": - return slog.LevelError - default: - return slog.LevelError + 4 // above error — effectively silent - } -} diff --git a/internal/trafficpolicy/node/edge.go b/internal/trafficpolicy/node/edge.go index aa8fe2276..70f1ae995 100644 --- a/internal/trafficpolicy/node/edge.go +++ b/internal/trafficpolicy/node/edge.go @@ -49,7 +49,7 @@ func (r *Reconciler) setupEdge(mgr ctrl.Manager) error { for i := range services { var list galacticv1alpha1.EdgeAttachmentList if err := c.List(ctx, &list, client.MatchingFields{edgeServiceIndex: string(services[i].UID)}); err != nil { - ctrl.LoggerFrom(ctx).Error(err, "list edge attachments of service", "service", services[i].Name) + ctrl.LoggerFrom(ctx).Error(err, "list edge attachments of service", "serviceName", services[i].Name) continue } for j := range list.Items { diff --git a/tests/edgeconformance/masqueprovider/main.go b/tests/edgeconformance/masqueprovider/main.go index 73d3ff06f..c663741c2 100644 --- a/tests/edgeconformance/masqueprovider/main.go +++ b/tests/edgeconformance/masqueprovider/main.go @@ -46,6 +46,7 @@ import ( "go.datum.net/galactic/internal/edge/masque" "go.datum.net/galactic/internal/edge/provider" "go.datum.net/galactic/internal/edge/timing" + "go.datum.net/galactic/internal/logging" ) func main() { @@ -60,7 +61,8 @@ func run() error { certPath := flag.String("tls-cert", "/etc/masque/tls/tls.crt", "server certificate") keyPath := flag.String("tls-key", "/etc/masque/tls/tls.key", "server key") flag.Parse() - log := slog.New(slog.NewJSONHandler(os.Stderr, nil)) + logging.SetupFile(os.Stderr, slog.LevelInfo) + log := slog.Default() cfg, err := LoadConfig(*configPath) if err != nil { @@ -97,7 +99,7 @@ func run() error { } a, err := masque.New(masque.Config{ Client: c, Provider: cfg.Provider, Pod: pod, Authorizer: cfg, Claims: claims, - OpenDevice: masque.OpenTUN, Log: log.With("pod", pod.Name), + OpenDevice: masque.OpenTUN, Log: log.With("podName", pod.Name), }) if err != nil { return err diff --git a/tests/lgqualify/harness_test.go b/tests/lgqualify/harness_test.go index dc12248d9..1c98f6cad 100644 --- a/tests/lgqualify/harness_test.go +++ b/tests/lgqualify/harness_test.go @@ -528,7 +528,7 @@ func (l *lab) load(ctx context.Context, s spec) ([]Record, []json.RawMessage, er // the lab's operator identity, as the legacy operator interface. func (l *lab) operator(ctx context.Context, args ...string) (string, error) { full := append([]string{dockerExec, clientNode, clientDir + "/fabric-api", - "--log-format", "text", "--log-level", "warn", + "--log-level", "warn", "query", "--cell", cell, "--operator", "lab-verify", "--tls-cert", clientDir + "/operator/tls.crt", "--tls-key", clientDir + "/operator/tls.key", "--tls-ca", clientDir + "/operator/ca.crt"}, args...)