using MailSharp.MailClient.Models; using Microsoft.Extensions.Options; namespace MailSharp.MailClient.Services.Logging; // Keeps App_Data/logs.db from growing unbounded - prunes on startup and then periodically, rather // than capping the collection size, so retention is time-based (predictable for someone reading // the Maintenance log viewer) instead of silently dropping whichever entries happen to be oldest // once some row-count limit is hit. public class LogPruningService(ILogStore logStore, IOptions mailSettings, ILogger logger) : BackgroundService { private static readonly TimeSpan PruneInterval = TimeSpan.FromHours(6); protected override async Task ExecuteAsync(CancellationToken stoppingToken) { Prune(); using var timer = new PeriodicTimer(PruneInterval); while (await timer.WaitForNextTickAsync(stoppingToken)) { Prune(); } } private void Prune() { try { var retentionDays = Math.Max(1, mailSettings.Value.LogRetentionDays); logStore.PruneOlderThan(DateTime.UtcNow.AddDays(-retentionDays)); } catch (Exception ex) { logger.LogWarning(ex, "Log pruning failed"); } } }