Repository navigation
feat(observability): persistent per-subsystem file logging via SILO_LOG_FILE - #264
CoffeeKnyte wants to merge 1 commit into
Conversation
…OG_FILE Silo previously logged only to stderr, so under Docker the only record of a run lived in the daemon json-file log and was lost on container recreate. Add an opt-in file sink: when SILO_LOG_FILE is set, a new logsink.Router fans each slog record to stderr + a combined rotating file, and (with SILO_LOG_SPLIT) to per-subsystem files (silo-jellycompat.log, silo-playback.log, silo-api.log, silo-scanner.log, silo-metadata.log, silo-notifications.log). Rotation via lumberjack; records are classified by the same "component" signal opslog persists, reusing opslog.InferComponent. File destinations are best-effort: their write errors never propagate out of the Router, so a full/read-only log volume cannot disable the wrapping opslog DB/admin-stream capture or wedge the server. Bad paths are validated eagerly in New so buildBaseHandler's stderr fallback actually engages.
📝 WalkthroughWalkthroughAdds an internal/logsink package implementing a slog.Handler that routes log records to console and rotating, category-based log files, with configurable splitting, rotation, and compression. Exports InferComponent from opslog. Wires cmd/silo/main.go to build the handler from environment variables with stderr fallback, plus corresponding tests. ChangesFile-based rotating log routing
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Main as cmd/silo main
participant BuildHandler as buildBaseHandler
participant LogSink as logsink.New
participant Router as logsink.Router
participant Files as Rotating Log Files
Main->>BuildHandler: buildBaseHandler(format, level)
BuildHandler->>BuildHandler: read SILO_LOG_* env vars
BuildHandler->>LogSink: New(Options)
LogSink->>LogSink: ensureWritable(paths)
alt file sink creation succeeds
LogSink->>Router: construct Router with console+file destinations
Router-->>LogSink: handler, closer
LogSink-->>BuildHandler: handler, closer, nil
else creation fails
LogSink-->>BuildHandler: nil, nil, error
BuildHandler->>BuildHandler: fall back to stderr-only handler
end
BuildHandler-->>Main: slog.Handler, io.Closer
Main->>Router: log record emitted
Router->>Router: classify(record) via component attr or InferComponent
Router->>Files: write to combined log
opt Split enabled
Router->>Files: write to per-category log
end
Router-->>Main: Handle() (console errors only)
Main->>Main: defer logCloser.Close()
Possibly related issues
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fc98a87f75
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| logLevelVar := new(slog.LevelVar) | ||
| logLevelVar.Set(parseLogLevel(cfg.Server.LogLevel)) | ||
| baseHandler := buildBaseHandler(cfg.Server.LogFormat, logLevelVar) | ||
| baseHandler, logCloser := buildBaseHandler(cfg.Server.LogFormat, logLevelVar) |
There was a problem hiding this comment.
Capture standard and early logs in the file sink
When SILO_LOG_FILE is set, installing only the slog handler here leaves the existing standard-library log output—and all slog/log calls before this point during bootstrap, migrations, and config validation—on stderr only; examples after this line include log.Fatalf("log stream hub start..."), and there are many log.Printf call sites in playback/reconciler. Those are the crash-loop/debug records operators need to survive container recreation, so the persistent file can miss the failure that explains a restart. Wire the file sink/tee into the standard logger early, or migrate those call sites before relying on durable process logs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
🧹 Nitpick comments (3)
cmd/silo/main.go (1)
137-155: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate console-handler construction in fallback path.
The error fallback (lines 139-148) reimplements the JSON/text format switch that
logsink.Newalready performs internally for its console-only path (whenopts.Fileis empty,logsink.Newreturns a plain console handler and a no-op closer without erroring — seeinternal/logsink/logsink.goNew). Duplicating this logic here risks drift if the format-handling behavior inlogsinkchanges later (e.g. new format support).Consider retrying
logsink.Newwith the file path cleared instead, reusing the exact same console-construction path and dropping the need fornoopLogCloserentirely:♻️ Proposed refactor
func buildBaseHandler(format string, level slog.Leveler) (slog.Handler, io.Closer) { - handler, closer, err := logsink.New(logSinkOptionsFromEnv(format, level)) + opts := logSinkOptionsFromEnv(format, level) + handler, closer, err := logsink.New(opts) if err != nil { // Never let a logging-config problem take down the server: fall back to // stderr-only and surface the failure through the standard logger. log.Printf("file logging disabled: %v", err) - opts := &slog.HandlerOptions{Level: level} - if strings.EqualFold(format, "json") { - return slog.NewJSONHandler(os.Stderr, opts), noopLogCloser{} - } - return slog.NewTextHandler(os.Stderr, opts), noopLogCloser{} + opts.File = "" + opts.Split = false + // File=="" is guaranteed not to error, per logsink.New's contract. + handler, closer, _ = logsink.New(opts) } return handler, closer } - -type noopLogCloser struct{} - -func (noopLogCloser) Close() error { return nil }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@cmd/silo/main.go` around lines 137 - 155, The fallback in buildBaseHandler is duplicating logsink’s console-handler creation logic instead of reusing the same path that logsink.New already uses when no file is configured. Update buildBaseHandler to retry logsink.New with the file setting cleared on error so it returns the existing console-only handler path, and remove the manual JSON/text switch plus the noopLogCloser type since they should no longer be needed.internal/logsink/logsink.go (2)
314-335: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winComponent extraction diverges from opslog's stricter string check.
classify()(Line 323) andWithAttrs()(Line 351) resolve "component" viaa.Value.Resolve().String(), which stringifies anyValuekind (ints, bools, etc.).opslog.Handler.Handleinstead does a strictcomponent, _ := attrs["component"].(string)type assertion, so a non-string component value there yields""and falls back to message-prefix inference. The package doc states file and DB classification should use "the same 'component' signal," but for a non-string component attribute the two paths would classify differently.♻️ Proposed fix to match opslog's string-only precedence
rec.Attrs(func(a slog.Attr) bool { if a.Key == "component" { - if s := a.Value.Resolve().String(); s != "" { + if s, ok := a.Value.Resolve().Any().(string); ok && s != "" { component = s return false } } return true })Apply the analogous change in
WithAttrs(Line 351).Also applies to: 337-358
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/logsink/logsink.go` around lines 314 - 335, The component extraction in Router.classify and WithAttrs is too permissive because it stringifies any slog.Value instead of matching opslog’s string-only handling. Update the component lookup in both places to only accept attributes whose value is actually a string, and otherwise leave component empty so the existing InferComponent fallback is used. Keep the precedence/override behavior the same while making classification consistent with opslog.Handler.
289-312: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winClone the record before fan-out.
Router.Handlepasses the sameslog.Recordto multiple downstream handlers; userec.Clone()for each dispatch so handlers don’t share state and the slog contract stays intact.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/logsink/logsink.go` around lines 289 - 312, Router.Handle currently fans out the same slog.Record to multiple destinations, which can let downstream handlers share mutable record state. Update Router.Handle to clone the record for each dispatch using rec.Clone() before calling each destination’s Handle method, while keeping the existing consoleErr best-effort behavior and the classification/Enabled checks intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@cmd/silo/main.go`:
- Around line 137-155: The fallback in buildBaseHandler is duplicating logsink’s
console-handler creation logic instead of reusing the same path that logsink.New
already uses when no file is configured. Update buildBaseHandler to retry
logsink.New with the file setting cleared on error so it returns the existing
console-only handler path, and remove the manual JSON/text switch plus the
noopLogCloser type since they should no longer be needed.
In `@internal/logsink/logsink.go`:
- Around line 314-335: The component extraction in Router.classify and WithAttrs
is too permissive because it stringifies any slog.Value instead of matching
opslog’s string-only handling. Update the component lookup in both places to
only accept attributes whose value is actually a string, and otherwise leave
component empty so the existing InferComponent fallback is used. Keep the
precedence/override behavior the same while making classification consistent
with opslog.Handler.
- Around line 289-312: Router.Handle currently fans out the same slog.Record to
multiple destinations, which can let downstream handlers share mutable record
state. Update Router.Handle to clone the record for each dispatch using
rec.Clone() before calling each destination’s Handle method, while keeping the
existing consoleErr best-effort behavior and the classification/Enabled checks
intact.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7ee107fa-a995-4ace-bb32-3d649a089a0d
📒 Files selected for processing (5)
cmd/silo/logsink_env_test.gocmd/silo/main.gointernal/logsink/logsink.gointernal/logsink/logsink_test.gointernal/opslog/handler.go
|
Copied from #265 (comment):
|
|
@darthShadow — fair point, and I'm open to it. To be clear about scope: this PR is deliberately narrow — its only goal is to stop the transient Docker logs (lost on every container recreate) from disappearing, by persisting them to a mounted volume. I mainly just wanted to keep the logs. Happy to close this PR for now — let's discuss in Discord what foundation we want to use for the logs (OTel or otherwise) before I take it further. |
|
Closing in favour of #290. Per @darthShadow's feedback (#265 (comment)) to build on OpenTelemetry rather than a custom file sink, we dropped the bespoke rotating-file approach here and reworked it: #290 adds opt-in OpenTelemetry logs + traces (default-off, stderr + opslog unchanged), moves durable retention/rotation to the collector/backend and the container runtime, and — beyond the original scope — adds secret redaction on every sink plus a repo-wide slog context standardization with a lint gate. Durability (the original goal here) is now handled by OTLP export + Docker json-file rotation on a mounted volume, documented in docs/architecture/observability.md. |
Part of #265.
Adds opt-in durable file logging so a server's logs survive container recreation, with optional per-subsystem split files.
Problem
Logs vanish when the container is recreated. Silo only ever wrote its logs to stderr. Under Docker that means the only record of a run lives in the daemon's
json-filelog, which is deleted every time the container is recreated (a redeploy, an image bump, adocker compose upafter an edit). An operator investigating something that happened "before the last restart" has nothing to look at — the history is gone. There is also no way, short of hand-editing the container entrypoint, to keep logs on a mounted volume.No way to isolate one subsystem's logs. When chasing a specific problem — a Jellyfin-compat client misbehaving, a transcode failing, a scan stalling — an operator has to grep the entire firehose. There is no focused, per-area log to tail.
Solution
A new opt-in file sink, gated entirely on the
SILO_LOG_FILEenvironment variable (empty = today's stderr-only behaviour, unchanged). File logging is operational infrastructure, so it is env-driven and configured before the DB-backed settings, matching the existingSILO_NODE_NAME/SILO_PLUGIN_CACHE_DIRpattern.feat(observability): persistent per-subsystem file logging via SILO_LOG_FILE
internal/logsinkpackage (logsink.go).logsink.Routeris anslog.Handlerinstalled as the process base handler. It fans each record to stderr + a combined rotating file, and — withSILO_LOG_SPLIT— to a per-subsystem file (silo-jellycompat.log,silo-playback.log,silo-api.log,silo-scanner.log,silo-metadata.log,silo-notifications.log). Rotation useslumberjack(already a dependency, same settings as the jellycompat debug logger). Records are classified by the samecomponentsignalopslogpersists — an explicitcomponentattr, else thesubsystem:message prefix — reusingopslog.InferComponent(exported ininternal/opslog/handler.go) so file and DB classification stay in lock-step.cmd/silo/main.go:131,buildBaseHandler). Delegates tologsink.New, reads theSILO_LOG_*env knobs (logSinkOptionsFromEnv), and returns a closer deferred inrun(). Chain is unchanged otherwise:opslog.Handler → logfilter(quiet) → logsink.Router → {stderr, files}.logsink.go,Router.Handle). Only the console destination's error may propagate. A file write failure (ENOSPC, read-only mount, rotation error) is swallowed. This matters because the wrappingopslog.Handlerskips its DB/admin-stream capture whenever its inner handler returns an error — so without this, a full log volume would silently disable the database operational-log path too. The console's effectively-never-fails contract is preserved, so logging can't wedge the server.logsink.go,ensureWritable).lumberjackopens files lazily on first write, so a badSILO_LOG_FILEwould otherwise surface only at runtime (where slog discardsHandleerrors).NewnowMkdirAlls and probe-opens every target path up front and returns an error, sobuildBaseHandler's stderr fallback actually engages and logs the reason.SILO_LOG_MAX_BACKUPS=0/SILO_LOG_MAX_AGE_DAYS=0are passed through verbatim (lumberjack's "keep all" / "never expire") rather than coalesced back to defaults. Multi-word inferred prefixes (jellycompat autoscan:) route via their leading token so they still land in the subsystem file. Inlinecomponentattrs override a staticWith("component", …), matchingopslog's last-write-wins precedence.This change went through a 7-angle adversarial review; the items above (best-effort file writes, eager path validation, config fidelity, routing fixes) are the confirmed findings from that pass, folded into the initial commit.
Risk / follow-ups
log_quietalso suppresses file records. The router sits below the quiet filter, so quieting a noisy subsystem also empties its split file. This keeps files an exact mirror of the console stream (documented in the package doc). If durable-capture-despite-quiet is wanted, the file sinks would need to tee in before the filter — deferred pending a product call.componentattr nor use asubsystem:message prefix fall to the combined log only. Tagging more subsystem roots explicitly is a follow-up.opslog's DB redaction does not apply to console/file sinks. Worth a separate hardening pass if secrets-in-logs is a concern.docker-compose.ymlstill needsSILO_LOG_FILE/SILO_LOG_SPLITset and the old tee/FIFO entrypoint removed; intentionally left out of this code-only PR.Verification
go build ./...— clean.go vet ./internal/logsink/ ./cmd/silo/ ./internal/opslog/— clean.gofmt -lon all touched files — no output.go test ./internal/logsink/ -race— 6 tests pass (routing to correct files incl. inline-attr and multi-word paths, inline-overrides-static, rotation produces a backup, unwritable path returns an error, closer error propagation, console-only when no file set).go test ./cmd/silo/— env-parsing tests pass (envIsTrue, defaults, overrides incl. explicit-0 retention, invalid-number fallback).AI-use disclosure
Implemented with AI assistance (Claude Code): drafting, the multi-agent adversarial review, the resulting fixes, and this description. All changes were reviewed by the author.
Summary by CodeRabbit