Class LogFileSink

The bounded queue, the single background writer, the rolling file and its retention policy.

Inheritance
LogFileSink
Implements
Namespace: MOSAIC.Diagnostics
Assembly: MOSAIC.dll
Syntax
internal sealed class LogFileSink : IAsyncDisposable
Remarks

Owned entirely by Log; nothing else constructs one. The split matters: everything a producer pays for lives in TryEnqueue(in LogEntry), and everything expensive - formatting a line, touching the disk, rotating, deleting old files - happens on one background task.

The channel is bounded and drops the OLDEST entry on overflow. Dropping the newest would hide exactly the burst that caused the overflow, and blocking the producer would stall an EMG data thread on disk I/O, which is the one thing this design must never do. Drops are counted and reported into the log itself, so an overflow is visible rather than silent.

Shape (channel, one writer task, batched drain, timed flush) is copied from Components/Basics/CsvDumper.cs, which already solves the same problem for recording.

Constructors

LogFileSink(string)

Opens the first file and starts the writer task. Never throws.

Declaration
internal LogFileSink(string directory)
Parameters
Type Name Description
string directory

Folder to write into. Must already exist.

Fields

DropReportIntervalMs

Declaration
private const int DropReportIntervalMs = 1000
Field Value
Type Description
int

FileEncoding

Declaration
private static readonly UTF8Encoding FileEncoding
Field Value
Type Description
UTF8Encoding

FlushIntervalMs

Longest a written line may sit unflushed.

Declaration
internal const int FlushIntervalMs = 250
Field Value
Type Description
int

MaxFileBytes

File size at which the writer rolls over to the next file.

Declaration
internal const long MaxFileBytes = 8388608
Field Value
Type Description
long

MaxRetainedFiles

Log files kept in the folder; older ones are deleted when a new run starts.

Declaration
internal const int MaxRetainedFiles = 10
Field Value
Type Description
int

MaxWriterRestarts

Declaration
private const int MaxWriterRestarts = 3
Field Value
Type Description
int

NewLineByteCount

Declaration
private static readonly int NewLineByteCount
Field Value
Type Description
int

QueueCapacity

Entries buffered before the oldest starts being dropped.

Declaration
internal const int QueueCapacity = 4096
Field Value
Type Description
int

WriterRestartDelayMs

Declaration
private const int WriterRestartDelayMs = 500
Field Value
Type Description
int

_baseName

Declaration
private readonly string _baseName
Field Value
Type Description
string

_bytesWritten

Declaration
private long _bytesWritten
Field Value
Type Description
long

_channel

Declaration
private readonly Channel<LogEntry> _channel
Field Value
Type Description
Channel<LogEntry>

_cts

Declaration
private readonly CancellationTokenSource _cts
Field Value
Type Description
CancellationTokenSource

_currentPath

Declaration
private volatile string? _currentPath
Field Value
Type Description
string

_directory

Declaration
private readonly string _directory
Field Value
Type Description
string

_disposed

Declaration
private int _disposed
Field Value
Type Description
int

_dropped

Declaration
private long _dropped
Field Value
Type Description
long

_fileGate

Declaration
private readonly SemaphoreSlim _fileGate
Field Value
Type Description
SemaphoreSlim

_lastDropReportTicks

Declaration
private long _lastDropReportTicks
Field Value
Type Description
long

_lastFlushTicks

Declaration
private long _lastFlushTicks
Field Value
Type Description
long

_reportedDropped

Declaration
private long _reportedDropped
Field Value
Type Description
long

_ring

Declaration
private readonly LogRing _ring
Field Value
Type Description
LogRing

_rotation

Declaration
private int _rotation
Field Value
Type Description
int

_stream

Declaration
private FileStream? _stream
Field Value
Type Description
FileStream

_unflushed

Declaration
private int _unflushed
Field Value
Type Description
int

_writer

Declaration
private StreamWriter? _writer
Field Value
Type Description
StreamWriter

_writerStopped

Declaration
private int _writerStopped
Field Value
Type Description
int

_writerTask

