Skip to content

feat: log to the logger in the context - #3584

Open
kiangribi wants to merge 5 commits into
srl-labs:mainfrom
kiangribi:feat/context-logger
Open

kiangribi wants to merge 5 commits into
srl-labs:mainfrom
kiangribi:feat/context-logger

Conversation

@kiangribi

@kiangribi kiangribi commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Heyo!

containerlab logs through the global charmbracelet/log logger. A program that embeds containerlab as a Go library and runs labs for several users at once, like Antimony, can't tell which lab a message belongs to, so it can't show a user the output of their own deploy, destroy or restart.

Today, Antimony runs the containerlab CLI as a subprocess and collects logs from stderr. This PR solves the largest upstream road block that keeps Antimony from switching from the legacy CLI subprocess calling to using the new clab runtime for docker as well as c9s.

Note: This change was largely generated by Claude, since its a large refactor. I also ran a review agent at high effort on this change double-checking its correctness and code health.

The change lets the library log to the logger stored in the operation's context, with charmbracelet's own context API:

ctx = log.WithContext(ctx, labLogger)
_, err = c.Deploy(ctx, deployOpts)

log.FromContext returns the default logger when the context holds none, so the CLI and every existing caller behave exactly as before.

Change

  • Log calls: every library log call outside cmd/ that has the operation's ctx in scope now uses log.FromContext(ctx), about 620 calls in core, nodes, links, runtime (docker and podman), labruntime/clabernetes, capture, exec, mgmt and netconf.

  • Passing the context down: helpers on the deploy, destroy, apply, start/stop/restart, save, exec, inspect, events and capture paths that logged without a context now take ctx. That's only where all their callers already have one. This changes some exported signatures and interfaces:

    • nodes.Node: GenerateConfig(ctx, dst, templ), DeleteNetnsSymlink(ctx)
    • nodes.NodeOverwrites: VerifyContainerName(ctx), VerifyHostRequirements(ctx)
    • dependency_manager.DependencyManager: CheckAcyclicity(ctx)
    • the docker firewall client (definitions.ClabFirewall, firewall.NewFirewallClient)
    • helpers such as CLab.WriteState, exec.ExecCollection.Log, nodes.LoadStartupConfigFileVr, nodes.WriteSavedConfig, DefaultNode.LoadOrGenerateCertificate, types.HostRequirements.Verify, netconf.GetConfig/MultiExec, mgmt.PrepareMacvlanParent, progress.New, capture.ReportGap, links.SetNameMACAndUpInterface, and a few in utils and virt (DeleteNetnsSymlink, NSEthtoolTXOff, DisableTxOffloadByIndex, SpawnCLIviaExec, MacvlanHost.Remove, VerifyVirtSupport, GetSysMemory).

    The mocks are regenerated with mockgen v0.6.0.

  • Loggers handed to other code: the c9s compiler's logger and the kind provider's logger are now built from the context logger.

  • Image pulls: progress.New(ctx, w) makes the plain reporter log to the context logger. A logger in the context also turns off the TUI progress bars, since its owner collects the output rather than a terminal.

  • Contexts that dropped the logger: three places created their own background context although the caller's was at hand. These are the SR-SIM version detection (createSROSConfigFiles), the SR Linux custom prompt lookup, and the SR-SIM distributed management IP lookup. They now use the caller's ctx, so they're also cancelled with the operation.

  • Docs: a "Logging per lab" subsection under "Node access from Go" in the c9s runtime docs, with a note that it applies to Docker and Podman labs as well.

What keeps the default logger

  • Lab construction: NewContainerLab, its options, topology loading and parsing, node Init, link resolution and YAML unmarshalling take no context. That includes the copy destroy builds per lab, so "Parsing & checking topology" still goes to the default logger. Giving construction a context is an API decision of its own (a ctx for NewContainerLab, or an option), so I left it for a follow-up.
  • CLI-only code: the destroy-all terminal prompt, the graph command where it creates its own context, the sudo helpers and the TUI renderer.
  • Code not tied to one operation: generic helpers in utils, git and cert, pure parsers, the IPAM DAD probe goroutine shared by concurrent probes, and the capture reorder buffer.

A few file copies in node PreDeploy steps (clabutils.CopyFile for licenses and startup configs) still pass context.Background(). CopyFile doesn't log, and switching them would change their cancellation, so I left them alone.

No lint rule enforces the convention yet. forbidigo could ban bare log.Info and friends outside cmd/ once construction takes a context too.

Testing

  • go build ./... and go build -tags podman ./...
  • go test ./... and go test -tags podman ./runtime/podman/...
  • golangci-lint run ./... reports the same issues as on main.
  • New tests:
    • TestDestroyLogsToContextLogger: a destroy logs to the context logger and not to the default logger. Both are set to the debug level.
    • TestNewLogsToContextLogger: image pull progress goes to the context logger.
    • TestUseTUI: the progress bars are only used on a terminal, and not when the context holds a logger.
  • Two existing tests (TestNodeReadinessProgressReportsTransitions, TestExecCollectionLogPreservesAddOrder) now capture output through a context logger instead of swapping the default logger's output.
  • I checked every log.FromContext argument with a small go/types scan: each one is a parameter of the enclosing function or closure, never a local context.Background(). No call passes a nil context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kiangribi
