-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogger.cs
85 lines (62 loc) · 2.79 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
/*
Credit to Calcilore (https://github.com/Calcilore) for this file
Original: https://github.com/Calcilore/RayKeys/blob/main/Misc/Logger.cs
*/
using System;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
namespace HomeworkTrackerServer;
public static class Logger {
public static LogLevel LoggingLevel { get; set; } = LogLevel.Debug;
private static FileStream _logFile;
private static StreamWriter _streamWriter;
private static Task _writeTask = Task.CompletedTask;
private static string _typeText;
public static void Log(object logObj, LogLevel level) {
if (LoggingLevel < level) { return; }
string log = $"[{DateTime.Now.ToLongTimeString()}] [{level}]: {logObj}\n";
Console.Write(log);
_typeText += log;
if (!_writeTask.IsCompleted) { return; }
_writeTask = _streamWriter.WriteAsync(_typeText);
_typeText = "";
}
public static void WaitFlush() {
_writeTask.Wait();
_streamWriter.Write(_typeText);
_typeText = "";
}
public static void Init(LogLevel logLevel) {
LoggingLevel = logLevel;
if (!Directory.Exists("Logs")) { Directory.CreateDirectory("Logs"); }
if (File.Exists("Logs/latest.log")) {
using FileStream originalFileStream = File.Open("Logs/latest.log", FileMode.Open);
string gzFileLoc = new StreamReader(originalFileStream).ReadLine();
try {
gzFileLoc = "Logs" + gzFileLoc[gzFileLoc.LastIndexOf('/')..] + ".gz";
}
catch (Exception) {
gzFileLoc = "Logs/Unknown-" +
(int)(new Random().Next()*1000000*3.141592653589793238462643383279502884197169) + ".log.gz";
}
originalFileStream.Seek(0, SeekOrigin.Begin);
using FileStream compressedFileStream = File.Create(gzFileLoc);
using GZipStream compressor = new(compressedFileStream, CompressionMode.Compress);
originalFileStream.CopyTo(compressor);
}
string logFileName = $"Logs/{DateTime.Now:yyyy-MM-dd}-";
int i = 1;
while (File.Exists(logFileName + i + ".log.gz")) { i++; } // Get a unique number for the name
logFileName += i + ".log";
_logFile = File.OpenWrite("Logs/latest.log");
_streamWriter = new StreamWriter(_logFile);
_streamWriter.AutoFlush = true;
_typeText = "";
Info($"Logging to: {logFileName}");
}
public static void Error(object log) => Log(log, LogLevel.Error);
public static void Info(object log) => Log(log, LogLevel.Info);
public static void Debug(object log) => Log(log, LogLevel.Debug);
}
public enum LogLevel { Error, Info, Debug }