Skip to content

feat(observability): persistent per-subsystem file logging via SILO_LOG_FILE - #264

Closed
CoffeeKnyte wants to merge 1 commit into
mainfrom
feat/log-file-sink
Closed

CoffeeKnyte wants to merge 1 commit into
mainfrom
feat/log-file-sink

Conversation

@CoffeeKnyte

@CoffeeKnyte CoffeeKnyte commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

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-file log, which is deleted every time the container is recreated (a redeploy, an image bump, a docker compose up after 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_FILE environment 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 existing SILO_NODE_NAME / SILO_PLUGIN_CACHE_DIR pattern.

feat(observability): persistent per-subsystem file logging via SILO_LOG_FILE

  • New internal/logsink package (logsink.go). logsink.Router is an slog.Handler installed as the process base handler. It fans each record to stderr + a combined rotating file, and — with SILO_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 uses lumberjack (already a dependency, same settings as the jellycompat debug logger). Records are classified by the same component signal opslog persists — an explicit component attr, else the subsystem: message prefix — reusing opslog.InferComponent (exported in internal/opslog/handler.go) so file and DB classification stay in lock-step.
  • Wiring (cmd/silo/main.go:131, buildBaseHandler). Delegates to logsink.New, reads the SILO_LOG_* env knobs (logSinkOptionsFromEnv), and returns a closer deferred in run(). Chain is unchanged otherwise: opslog.Handler → logfilter(quiet) → logsink.Router → {stderr, files}.
  • Reliability: file writes are best-effort (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 wrapping opslog.Handler skips 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.
  • Reliability: bad paths fail fast (logsink.go, ensureWritable). lumberjack opens files lazily on first write, so a bad SILO_LOG_FILE would otherwise surface only at runtime (where slog discards Handle errors). New now MkdirAlls and probe-opens every target path up front and returns an error, so buildBaseHandler's stderr fallback actually engages and logs the reason.
  • Config fidelity. Explicit SILO_LOG_MAX_BACKUPS=0 / SILO_LOG_MAX_AGE_DAYS=0 are 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. Inline component attrs override a static With("component", …), matching opslog'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_quiet also 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.
  • Per-subsystem routing is best-effort, not exhaustive. Subsystems that neither set a component attr nor use a subsystem: message prefix fall to the combined log only. Tagging more subsystem roots explicitly is a follow-up.
  • File records are not redacted. Like stderr today (no regression), file output is raw; opslog's DB redaction does not apply to console/file sinks. Worth a separate hardening pass if secrets-in-logs is a concern.
  • Runtime wiring not included. The deployment docker-compose.yml still needs SILO_LOG_FILE/SILO_LOG_SPLIT set 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 -l on 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

  • New Features
    • Added optional file-based logging with automatic rotation and per-area log splitting.
    • Logging now falls back to console output if file logging can’t be initialized, so the app still starts.
    • Added broader log category detection for more consistent routing.
  • Bug Fixes
    • Improved handling of environment settings, including default values, zero values, and invalid numeric inputs.
    • Added safeguards for log cleanup so log files are properly closed and flushed.

…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.
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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.

Changes

File-based rotating log routing

Layer / File(s) Summary
Export InferComponent helper
internal/opslog/handler.go
Renames unexported inferComponent to exported InferComponent and updates the internal caller.
Category model and routing
internal/logsink/logsink.go, internal/logsink/logsink_test.go
Defines Category constants and prefix-based mapping via CategoryForComponent/lookupCategory, tested across case/prefix/multi-word scenarios.
Options, rotation, and construction
internal/logsink/logsink.go, internal/logsink/logsink_test.go
Adds Rotation, DefaultRotation, Options, and New, building console plus lumberjack-backed file handlers with startup validation, verified by console-only, rotation, and unwritable-path tests.
Router fan-out and helpers
internal/logsink/logsink.go, internal/logsink/logsink_test.go
Implements Router.Handle/WithAttrs/WithGroup fan-out to console/combined/split files with non-propagating file errors, plus newFormatHandler, stem, noopCloser, multiCloser helpers and their tests.
main.go wiring and env config tests
cmd/silo/main.go, cmd/silo/logsink_env_test.go
Replaces buildBaseHandler to optionally initialize logsink from SILO_LOG_* env vars with stderr fallback, defers closing the returned closer in main, and adds tests for envIsTrue and logSinkOptionsFromEnv defaults/overrides/invalid inputs.

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()
Loading

Possibly related issues

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: optional persistent file logging driven by SILO_LOG_FILE, including per-subsystem routing.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/log-file-sink

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread cmd/silo/main.go
logLevelVar := new(slog.LevelVar)
logLevelVar.Set(parseLogLevel(cfg.Server.LogLevel))
baseHandler := buildBaseHandler(cfg.Server.LogFormat, logLevelVar)
baseHandler, logCloser := buildBaseHandler(cfg.Server.LogFormat, logLevelVar)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
cmd/silo/main.go (1)

137-155: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate console-handler construction in fallback path.

The error fallback (lines 139-148) reimplements the JSON/text format switch that logsink.New already performs internally for its console-only path (when opts.File is empty, logsink.New returns a plain console handler and a no-op closer without erroring — see internal/logsink/logsink.go New). Duplicating this logic here risks drift if the format-handling behavior in logsink changes later (e.g. new format support).

Consider retrying logsink.New with the file path cleared instead, reusing the exact same console-construction path and dropping the need for noopLogCloser entirely:

♻️ 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 win

Component extraction diverges from opslog's stricter string check.

classify() (Line 323) and WithAttrs() (Line 351) resolve "component" via a.Value.Resolve().String(), which stringifies any Value kind (ints, bools, etc.). opslog.Handler.Handle instead does a strict component, _ := 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 win

Clone the record before fan-out. Router.Handle passes the same slog.Record to multiple downstream handlers; use rec.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

📥 Commits

Reviewing files that changed from the base of the PR and between 46a6e86 and fc98a87.

📒 Files selected for processing (5)
  • cmd/silo/logsink_env_test.go
  • cmd/silo/main.go
  • internal/logsink/logsink.go
  • internal/logsink/logsink_test.go
  • internal/opslog/handler.go

@darthShadow

darthShadow commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Copied from #265 (comment):

I would have preferred some discussion regarding this before committing any effort for it. If we are touching the monitoring/observability, it would have been a lot better if we just went the OpenTelemetry (opentelemetry.io/docs) way rather than custom implementations and sinks.

@CoffeeKnyte

CoffeeKnyte commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor Author

@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.

@CoffeeKnyte

Copy link
Copy Markdown
Contributor Author

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.

@CoffeeKnyte CoffeeKnyte closed this Jul 3, 2026
@CoffeeKnyte
CoffeeKnyte deleted the feat/log-file-sink branch July 3, 2026 22:45
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