From 0e672597f8790d3be700e8e3603dc78afe3861d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BE=99=E8=85=BE=E7=8C=AB=E8=B7=83?= <1043137532@qq.com> Date: Wed, 6 May 2026 18:39:42 +0800 Subject: [PATCH] =?UTF-8?q?ref:=20=E5=88=9D=E6=AD=A5=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E6=96=B0=20Logger?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Shared/General/Logger.cs | 16 +++++++++------- Shared/Main.cs | 8 -------- Shared/Utils/FileUtils.cs | 8 ++++---- 3 files changed, 13 insertions(+), 19 deletions(-) delete mode 100644 Shared/Main.cs diff --git a/Shared/General/Logger.cs b/Shared/General/Logger.cs index d8f53a2..18a1f1a 100644 --- a/Shared/General/Logger.cs +++ b/Shared/General/Logger.cs @@ -60,18 +60,18 @@ public static class Logger { public static BaseLogger Instance { get; set; } = new(); // 转发给实例的方法调用 + public static void Log(string message, LogLevels level = LogLevels.Info, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Instance.Log(message, level, behavior, filePath); public static void Log(Exception ex, string? message = null, LogLevels level = LogLevels.Warning, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Instance.Log(ex, message, level, behavior, filePath); + + public static void Trace(Func message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") { if (Instance.MinLevel <= LogLevels.Trace) Log(message(), LogLevels.Trace, behavior, filePath); } public static void Trace(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Trace, behavior, filePath); - public static void Trace(Func message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") { - if (Instance.MinLevel > LogLevels.Trace) return; - Log(message(), LogLevels.Trace, behavior, filePath); - } public static void Info(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Info, behavior, filePath); - public static void Warning(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Warning, behavior, filePath); - public static void Error(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Error, behavior, filePath); + public static void Warning(string message, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Warning, behavior, filePath); + public static void Error(string message, LogBehaviors behavior = LogBehaviors.AlertThenFeedback, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Error, behavior, filePath); + public static void Trace(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Trace, behavior, filePath); public static void Info(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Info, behavior, filePath); public static void Warning(Exception ex, string? message = null, LogBehaviors behavior = LogBehaviors.ToastIfDebug, [CallerFilePath] string filePath = "") => Log(ex, message, LogLevels.Warning, behavior, filePath); @@ -113,7 +113,7 @@ public class BaseLogger { /// 格式化日志文本。 /// protected virtual string Format(string text, LogLevels level, string filePath, Exception? ex) { - string prefix = $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} [{filePath.AfterLast(@"\").BeforeFirst(".")}{(Thread.CurrentThread.Name is null ? "" : $" @ {Thread.CurrentThread.Name}")}] "; + string prefix = $"{DateTime.Now:HH':'mm':'ss'.'fff} {level.ToString().First()} {(Thread.CurrentThread.Name is null ? "" : $"<{Thread.CurrentThread.Name}> ")}[{filePath.AfterLast(@"\").BeforeFirst(".")}] "; return text .ReplaceLineEndings("\n", mergeMultiple: true).Split(['\n'], StringSplitOptions.RemoveEmptyEntries) .Select(t => prefix + t) @@ -174,6 +174,7 @@ public class FileLogger : BaseLogger { public FileLogger(string logFolder, string fileNamePrefix = "Log", string fileNameSuffix = ".txt") { var thread = new Thread(() => { // 轮转日志文件,将 Log1.txt 留空 + Logger.Info("日志初始化开始"); try { for (int i = 4; i >= 1; i--) { string newerFile = Path.Combine(logFolder, $"{fileNamePrefix}{i + 1}{fileNameSuffix}"); @@ -191,6 +192,7 @@ public class FileLogger : BaseLogger { try { writer = new StreamWriter(PathUtils.WithLongPath(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true }; writerAvaliable = true; + Logger.Info("日志初始化成功"); while (true) { queuedEvent.WaitOne(); Flush(); diff --git a/Shared/Main.cs b/Shared/Main.cs deleted file mode 100644 index 077a83e..0000000 --- a/Shared/Main.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace MeloongCore; -public static class Main { - - public static void Initialize(BaseLogger? logger = null) { - if (logger is not null) Logger.Instance = logger; - } - -} diff --git a/Shared/Utils/FileUtils.cs b/Shared/Utils/FileUtils.cs index 34508d5..886b85f 100644 --- a/Shared/Utils/FileUtils.cs +++ b/Shared/Utils/FileUtils.cs @@ -27,7 +27,7 @@ public static class FileUtils { /// public static void Write(string filePath, byte[] content) { DirectoryUtils.Create(filePath, isFilePath: true); - Logger.Trace($"写入文件:{filePath}({content.Length} 字节)"); + Logger.Trace(() => $"写入文件:{filePath}({content.Length} 字节)"); File.WriteAllBytes(PathUtils.WithLongPath(filePath), content); } @@ -39,7 +39,7 @@ public static class FileUtils { public static void Write(string filePath, Stream stream) { using FileStream fileStream = CreateAsStream(PathUtils.WithLongPath(filePath)); if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin); - Logger.Trace($"写入文件:{filePath}({stream.GetType().Name} {stream.Length} 字节)"); + Logger.Trace(() => $"写入文件:{filePath}({stream.GetType().Name} {stream.Length} 字节)"); stream.CopyTo(fileStream); } @@ -155,7 +155,7 @@ public static class FileUtils { /// public static ZipArchive OpenZip(string zipFilePath) { ZipArchive TryOpen(Encoding encoding) { - Logger.Trace($"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}"); + Logger.Trace(() => $"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}"); var result = ZipFile.Open(PathUtils.WithLongPath(zipFilePath), ZipArchiveMode.Read, encoding); try { _ = result.Entries; // 如果编码有误,会在这里抛出 DecoderFallbackException;如果文件异常,会在这里抛出 InvalidDataException @@ -251,7 +251,7 @@ public static class FileUtils { DirectoryUtils.Create(outputFullPath, isFilePath: true); FileUtils.Delete(outputFullPath); using var archive = ZipFile.Open(outputFullPath, ZipArchiveMode.Create); - Logger.Trace($"创建 zip 文件:{sources.Count} 个文件 → {outputFullPath}\n{sources.Select(p => $"- {p.Value} → {p.Key}").Join('\n')}"); + Logger.Trace(() => $"创建 zip 文件:{sources.Count} 个文件 → {outputFullPath}\n{sources.Select(p => $"- {p.Value} → {p.Key}").Join('\n')}"); foreach (var pair in sources) archive.CreateEntryFromFile(PathUtils.WithLongPath(pair.Value), pair.Key.Replace('\\', '/'), CompressionLevel.Optimal); }