kiangribi marked this pull request as draft November 8, 2026 02:58
kiangribi and others added 2 commits November 11, 2026 10:55
@kiangribi
kiangribi marked this pull request as ready for review November 17, 2026 11:06
@hellt

hellt commented Nov 22, 2026

Copy link
Copy Markdown
Member

/tofarev review

@tofarev

tofarev Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

ToFaRev review — partial

Reviewed bd4a8beb74d9 with zai-org/GLM-5.3-Flash · Session log · Workflow run

Partial review. The findings below do not cover all changes.

Finding Location
P4 - prepareAddNodes pulls images without the progress reporter, diverging from deploy output core/apply.go:309-313

Detailed findings:

P4 - prepareAddNodes pulls images without the progress reporter, diverging from deploy output

Location: core/apply.go:309-313

Problem: The PR wires the new utils/progress reporter for image pulls only in pullImagesForNodes (core/image.go:22-25), which is reached from CLab.Deploy. The reconcile path CLab.apply -> reconcileNodes -> prepareAddNodes calls c.Nodes[nodeName].PullImage(ctx) with a context that carries no reporter, so DockerRuntime.PullImage falls back to its legacy single-image rendering.

Trigger: Run containerlab apply on an existing lab that adds one or more nodes requiring an image pull, and compare the pull output with a containerlab deploy of a fresh lab.

Impact: Cosmetic inconsistency only: deploy shows the new per-image reporter output while apply shows legacy pull logs. Correctness is unaffected because the nil-reporter fallback is intentional design (progress.FromContext returns nil to signal legacy rendering).

Suggested correction: Optionally mirror pullImagesForNodes by wrapping the pull loop in prepareAddNodes with clabutilsprogress.New(ctx, os.Stderr) and clabutilsprogress.NewContext, so both flows report pulls consistently. Alternatively leave as-is and accept the divergence; marked P4 because the fallback functions as designed.

review conditions

Source inspection only; PR code, tests, and benchmarks were not executed.

  • The supplied diff.txt is truncated (ends at nodes/k8s_kind/logger.go); files after that point were reviewed by direct base-vs-head inspection and targeted signature-consistency greps instead of the unified diff. All changed paths from manifest.json were covered by one route or the other.
  • The charmbracelet/log v1.0.0 module source was not readable (no module cache in the environment); the log.FromContext fallback-to-default behavior was established from in-repo evidence (labruntime/clabernetes/clabernetes_test.go TestNodePhaseProgressDetails capturing global output while calling progress.observe(context.Background(), ...)) and the added docs section, not from library source.
  • Static, source-only review; no tests were executed. Added tests (utils/progress/progress_test.go, labruntime/clabernetes/clabernetes_test.go, exec/exec_test.go) were inspected, not run.
  • Remaining bare global log calls in nodes/ (e.g., nodes/default_node.go:1071, nodes/vr_node.go:87, nodes/vr_c8000v/vr-c8000v.go:110, nodes/vyosnetworks_vyos/vyos.go:77, nodes/sros/component.go:190, nodes/srl/srl.go:269,300, nodes/iol/iol.go:578) all sit in functions without a context.Context parameter in both base and head; they are consistent with base behavior and the documented mixed-logging design and were not flagged.
  • context.Background() at runtime/docker/docker.go:106,1782,1788 pre-exists in base and was not introduced by this PR.
  • No topology or configuration schema changes were made; the user-visible behavior change (per-lab logging, image-pull reporting) is documented in docs/manual/clabernetes/runtime.md 'Logging per lab'.
  • Snapshot incomplete: true — review environment provided source snapshots and manifest but the unified diff was truncated.
  • Long lines in head:docs/images/clabnew.svg exceed the read tool's per-line display limit.
  • 175 additional coverage limitations were recorded.

Powered by Nebius Token Factory  ·  Z.ai $\color{gray}\textsf{GLM-5.3-Flash}$

kiangribi and others added 2 commits November 23, 2026 20:49
Resolves the capture/local.go conflict and logs the new netem
messages in links/netem_apply.go to the context logger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011VSJ2TLnUV5rU9F24Q3BNz
Pulls for nodes added by apply share a reporter like deploy's,
instead of each pull creating its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011VSJ2TLnUV5rU9F24Q3BNz
@kiangribi

Copy link
Copy Markdown
Contributor Author

The P4 is fixed in 141aa0f: apply now pulls images through one shared reporter, like deploy.

I also merged main and moved the new netem log messages to the context logger.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants