feat: 优化异常处理,新增日志记录

This commit is contained in:
2026-01-19 17:48:49 +08:00
parent 0ab770d464
commit d421b9b72b
3 changed files with 182 additions and 91 deletions

36
Logger.cs Normal file
View File

@@ -0,0 +1,36 @@
using System;
using System.IO;
using System.Text;
namespace TimerApp
{
public static class Logger
{
private static readonly string LogFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "error.log");
private static readonly object LockObj = new object();
public static void LogError(string message, Exception? ex = null)
{
try
{
lock (LockObj)
{
var sb = new StringBuilder();
sb.AppendLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ERROR: {message}");
if (ex != null)
{
sb.AppendLine($"Exception: {ex.Message}");
sb.AppendLine($"StackTrace: {ex.StackTrace}");
}
sb.AppendLine(new string('-', 50));
File.AppendAllText(LogFile, sb.ToString());
}
}
catch
{
// Failed to log, nothing we can do
}
}
}
}