From 4df6165fa93c7caeea86385312415e312de4d11f Mon Sep 17 00:00:00 2001
From: Moli <13026959681@163.com>
Date: 星期二, 05 五月 2026 01:10:39 +0800
Subject: [PATCH] 暂存
---
src/Moli.Desktop/Diagnostics/DailyFileLoggerProvider.cs | 79 +++++++++++++++++++++++++++++++++++++++
1 files changed, 79 insertions(+), 0 deletions(-)
diff --git a/src/Moli.Desktop/Diagnostics/DailyFileLoggerProvider.cs b/src/Moli.Desktop/Diagnostics/DailyFileLoggerProvider.cs
new file mode 100644
index 0000000..7a0f9fd
--- /dev/null
+++ b/src/Moli.Desktop/Diagnostics/DailyFileLoggerProvider.cs
@@ -0,0 +1,79 @@
+using System.IO;
+using System.Text;
+using Microsoft.Extensions.Logging;
+
+namespace Moli.Desktop.Diagnostics;
+
+public sealed class DailyFileLoggerProvider : ILoggerProvider
+{
+ private readonly string _logDirectory;
+ private readonly object _gate = new();
+ private bool _disposed;
+
+ public DailyFileLoggerProvider(string logDirectory)
+ {
+ _logDirectory = logDirectory;
+ Directory.CreateDirectory(_logDirectory);
+ }
+
+ public ILogger CreateLogger(string categoryName)
+ => new DailyFileLogger(categoryName, _logDirectory, _gate, () => _disposed);
+
+ public void Dispose()
+ {
+ _disposed = true;
+ }
+
+ private sealed class DailyFileLogger(
+ string categoryName,
+ string logDirectory,
+ object gate,
+ Func<bool> isDisposed) : ILogger
+ {
+ public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel)
+ => logLevel != LogLevel.None && !isDisposed();
+
+ public void Log<TState>(
+ LogLevel logLevel,
+ EventId eventId,
+ TState state,
+ Exception? exception,
+ Func<TState, Exception?, string> formatter)
+ {
+ if (!IsEnabled(logLevel))
+ {
+ return;
+ }
+
+ var message = formatter(state, exception);
+ if (string.IsNullOrWhiteSpace(message) && exception is null)
+ {
+ return;
+ }
+
+ var now = DateTimeOffset.Now;
+ var line = $"{now:O} [{logLevel}] {categoryName} {message}";
+ if (exception is not null)
+ {
+ line += $" {exception.GetType().Name}: {exception.Message}";
+ }
+
+ var path = Path.Combine(logDirectory, $"moli-desktop-{now:yyyyMMdd}.log");
+ try
+ {
+ lock (gate)
+ {
+ File.AppendAllText(path, line + Environment.NewLine, Encoding.UTF8);
+ }
+ }
+ catch (IOException)
+ {
+ }
+ catch (UnauthorizedAccessException)
+ {
+ }
+ }
+ }
+}
--
Gitblit v1.9.1