-
Notifications
You must be signed in to change notification settings - Fork 1
/
Logger.cs
88 lines (76 loc) · 2.26 KB
/
Logger.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System.IO;
using System.Text;
public static class Logger
{
private static readonly object lockObj = new();
private static string? logFilePath;
private static string GetLogFilePath()
{
if (logFilePath == null)
{
var fileName = $"toucca-{DateTime.Now:yyyy-MM-dd}.log";
logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
}
return logFilePath;
}
public static void CleanupOldLogFiles()
{
var directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
var oldFiles = directory.GetFiles("toucca-*.log")
.Where(f => f.CreationTime < DateTime.Now.AddDays(-7))
.ToList();
foreach (var file in oldFiles)
{
try
{
file.Delete();
}
catch (Exception ex)
{
Error("Failed to delete log file", ex);
}
}
}
private static void LogException(StringBuilder logMessage, Exception ex)
{
logMessage.AppendLine();
logMessage.AppendLine($"Exception: {ex.Message}");
logMessage.AppendLine($"StackTrace: {ex.StackTrace}");
}
public static void Info(string message)
{
Log("INFO", message);
}
public static void Warn(string message)
{
Log("WARN", message);
}
public static void Error(string message, Exception? ex = null)
{
var logMessage = new StringBuilder(message);
if (ex != null)
LogException(logMessage, ex);
Log("ERROR", logMessage.ToString());
}
public static void Fatal(string message, Exception? ex = null)
{
var logMessage = new StringBuilder(message);
if (ex != null)
LogException(logMessage, ex);
Log("FATAL", logMessage.ToString());
}
private static void Log(string level, string message)
{
try
{
lock (lockObj)
{
using var sw = new StreamWriter(GetLogFilePath(), true, Encoding.UTF8);
sw.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}");
}
}
catch
{
}
}
}