KellyReport_D/Utils/FileLogger.cs
earo.lau f839573712 自动生成客户/产品年度统计,新增日志功能
- 新增 FileLogger 日志工具类,增强异常记录
- 自动生成“客户年度预估”“产品年度销量统计”表
- 升级版本号至 1.0.0.7
2025-12-30 01:05:26 +08:00

48 lines
1.6 KiB
C#

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