Code
·
220 lines
·
4881 bytes
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Channels;
namespace LoggerExtensions;
public sealed class FileLogger : IDisposable
{
private readonly Channel<string> channel;
private readonly Task consumerTask;
private readonly CancellationTokenSource cts = new();
private readonly string logDirectory;
private StreamWriter? writer;
private string currentFilePath = string.Empty;
private DateTime currentDate = DateTime.MinValue;
public FileLogger(string logDirectory = "Logs")
{
this.logDirectory = logDirectory;
Directory.CreateDirectory(logDirectory);
channel = Channel.CreateBounded<string>(
new BoundedChannelOptions(10000)
{
SingleReader = true,
SingleWriter = false,
FullMode = BoundedChannelFullMode.Wait
});
consumerTask = Task.Run(() => ConsumeAsync(cts.Token));
}
internal void WriteMessage(string message)
{
channel.Writer.TryWrite(message);
}
private async Task ConsumeAsync(CancellationToken ct)
{
const int batchSize = 200;
const int maxIdleMs = 4000;
var batch = new List<string>(batchSize);
Task<string>? readTask = null;
try
{
while (!ct.IsCancellationRequested)
{
readTask ??= channel.Reader.ReadAsync(ct).AsTask();
using var delayCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var delayTask = Task.Delay(maxIdleMs, delayCts.Token);
var completed = await Task.WhenAny(readTask, delayTask);
if (completed == delayTask)
{
if (batch.Count > 0)
{
await WriteBatchAsync(batch, ct);
batch.Clear();
}
continue;
}
delayCts.Cancel();
var message = await readTask;
readTask = null;
batch.Add(message);
if (batch.Count >= batchSize)
{
await WriteBatchAsync(batch, ct);
batch.Clear();
}
}
}
catch (OperationCanceledException)
{
if (batch.Count > 0)
{
try { await WriteBatchAsync(batch, ct); } catch { }
}
}
}
private async Task WriteBatchAsync(List<string> messages, CancellationToken ct)
{
const int maxRetries = 3;
for (int attempt = 0; attempt < maxRetries; attempt++)
{
try
{
await WriteBatchInternalAsync(messages, ct);
return;
}
catch (IOException) when (attempt < maxRetries - 1)
{
await Task.Delay(100 << attempt, ct);
}
}
}
private async Task WriteBatchInternalAsync(List<string> messages, CancellationToken ct)
{
var today = DateTime.Today;
if (writer == null || today != currentDate)
{
await CloseWriterAsync(ct);
currentDate = today;
currentFilePath = Path.Combine(logDirectory, $"log-{today:yyyyMMdd}.txt");
FileStream stream = new(
currentFilePath,
FileMode.Append,
FileAccess.Write,
FileShare.ReadWrite,
bufferSize: 65536,
useAsync: true);
writer = new StreamWriter(stream) { AutoFlush = false };
}
foreach (var msg in messages)
{
await writer.WriteAsync(msg.AsMemory(), ct);
}
await writer.FlushAsync(ct);
}
private async Task CloseWriterAsync(CancellationToken ct)
{
if (writer == null) return;
try
{
await writer.FlushAsync(ct);
await writer.DisposeAsync();
}
catch { }
finally
{
writer = null;
}
}
public void Dispose()
{
channel.Writer.Complete();
cts.CancelAfter(TimeSpan.FromSeconds(8));
try
{
consumerTask.Wait(TimeSpan.FromSeconds(10));
}
catch { }
CloseWriterAsync(cts.Token).GetAwaiter().GetResult();
cts.Dispose();
}
}
internal sealed class CategoryLogger(FileLogger innerLogger, string categoryName) : ILogger
{
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
return;
var message = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{logLevel,-11}] {categoryName}: {formatter(state, exception)}";
if (exception != null)
message += $"{Environment.NewLine}{exception}";
message += Environment.NewLine;
innerLogger.WriteMessage(message);
}
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;
}
public sealed class FileLoggerProvider : ILoggerProvider
{
private readonly FileLogger sharedLogger;
public FileLoggerProvider(string logDirectory = "Logs")
{
sharedLogger = new FileLogger(logDirectory);
}
public ILogger CreateLogger(string categoryName)
{
return new CategoryLogger(sharedLogger, categoryName);
}
public void Dispose() => sharedLogger.Dispose();
}
public static class LoggingBuilderExtensions
{
public static ILoggingBuilder AddFileLogger(
this ILoggingBuilder builder,
string logDirectory = "Logs")
{
builder.Services.AddSingleton<ILoggerProvider>(sp =>
new FileLoggerProvider(logDirectory));
return builder;
}
}