Reputation: 100
I want to compress the rotated logs, and if the number of rotated logs exceeds the limit, delete the old ones. Already checked the serilog-sinks-file-archive. It does a great job of compressing, but it doesn't delete previous files.
Upvotes: 1
Views: 1964
Reputation: 726
Appreciate this is an old post so hoping you've solved the challenge by now. You didn't share any detail on what you've tried but in the interest of helping you if you don't already have a solution...
You can implement two simple methods:
SerilogHousekeeping
the entry point that gathers all files in the target directorypublic void SerilogHousekeeping(string filePath, string searchPattern, bool includeSubDirectories, int retentionPeriod)
{
if (!includeSubDirectories)
{
var files = Directory.GetFiles(filePath, searchPattern).ToList();
CheckAndDeleteFiles(files, retentionPeriod);
}
else
{
foreach (var subDirectory in Directory.GetDirectories(filePath))
{
var files = Directory.GetFiles(subDirectory, searchPattern).ToList();
CheckAndDeleteFiles(files, retentionPeriod);
}
}
}
CheckAndDeleteFiles
that checks if a given file is outside the retention period and, if so, attempts to delete itprivate void CheckAndDeleteFiles(List<string> files, int retentionPeriod)
{
foreach (var filename in files)
{
if (DateTime.UtcNow - File.GetCreationTimeUtc(filename) >= TimeSpan.FromDays(retentionPeriod))
{
try
{
File.Delete(filename);
}
catch ()
{
// Handle your exception here
}
}
}
}
SerilogHousekeeping()
at whatever place is appropriate for your application (e.g. before you configure Serilog.Log.Logger
in your startup). For example, to remove all .txt
files that are over 60 days old in the relative Logs
directory (not recursive) then call:SerilogHousekeeping(Path.Combine(Directory.GetCurrentDirectory(), $"Logs"), "*.txt", false, 60)
Upvotes: 2