Code
·
37 lines
·
1165 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37using 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> mailSettings, ILogger<LogPruningService> 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");
}
}
}