feat: 优化异常处理,新增日志记录
This commit is contained in:
36
Logger.cs
Normal file
36
Logger.cs
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user