Selaa lähdekoodia

ref: 初步完成新 Logger

龙腾猫跃 5 kuukautta sitten
vanhempi
sitoutus
0e672597f8
3 muutettua tiedostoa jossa 13 lisäystä ja 19 poistoa
  1. 9 7
      Shared/General/Logger.cs
  2. 0 8
      Shared/Main.cs
  3. 4 4
      Shared/Utils/FileUtils.cs

+ 9 - 7
Shared/General/Logger.cs

@@ -60,18 +60,18 @@ public static class Logger {
     public static BaseLogger Instance { get; set; } = new();
     public static BaseLogger Instance { get; set; } = new();
 
 
     // 转发给实例的方法调用
     // 转发给实例的方法调用
+
     public static void Log(string message, LogLevels level = LogLevels.Info, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "")
     public static void Log(string message, LogLevels level = LogLevels.Info, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "")
         => Instance.Log(message, level, behavior, 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 = "")
     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);
         => Instance.Log(ex, message, level, behavior, filePath);
+
+    public static void Trace(Func<string> 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(string message, LogBehaviors behavior = LogBehaviors.None, [CallerFilePath] string filePath = "") => Log(message, LogLevels.Trace, behavior, filePath);
-    public static void Trace(Func<string> 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 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 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 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);
     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 {
     /// 格式化日志文本。
     /// 格式化日志文本。
     /// </summary>
     /// </summary>
     protected virtual string Format(string text, LogLevels level, string filePath, Exception? ex) {
     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
         return text
             .ReplaceLineEndings("\n", mergeMultiple: true).Split(['\n'], StringSplitOptions.RemoveEmptyEntries)
             .ReplaceLineEndings("\n", mergeMultiple: true).Split(['\n'], StringSplitOptions.RemoveEmptyEntries)
             .Select(t => prefix + t)
             .Select(t => prefix + t)
@@ -174,6 +174,7 @@ public class FileLogger : BaseLogger {
     public FileLogger(string logFolder, string fileNamePrefix = "Log", string fileNameSuffix = ".txt") {
     public FileLogger(string logFolder, string fileNamePrefix = "Log", string fileNameSuffix = ".txt") {
         var thread = new Thread(() => {
         var thread = new Thread(() => {
             // 轮转日志文件,将 Log1.txt 留空
             // 轮转日志文件,将 Log1.txt 留空
+            Logger.Info("日志初始化开始");
             try {
             try {
                 for (int i = 4; i >= 1; i--) {
                 for (int i = 4; i >= 1; i--) {
                     string newerFile = Path.Combine(logFolder, $"{fileNamePrefix}{i + 1}{fileNameSuffix}");
                     string newerFile = Path.Combine(logFolder, $"{fileNamePrefix}{i + 1}{fileNameSuffix}");
@@ -191,6 +192,7 @@ public class FileLogger : BaseLogger {
             try {
             try {
                 writer = new StreamWriter(PathUtils.WithLongPath(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true };
                 writer = new StreamWriter(PathUtils.WithLongPath(Path.Combine(logFolder, $"{fileNamePrefix}1{fileNameSuffix}")), append: true) { AutoFlush = true };
                 writerAvaliable = true;
                 writerAvaliable = true;
+                Logger.Info("日志初始化成功");
                 while (true) {
                 while (true) {
                     queuedEvent.WaitOne();
                     queuedEvent.WaitOne();
                     Flush();
                     Flush();

+ 0 - 8
Shared/Main.cs

@@ -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;
-    }
-
-}

+ 4 - 4
Shared/Utils/FileUtils.cs

@@ -27,7 +27,7 @@ public static class FileUtils {
     /// </summary>
     /// </summary>
     public static void Write(string filePath, byte[] content) {
     public static void Write(string filePath, byte[] content) {
         DirectoryUtils.Create(filePath, isFilePath: true);
         DirectoryUtils.Create(filePath, isFilePath: true);
-        Logger.Trace($"写入文件:{filePath}({content.Length} 字节)");
+        Logger.Trace(() => $"写入文件:{filePath}({content.Length} 字节)");
         File.WriteAllBytes(PathUtils.WithLongPath(filePath), content);
         File.WriteAllBytes(PathUtils.WithLongPath(filePath), content);
     }
     }
 
 
@@ -39,7 +39,7 @@ public static class FileUtils {
     public static void Write(string filePath, Stream stream) {
     public static void Write(string filePath, Stream stream) {
         using FileStream fileStream = CreateAsStream(PathUtils.WithLongPath(filePath));
         using FileStream fileStream = CreateAsStream(PathUtils.WithLongPath(filePath));
         if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
         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);
         stream.CopyTo(fileStream);
     }
     }
 
 
@@ -155,7 +155,7 @@ public static class FileUtils {
     /// </summary>
     /// </summary>
     public static ZipArchive OpenZip(string zipFilePath) {
     public static ZipArchive OpenZip(string zipFilePath) {
         ZipArchive TryOpen(Encoding encoding) {
         ZipArchive TryOpen(Encoding encoding) {
-            Logger.Trace($"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}");
+            Logger.Trace(() => $"尝试以 {encoding.EncodingName} 编码打开压缩包:{zipFilePath}");
             var result = ZipFile.Open(PathUtils.WithLongPath(zipFilePath), ZipArchiveMode.Read, encoding);
             var result = ZipFile.Open(PathUtils.WithLongPath(zipFilePath), ZipArchiveMode.Read, encoding);
             try {
             try {
                 _ = result.Entries; // 如果编码有误,会在这里抛出 DecoderFallbackException;如果文件异常,会在这里抛出 InvalidDataException
                 _ = result.Entries; // 如果编码有误,会在这里抛出 DecoderFallbackException;如果文件异常,会在这里抛出 InvalidDataException
@@ -251,7 +251,7 @@ public static class FileUtils {
         DirectoryUtils.Create(outputFullPath, isFilePath: true);
         DirectoryUtils.Create(outputFullPath, isFilePath: true);
         FileUtils.Delete(outputFullPath);
         FileUtils.Delete(outputFullPath);
         using var archive = ZipFile.Open(outputFullPath, ZipArchiveMode.Create);
         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);
         foreach (var pair in sources) archive.CreateEntryFromFile(PathUtils.WithLongPath(pair.Value), pair.Key.Replace('\\', '/'), CompressionLevel.Optimal);
     }
     }