基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-02 b4858d19fbad69810d211270bc5b280bf9909ea5
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
    };
}