-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogger.cs
More file actions
73 lines (64 loc) · 1.62 KB
/
Logger.cs
File metadata and controls
73 lines (64 loc) · 1.62 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
using System.IO;
namespace YAOLlm;
public class Logger : IDisposable
{
private readonly object _lock = new();
private string? _lastMessage;
private int _repeatCount;
private readonly StreamWriter? _fileWriter;
private bool _disposed;
public Logger()
{
try
{
var logDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
Directory.CreateDirectory(logDir);
var logFile = Path.Combine(logDir, $"yaollm_{DateTime.Now:yyyy-MM-dd}.log");
_fileWriter = new StreamWriter(logFile, append: true);
}
catch
{
_fileWriter = null;
}
}
public void Log(string message)
{
lock (_lock)
{
if (_disposed) return;
if (message == _lastMessage)
{
_repeatCount++;
return;
}
if (_repeatCount > 0)
{
WriteToAllTargets($"(last line repeated {_repeatCount} times)");
_repeatCount = 0;
}
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
WriteToAllTargets($"{timestamp} - {message}");
_lastMessage = message;
}
}
private void WriteToAllTargets(string line)
{
Console.WriteLine(line);
try
{
_fileWriter?.WriteLine(line);
}
catch
{
}
}
public void Dispose()
{
lock (_lock)
{
if (_disposed) return;
_disposed = true;
_fileWriter?.Dispose();
}
}
}