53 lines
1.5 KiB
C#
53 lines
1.5 KiB
C#
using System.IO;
|
|
using UtopiaCanteenSystem.Services.Logging;
|
|
|
|
namespace UtopiaCanteenSystem.Services;
|
|
|
|
public static class Logger
|
|
{
|
|
public static void Log(Exception ex, string context = "")
|
|
{
|
|
try
|
|
{
|
|
if (ex == null)
|
|
return;
|
|
|
|
if (FileLogger.IsConfigured)
|
|
{
|
|
FileLogger.Error(context, ex.Message, ex);
|
|
return;
|
|
}
|
|
|
|
WriteLegacyErrorLog(ex, context);
|
|
}
|
|
catch
|
|
{
|
|
// never throw from logger
|
|
}
|
|
}
|
|
|
|
private static void WriteLegacyErrorLog(Exception ex, string context)
|
|
{
|
|
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
|
var logsDir = Path.Combine(localAppData, "UtopiaCanteenSystem", "Logs");
|
|
var logFile = Path.Combine(logsDir, "error.log");
|
|
|
|
if (!Directory.Exists(logsDir))
|
|
Directory.CreateDirectory(logsDir);
|
|
|
|
var lines = new List<string>
|
|
{
|
|
$"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}]",
|
|
string.IsNullOrWhiteSpace(context) ? string.Empty : $"Context: {context}",
|
|
$"Message: {ex.Message}",
|
|
$"StackTrace: {ex.StackTrace}"
|
|
};
|
|
if (ex.InnerException != null)
|
|
lines.Add($"InnerException: {ex.InnerException.Message}");
|
|
lines.Add("----------------------------------------------------");
|
|
|
|
File.AppendAllText(logFile, string.Join(Environment.NewLine, lines.Where(l => !string.IsNullOrEmpty(l))) + Environment.NewLine);
|
|
}
|
|
}
|
|
|