Document ID: DES-005
Status: Accepted
Version: v1.2.0
Updated: 2026-11-29
Related Requirement: Logging and Diagnostics Requirements
1. Design Boundaries and Components
RelayLink uses Serilog and its official File sink to unify structured logging, severity-based stream splitting, and rolling retention across Server and Agent. This document records the adopted design; Accepted does not mean every target environment has completed acceptance testing—see Verification Status for current evidence and open items.
| Component | Implementation Entry | Responsibilities |
|---|---|---|
| Shared logging library | RelayLink.Logging/FileLogging.cs | Log levels, JSONL formatting, dual output streams, size/date rolling and retention |
| Agent host | Program.cs, AgentFileLogging.cs | Resolve log path, initialize startup logging, attach ILogger, flush on shutdown |
| Agent local web | AgentLocalDashboard.cs | Reuse host ILoggerFactory; log Error on save failures without logging request bodies |
| Server host | Program.cs | Select log directory, attach ILogger, persist startup and host failures |
| Control rejection | ControlRejectionReason.cs, TunnelAcceptorService.cs, ControlSessionWorker.cs | Stable reason codes, two-sided logging, error frames, and rejection audit events |
| Operational diagnostics | AgentDiagnosticLog.cs | Per-profile phase, byte-count, and elapsed-time JSONL trace |
The shared logging library does not depend on Protocol, Server, or Agent; Protocol does not depend on Serilog, file I/O, or host abstractions. Business code continues to log via ILogger. SQLite auditing (audit_event and direct_lease_occupancy) and minute-level traffic history (traffic_minute) remain separate services and are not folded into file logs.
2. Log Format, Levels, and Outputs
Runtime log files use UTF-8 without BOM in JSONL format, one Serilog JsonFormatter(renderMessage: true) event per line. Standard fields are Timestamp (with timezone offset), Level, MessageTemplate, RenderedMessage, optional Exception, and Properties. Properties.SourceContext identifies the logger category. Correlation fields preserve existing scope/property names: profileId, clientId, sessionId, connectionId, and attemptId (distinguishing relay or P2P direct attempts within a logical connection). Process-global events do not require a server profile identifier.
Microsoft.Extensions.Logging levels Information, Warning, Error, and Critical map to Serilog Information, Warning, Error, and Fatal. The default minimum level is Information, with Microsoft overridden to Warning and Microsoft.Hosting.Lifetime kept at Information. Debug and Trace are disabled by default, and no dynamic log-level or retention settings are exposed.
| Component / File Pattern | Level Filter | Rolling Trigger | Retention |
|---|---|---|---|
Agent agent-YYYYMMDD[_NNN].jsonl |
Information <= level < Error |
Each calendar day or 10 MiB | Retained for 14 days |
Agent error-YYYYMMDD[_NNN].jsonl |
Error / Fatal |
Same as above | Never deleted by age or count |
Server server-YYYYMMDD[_NNN].jsonl |
Information <= level < Error |
Same as above | Retained for 14 days |
Server server-error-YYYYMMDD[_NNN].jsonl |
Error / Fatal |
Same as above | Never deleted by age or count |
The two sub-logger filters are mutually exclusive so errors are never duplicated into routine logs. Both sinks set retainedFileCountLimit: null; the routine sink sets retainedFileTimeLimit to 14 days while the error sink sets no time limit so default count caps never delete older errors. Calendar days follow host local time. Expired files are pruned when the sink opens or rolls; no background cleanup runs while stopped. A single event may push a file slightly past 10 MiB (10 * 1024 * 1024 bytes) before the next event triggers a size roll—the threshold is not a hard per-event truncation cap.
Routine connection failures, registration rejections, P2P probe fallbacks, and reconnects remain Warning; configuration validation/save failures and unexpected host termination log Error/Fatal. The errorType field in operational diagnostics is phase metadata and does not promote diagnostics entries into permanently retained runtime Error logs.
3. Paths, Startup, and Deployment
| Scenario | Runtime Log Directory |
|---|---|
| Agent | logs/ next to the config file; standard Windows install uses C:\ProgramData\RelayLink\Agent\logs |
| Server default | logs/ next to the config file |
| Server custom | --log-directory <dir>; relative paths resolve against the working directory |
| Linux Server systemd / Docker | Templates target /var/lib/relaylink/logs |
| Docker host | .local/docker-server/data/logs by default, persisted on the data volume |
The service account writes to the log directory; Windows inherits parent directory ACLs, and Unix sets 0700. When Server uses a custom directory, permissions must be granted beforehand—see Linux Deployment. Program installation directories are never used for logs. Agent upgrades, reconfigurations, and uninstalls preserve logs/; Server upgrades and restarts preserve the configured data directory, leaving manual archiving and cleanup to operators.
Normal startup initializes logging before reading configuration so configuration validation errors are captured. --check-config and Agent fingerprint inspection (--show-e2e-fingerprint) do not create runtime log files. After calling AddWindowsService / UseWindowsService, default logging providers are cleared before registering AddSerilog so Windows Event Log sources are not auto-registered. The Agent local web host reuses the process ILoggerFactory and does not add a separate console logger.
The File sink uses synchronous, unbuffered per-event flushing without an async queue. Unhandled host exceptions are caught at top level and logged as Fatal, and clean shutdown disposes and flushes the logger. Persistence of the final entry cannot be guaranteed across kill -9, power loss, or disk failure because per-event flush is not a per-event fsync. Serilog SelfLog writes to stderr for sink diagnostics, and stderr is the only fallback if the log directory itself cannot be created. docker compose logs and journalctl are intended primarily for these bootstrap diagnostics; routine operational events live in the JSONL files.
4. Control Rejection Protocol and Diagnostics
ErrorMessage retains its numeric code field and adds an optional numeric reason field (omitted when unset). The wire protocol remains backward-compatible with v3 (shared across v3/v4/v5), and existing error codes are not renumbered. Example error payload (synthetic, no real deployment data):
{"code":0,"reason":5}
This example represents AuthFailed / IdentityMismatch. Reason values are defined below; human-readable client descriptions come from local Describe(), never from remote free-form text.
| reason | Identifier | Meaning | Mapped code |
|---|---|---|---|
| 1 | ClientNotFound |
Client ID is not registered | AuthFailed |
| 2 | ClientDisabled |
Client is disabled | AuthFailed |
| 3 | InvalidSecret |
Secret format or value is invalid | AuthFailed |
| 4 | IdentityInvalid |
Identity fingerprint is missing or invalid | AuthFailed |
| 5 | IdentityMismatch |
Fingerprint mismatches pinned identity | AuthFailed |
| 6 | DuplicateSession |
Another control session is active for this ID | DuplicateSession |
| 7 | InvalidFirstFrame |
First control frame is not Register |
ProtocolError |
| 8 | ConfigurationMismatch |
Acknowledged session or digest does not match | ConfigurationMismatch |
| 9 | ClientConfigurationChanged |
Client config changed during registration | AuthFailed |
| 10 | AuthenticationFailed |
Unified unauthenticated rejection reason | AuthFailed |
The Server validates the client and secret before checking identity or session occupancy; finer rejection codes never bypass authentication, identity pinning, or capacity limits. Unknown client, disabled client, and invalid secret remain distinct in Server runtime logs and SQLite audit records, but ToUnauthenticatedWireReason() collapses all three (1, 2, 3) to AuthenticationFailed (10) on the wire before secret verification completes, preventing client ID or enable-state enumeration on the control port. Identity, duplicate-session, and configuration-acknowledgement failures occur after secret verification and return their specific reasons. Server logs include the detailed reason, error code, control-character-filtered and length-bounded client ID, and source IP; audit records emit agent_session_rejected. Audit reasonCode values stay lowercase (e.g., identity_mismatch, duplicate_session, authentication_failed for InvalidSecret, client_not_found, and client_disabled).
If the management dashboard binds a non-loopback address, Server logs an Error prefixed with SECURITY: on startup and mirrors it to stderr, without including passwords or session cookies.
The Agent parses Error frames during registration, configuration acknowledgement, and the online control read loop. AgentPermanentException preserves both ErrorCode and RejectionReason; the Warning event logs both values, the exception message includes the stage and fixed local description, and the outer logging scope preserves profileId and clientId. Explicit rejections enter slow permanent-error retry backoff without disrupting other configured server profiles.
Compatibility and failure rules:
- A new Agent receiving a legacy frame preserves
code, reports that no reason was provided, and advises checking Server audit logs; legacy clients ignore the new JSON field under existing deserialization rules. - Unknown
reasonvalues map to an unrecognized-reason message; unknowncodevalues fall back toProtocolError; payload parse failure yields a fixed error without attaching remote payload bytes or parser exception text. - Submitted or expected secrets, fingerprints, and local stack traces are never echoed on the wire.
- When TLS is not yet established, frame headers are invalid, or pre-authentication quotas are saturated, an
Errorframe cannot be sent. On pre-auth saturation, the Server closes the socket immediately and logsCapacityExceededwithunauthenticated_connection_limit; the Agent surfaces its local network/TLS/protocol exception.
Operational troubleshooting steps are covered in Installation and Usage Guide.
5. Operational Diagnostics and Sensitive-Data Boundaries
Agent operational diagnostics are written to state/<profileId>/relaylink-diagnostics.jsonl with UTC timestamp (timestampUtc), profileId, clientId, connectionId, channelId, phase, bidirectional byte counts (toServerBytes, toTargetBytes), elapsedMs, idle durations (idleToServerMs, idleToTargetMs), and errorType. When the file reaches 4 MiB, it moves to .1 (overwriting any prior .1). Writes are serialized with a per-instance semaphore, and IOException / UnauthorizedAccessException are suppressed so diagnostics never interrupt business traffic. This file does not record control registration rejections and does not provide permanent error archival.
Runtime logs, Error frames, and operational diagnostics must never record credentials, tokens, full configuration snapshots, CA PEM bodies, private keys, HTTP request bodies, SQL text, TCP/UDP application payloads, ICE credentials, or STUN candidate details. Local Agent save failures log only the filesystem exception and profileId, returning a generic HTTP 500. Per-Data-frame or per-UDP-datagram runtime logging is prohibited; file logs never replace SQLite audit/traffic queries, and no log export endpoint is exposed.
6. Verification and Open Items
Automated tests cover level-split routing, scope and exception enrichment, pruning of expired routine logs, retention of historical error logs, size rolling and restart append, rejection reasons and safe fallbacks, real Server-process rejections recorded to Agent files, config save errors, startup errors, and zero side effects during --check-config. Test size thresholds may be lowered to trigger rolling, while production defaults remain 10 MiB.
Current build versions, test counts, and execution environments are tracked in Verification Status. Cross-platform service account permissions, configuration changes racing mid-registration, cross-version legacy binaries, and production upgrade rollouts remain partially unverified and are not claimed as complete.