using System.Text;
|
using System.IO;
|
using Microsoft.Extensions.Logging;
|
using Moli.Desktop.Host;
|
|
namespace Moli.Desktop.Diagnostics;
|
|
public sealed class DiagnosticsService : IDiagnosticsService
|
{
|
private readonly object _gate = new();
|
private readonly List<DiagnosticEntry> _entries = [];
|
private readonly ILogger<DiagnosticsService> _logger;
|
private readonly string _logFile;
|
|
public DiagnosticsService(DesktopPaths paths, ILogger<DiagnosticsService> logger)
|
{
|
_logger = logger;
|
Directory.CreateDirectory(paths.LogDirectory);
|
_logFile = Path.Combine(paths.LogDirectory, $"moli-desktop-{DateTimeOffset.Now:yyyyMMdd}.log");
|
}
|
|
public DiagnosticEntry Record(
|
DiagnosticSeverity severity,
|
string code,
|
string message,
|
IReadOnlyDictionary<string, string>? properties = null)
|
{
|
var entry = new DiagnosticEntry
|
{
|
Severity = severity,
|
Code = code,
|
Message = message,
|
Properties = properties ?? new Dictionary<string, string>()
|
};
|
|
lock (_gate)
|
{
|
_entries.Add(entry);
|
}
|
|
_logger.Log(MapLevel(severity), "{Code}: {Message}", code, message);
|
AppendLog(entry);
|
return entry;
|
}
|
|
public IReadOnlyList<DiagnosticEntry> Snapshot()
|
{
|
lock (_gate)
|
{
|
return [.. _entries];
|
}
|
}
|
|
private void AppendLog(DiagnosticEntry entry)
|
{
|
var line = $"{entry.Timestamp:O} [{entry.Severity}] {entry.Code} {entry.Message}";
|
if (entry.Properties.Count > 0)
|
{
|
line += " " + string.Join(";", entry.Properties.Select(p => $"{p.Key}={p.Value}"));
|
}
|
|
File.AppendAllText(_logFile, line + Environment.NewLine, Encoding.UTF8);
|
}
|
|
private static LogLevel MapLevel(DiagnosticSeverity severity) => severity switch
|
{
|
DiagnosticSeverity.Info => LogLevel.Information,
|
DiagnosticSeverity.Warning => LogLevel.Warning,
|
DiagnosticSeverity.Error => LogLevel.Error,
|
DiagnosticSeverity.Critical => LogLevel.Critical,
|
_ => LogLevel.Debug
|
};
|
}
|