39 lines
1.9 KiB
C#
39 lines
1.9 KiB
C#
using System.Text;
|
|
namespace Ads.Desktop;
|
|
public sealed class DailyLog
|
|
{
|
|
readonly string folder; readonly object gate = new(); DateTime cleanedDate;
|
|
public string Folder => folder;
|
|
public DailyLog(string path) => folder = path;
|
|
public void Write(string message)
|
|
{
|
|
lock (gate)
|
|
{
|
|
try
|
|
{
|
|
Directory.CreateDirectory(folder); var now = DateTime.Now; var name = $"ads-{now:yyyy-MM-dd}";
|
|
if (cleanedDate != now.Date)
|
|
{
|
|
foreach (var file in Directory.EnumerateFiles(folder, "ads-*.log"))
|
|
{
|
|
var text = Path.GetFileName(file);
|
|
if (System.Text.RegularExpressions.Regex.IsMatch(text, @"^ads-\d{4}-\d{2}-\d{2}(\.[1-4])?\.log$") && DateTime.TryParseExact(text.Substring(4, 10), "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out var date) && date < now.Date.AddDays(-13)) File.Delete(file);
|
|
}
|
|
cleanedDate = now.Date;
|
|
}
|
|
var path = Path.Combine(folder, name + ".log");
|
|
if (File.Exists(path) && new FileInfo(path).Length >= 5 * 1024 * 1024)
|
|
{
|
|
var oldest = Path.Combine(folder, name + ".4.log"); if (File.Exists(oldest)) File.Delete(oldest);
|
|
for (var i = 3; i >= 1; i--) { var old = Path.Combine(folder, $"{name}.{i}.log"); if (File.Exists(old)) File.Move(old, Path.Combine(folder, $"{name}.{i + 1}.log")); }
|
|
File.Move(path, Path.Combine(folder, name + ".1.log"));
|
|
}
|
|
if (message.Length > 16384) message = message[..16384] + " [truncated]";
|
|
File.AppendAllText(path, $"{now:O} {message}\n", Encoding.UTF8);
|
|
}
|
|
catch (IOException) { }
|
|
catch (UnauthorizedAccessException) { }
|
|
}
|
|
}
|
|
}
|