54 lines
1.5 KiB
C#
54 lines
1.5 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
namespace UtopiaCanteenSystem.Services;
|
|
|
|
public static class Logger
|
|
{
|
|
private static readonly object _lock = new();
|
|
|
|
public static void Log(Exception ex, string context = "")
|
|
{
|
|
try
|
|
{
|
|
if (ex == null) return;
|
|
|
|
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
|
var appRoot = Path.Combine(localAppData, "UtopiaCanteenSystem");
|
|
var logsDir = Path.Combine(appRoot, "Logs");
|
|
var logFile = Path.Combine(logsDir, "error.log");
|
|
|
|
try
|
|
{
|
|
if (!Directory.Exists(logsDir))
|
|
Directory.CreateDirectory(logsDir);
|
|
}
|
|
catch
|
|
{
|
|
return;
|
|
}
|
|
|
|
var sb = new StringBuilder();
|
|
sb.AppendLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}]");
|
|
if (!string.IsNullOrWhiteSpace(context))
|
|
sb.AppendLine($"Context: {context}");
|
|
sb.AppendLine($"Message: {ex.Message}");
|
|
sb.AppendLine($"StackTrace: {ex.StackTrace}");
|
|
if (ex.InnerException != null)
|
|
sb.AppendLine($"InnerException: {ex.InnerException.Message}");
|
|
sb.AppendLine("----------------------------------------------------");
|
|
|
|
lock (_lock)
|
|
{
|
|
File.AppendAllText(logFile, sb.ToString());
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// never throw from logger
|
|
}
|
|
}
|
|
}
|
|
|