-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLogger.cs
More file actions
82 lines (71 loc) · 2.38 KB
/
Logger.cs
File metadata and controls
82 lines (71 loc) · 2.38 KB
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
namespace OpenSC
{
public static class Logger
{
private static readonly object _lock = new object();
private static string _logFilePath;
private static bool _logToFile;
private static bool _logToConsole;
public static void Initialize(bool logToConsole = true, bool logToFile = false, string logFilePath = null)
{
_logToConsole = logToConsole;
_logToFile = logToFile;
if (_logToFile)
{
if (string.IsNullOrWhiteSpace(logFilePath))
{
logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", $"log_{DateTime.Now:yyyy-MM-dd}.txt");
}
_logFilePath = logFilePath;
var logDir = Path.GetDirectoryName(_logFilePath);
if (!Directory.Exists(logDir))
{
Directory.CreateDirectory(logDir);
}
}
}
public static void LogInfo(string message)
{
WriteLog(message, LogLevel.INFO);
}
public static void LogWarning(string message)
{
WriteLog(message, LogLevel.WARNING);
}
public static void LogError(string message, Exception ex = null)
{
var errorMessage = ex != null ? $"{message}\nEXCEPTION: {ex}\nSTACKTRACE: {ex.StackTrace}" : message;
WriteLog(errorMessage, LogLevel.ERROR);
}
private static void WriteLog(string message, LogLevel level)
{
var logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}";
lock (_lock)
{
if (_logToConsole)
{
Console.WriteLine(logEntry);
if (level == LogLevel.ERROR) Console.WriteLine();
}
if (_logToFile)
{
try
{
File.AppendAllText(_logFilePath, logEntry + Environment.NewLine);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to write to log file: {ex.Message}");
}
}
}
}
private enum LogLevel
{
INFO,
WARNING,
ERROR
}
}
}