using System; using System.IO; using System.Text; namespace KellyReport_D.Utils { internal static class FileLogger { private static readonly object _sync = new object(); private static string LogDirectory => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "KellyReport", "logs"); private static string GetLogFilePath() { string fileName = $"kellyreport_{DateTime.Now:yyyyMMdd}.log"; return Path.Combine(LogDirectory, fileName); } private static void WriteInternal(string level, string message, Exception ex = null) { try { lock (_sync) { Directory.CreateDirectory(LogDirectory); var path = GetLogFilePath(); using (var sw = new StreamWriter(path, true, Encoding.UTF8)) { sw.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}"); if (ex != null) { sw.WriteLine(ex.ToString()); } } } } catch { // 日志写入不应影响主流程,忽略任何异常 } } public static void Info(string message) => WriteInternal("INFO", message); public static void Debug(string message) => WriteInternal("DEBUG", message); public static void Error(string message, Exception ex = null) => WriteInternal("ERROR", message, ex); } }