Declaration
private readonly Task _writerTask
Field Value
Type Description
Task

Properties

CurrentPath

Path of the file currently being appended to, or null if none could be opened.

Declaration
internal string? CurrentPath { get; }
Property Value
Type Description
string

Dropped

Entries the queue has dropped because it was full.

Declaration
internal long Dropped { get; }
Property Value
Type Description
long

WriterStopped

True once the writer task has given up: the queue is no longer being drained, so nothing new reaches the log file until the next Initialize(). The ring and the panel do keep filling - Log treats a stopped writer as a refusal and routes the entry to the ring instead. Surfaced to the UI as WriterStopped.

Declaration
internal bool WriterStopped { get; }
Property Value
Type Description
bool

Methods

Close()

Declaration
private void Close()

DisposeAsync()

Stops the writer, drains what is left and closes the file. Never throws.

Declaration
public ValueTask DisposeAsync()
Returns
Type Description
ValueTask

DrainLoop()

Declaration
private Task DrainLoop()
Returns
Type Description
Task

FlushCritical(TimeSpan)

Drains the queue and flushes the file on the CALLING thread, giving up after timeout rather than deadlocking a dying process.

Declaration
internal void FlushCritical(TimeSpan timeout)
Parameters
Type Name Description
TimeSpan timeout

How long to wait for the writer to release the file.

Remarks

Deliberately independent of the writer task: when the crash being logged is the writer's own, the lines describing it must still reach disk.

FlushFile()

Declaration
private void FlushFile()

GuardedFlushAsync()

Declaration
private Task GuardedFlushAsync()
Returns
Type Description
Task

Open()

Declaration
private void Open()

Prune(int)

Deletes the oldest files until at most keep remain.

Declaration
private void Prune(int keep)
Parameters
Type Name Description
int keep

ReportDrops()

Turns a full queue into a visible line rather than a silent gap. Caller holds the file gate.

Declaration
private void ReportDrops()

ReportInternalFailure(Exception)

The logger's own failure path. It must never call Log's write path: a disk failure would then log an error, which would fail, which would log an error. NoteInternalFailure(string, Exception) only stores a counter and a string.

Declaration
private static void ReportInternalFailure(Exception ex)
Parameters
Type Name Description
Exception ex

ReportInternalFailure(string)

The logger's own failure path. It must never call Log's write path: a disk failure would then log an error, which would fail, which would log an error. NoteInternalFailure(string, Exception) only stores a counter and a string.

Declaration
private static void ReportInternalFailure(string detail)
Parameters
Type Name Description
string detail

Rotate()

Declaration
private void Rotate()

TryEnqueue(in LogEntry)

Hands an entry to the writer. One non-blocking channel write and nothing else - no lock, no allocation, no disk - which is what makes it safe to call from inside a device lock on a notification thread.

Declaration
internal bool TryEnqueue(in LogEntry entry)
Parameters
Type Name Description
LogEntry entry

The entry to write.

Returns
Type Description
bool

False only once the sink has been shut down.

WriteBacklog(LogEntry[], int)

Appends entries captured before this sink existed. File only: Log has already put them in the ring, and adding them again would show the panel every line twice.

Declaration
internal void WriteBacklog(LogEntry[] entries, int count)
Parameters
Type Name Description
LogEntry[] entries

Buffered entries, oldest first.

int count

How many leading elements of entries to write.

WriteEntry(in LogEntry)

Writes one entry to the ring and the file. Caller holds the file gate.

Declaration
private void WriteEntry(in LogEntry entry)
Parameters
Type Name Description
LogEntry entry

WriteLine(in LogEntry)

Writes one entry to the file only. Caller holds the file gate.

Declaration
private void WriteLine(in LogEntry entry)
Parameters
Type Name Description
LogEntry entry

WriterLoop()

Runs the drain continuously. Transient faults are retried; a persistent fault leaves WriterStopped set and records a description in LastInternalError.

Declaration
private Task WriterLoop()
Returns
Type Description
Task

Implements

IAsyncDisposable

Search documentation

Start typing to search the documentation.