Sfoglia il codice sorgente

feat(log): 新增FileLogger静态文件日志器 + csproj排除Logs/TestData

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
huangjie 1 settimana fa
parent
commit
a354b79e8a
2 ha cambiato i file con 50 aggiunte e 0 eliminazioni
  1. 2 0
      AutoFocusTool.csproj
  2. 48 0
      Logging/FileLogger.cs

+ 2 - 0
AutoFocusTool.csproj

@@ -23,6 +23,8 @@
     <Compile Remove="HScan\**\*.cs" />
     <Compile Remove="ToPng\**\*.cs" />
     <Compile Remove="WellSpacing\**\*.cs" />
+    <Compile Remove="Logs\**\*.cs" />
+    <Compile Remove="TestData\**\*.cs" />
     <Compile Remove="bin\**\*.cs" />
     <Compile Remove="obj\**\*.cs" />
     <Page Remove="SelfTest\**" />

+ 48 - 0
Logging/FileLogger.cs

@@ -0,0 +1,48 @@
+using System;
+using System.IO;
+
+namespace AutoFocusTool.Logging
+{
+    /// <summary>
+    /// 静态文件日志器:程序启动时按时间戳建一个文件,本次运行所有日志写入它。
+    /// 线程安全(lock),每条 flush。格式:HH:mm:ss.fff  [级别]  [类别]  消息
+    /// </summary>
+    public static class FileLogger
+    {
+        private static readonly object _lock = new object();
+        private static string _path;
+
+        /// <summary>启动时调用一次:在 Logs/ 下建 yyyy-MM-dd_HHmmss.log。</summary>
+        public static void Init()
+        {
+            lock (_lock)
+            {
+                if (_path != null) return;
+                string dir = @"C:\claudeFile\TL\AutoFocusTool\Logs";
+                Directory.CreateDirectory(dir);
+                _path = Path.Combine(dir, $"{DateTime.Now:yyyy-MM-dd_HHmmss}.log");
+                Write("INFO", "APP", "==== 日志开始 ====");
+            }
+        }
+
+        public static void Info(string category, string msg) => Write("INFO", category, msg);
+        public static void Action(string category, string msg) => Write("ACTION", category, msg);
+        public static void Data(string category, string msg) => Write("DATA", category, msg);
+        public static void Warn(string category, string msg) => Write("WARN", category, msg);
+        public static void Error(string category, string msg) => Write("ERROR", category, msg);
+
+        private static void Write(string level, string category, string msg)
+        {
+            try
+            {
+                lock (_lock)
+                {
+                    if (_path == null) return;   // 未 Init 则静默丢弃
+                    string line = $"{DateTime.Now:HH:mm:ss.fff}  [{level,-6}] [{category,-6}] {msg}";
+                    File.AppendAllText(_path, line + Environment.NewLine);
+                }
+            }
+            catch { /* 日志失败不能影响主流程 */ }
+        }
+    }
+}