-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogger.cs
182 lines (155 loc) · 5.59 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleFileLogger
{
public static class SFL
{
//ensure only one instance of the logger is initialized
private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
private static string logDirectory;
private static bool enableLogging;
private static LogLevel minimumLogLevel;
private static int maxLogFiles;
private static long maxFileSizeBytes;
private static bool isInitialized = false;
private static string currentLogFile;
private static object fileLock = new object();
public static async Task InitializeAsync(SFLConfig config)
{
await _semaphore.WaitAsync();
try
{
if (isInitialized)
{
return;
}
logDirectory = config.LogDirectory;
enableLogging = config.EnableLogging;
minimumLogLevel = config.MinimumLogLevel;
maxLogFiles = config.MaxLogFiles;
maxFileSizeBytes = config.MaxFileSizeMB * 1024 * 1024;
if (enableLogging)
{
try
{
if (!Directory.Exists(logDirectory))
{
Directory.CreateDirectory(logDirectory);
}
}
catch (Exception)
{
enableLogging = false;
Console.WriteLine("Failed to create log directory for SFL. Logging will be disabled.");
}
}
currentLogFile = GetLogFilePath();
isInitialized = true;
CleanupOldLogs();
}
finally
{
_semaphore.Release();
}
}
public static void Initialize(SFLConfig config)
{
InitializeAsync(config).GetAwaiter().GetResult();
}
private static void EnsureInitialized()
{
if (!isInitialized)
{
throw new InvalidOperationException("FileLogger is not initialized. Call Initialize() before using the logger.");
}
}
private static void Log(LogLevel level, string message)
{
EnsureInitialized();
if (!enableLogging || level < minimumLogLevel)
return;
try
{
string logMessage = $"- {DateTime.Now:HH:mm:ss} [{level}] - {message}";
lock (fileLock)
{
string todayLogFile = GetLogFilePath();
if (todayLogFile != currentLogFile)
{
currentLogFile = todayLogFile;
CleanupOldLogs();
}
if (File.Exists(currentLogFile) && new FileInfo(currentLogFile).Length + logMessage.Length > maxFileSizeBytes)
{
currentLogFile = GetLogFilePath(true);
}
File.AppendAllText(currentLogFile, logMessage + Environment.NewLine);
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to log message: {ex.Message}");
}
}
private static string GetLogFilePath(bool split = false)
{
string fileName = $"log_{DateTime.Now:yyyyMMdd}";
if (split)
{
fileName += $"_{DateTime.Now:HHmmss}";
}
fileName += ".txt";
return Path.Combine(logDirectory, fileName);
}
private static void CleanupOldLogs()
{
if (!Directory.Exists(logDirectory))
{
return;
}
var logFiles = Directory.GetFiles(logDirectory, "log_*.txt")
.OrderByDescending(f => f)
.Skip(maxLogFiles)
.ToList();
foreach (var file in logFiles)
{
try
{
File.Delete(file);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to delete old log file {file}: {ex.Message}");
}
}
}
public static void Debug(string message) => Log(LogLevel.Debug, message);
public static void Info(string message) => Log(LogLevel.Info, message);
public static void Warning(string message) => Log(LogLevel.Warning, message);
public static void Error(string message) => Log(LogLevel.Error, message);
public static void Critical(string message) => Log(LogLevel.Critical, message);
private static string GenerateFileName()
{
return $"SFLog_{DateTime.Now:yyyyMMdd}.txt";
}
}
public enum LogLevel
{
Debug,
Info,
Warning,
Error,
Critical
}
public class SFLConfig
{
public string LogDirectory { get; set; } = @".\SFLogs"; // Default to "logs
public bool EnableLogging { get; set; } // Default disabled
public LogLevel MinimumLogLevel { get; set; } = LogLevel.Info;
public int MaxLogFiles { get; set; } = 30; // Default to keep last 30 log files
public long MaxFileSizeMB { get; set; } = 5; // 5 MB default
}
}