namespace VanDerHeijden.Logging.File;
///
/// Writes batches of log messages to a daily rotating text file.
/// A new file is opened automatically whenever the calendar date changes.
///
///
/// Directory in which log files are created. Defaults to "Logs".
/// Files follow the naming pattern log-yyyyMMdd.txt.
///
public sealed class FileLogWriter(string logDirectory = "Logs") : IBatchedLogWriter
{
private StreamWriter? writer;
private DateTime currentDate = DateTime.MinValue;
///
/// Appends all messages in the batch to the current day's log file.
/// If the date has changed since the last write, the previous file is closed
/// and a new one is opened.
///
/// The pre-formatted log lines to write.
/// A token that can cancel the operation.
public async Task WriteBatchAsync(List messages, CancellationToken ct)
{
var today = DateTime.Today;
if (writer == null || today != currentDate)
{
await DisposeAsync();
currentDate = today;
Directory.CreateDirectory(logDirectory);
var stream = new FileStream(
Path.Combine(logDirectory, $"log-{today:yyyyMMdd}.txt"),
FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 65536, useAsync: true);
writer = new StreamWriter(stream) { AutoFlush = false };
}
foreach (var msg in messages)
await writer.WriteAsync(msg.AsMemory(), ct);
await writer.FlushAsync(ct);
}
///
/// Flushes and closes the current log file, releasing all file handles.
///
public async ValueTask DisposeAsync()
{
if (writer == null) return;
try { await writer.FlushAsync(); await writer.DisposeAsync(); }
catch { }
finally { writer = null; }
}
}