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 _entries = []; private readonly ILogger _logger; private readonly string _logFile; public DiagnosticsService(DesktopPaths paths, ILogger 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? properties = null) { var entry = new DiagnosticEntry { Severity = severity, Code = code, Message = message, Properties = properties ?? new Dictionary() }; _logger.Log(MapLevel(severity), "{Code}: {Message}", code, message); lock (_gate) { _entries.Add(entry); AppendLog(entry); } return entry; } public IReadOnlyList 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}")); } try { File.AppendAllText(_logFile, line + Environment.NewLine, Encoding.UTF8); } catch (IOException) { _logger.LogWarning("Failed to append diagnostic log file because it is currently unavailable."); } catch (UnauthorizedAccessException) { _logger.LogWarning("Failed to append diagnostic log file because access was denied."); } } 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 }; }