Repository navigation
Expand file tree
/
Copy pathBroadcastLogger.cs
More file actions
268 lines (233 loc) · 8.39 KB
/
Copy pathBroadcastLogger.cs
File metadata and controls
268 lines (233 loc) · 8.39 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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
namespace WpfApp1
{
public static class BroadcastLogger
{
private const int MaxQueueLength = 1000;
private const int MaxWriteBatch = 64;
private const long TailReadWindowBytes = 256 * 1024;
private const int RetentionDays = 30;
private static readonly BlockingCollection<BroadcastLogEntry> Queue = new(new ConcurrentQueue<BroadcastLogEntry>(), MaxQueueLength);
private static readonly Lazy<Thread> WriterThread = new(StartWriterThread, LazyThreadSafetyMode.ExecutionAndPublication);
private static int _droppedCount;
private static Thread StartWriterThread()
{
TryCleanupOldLogs();
var thread = new Thread(ProcessQueue)
{
IsBackground = true,
Name = "BroadcastLogger"
};
thread.Start();
return thread;
}
public static string LogDirectory => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
public static string TodayLogPath => GetLogPath(DateTime.Now);
public static void Info(string message)
{
Write("INFO", message);
}
public static void Warning(string message)
{
Write("WARN", message);
}
public static void Error(string message)
{
Write("ERROR", message);
}
public static string ReadTodayTail(int maxLines)
{
return ReadTail(TodayLogPath, maxLines);
}
internal static string ReadTail(string path, int maxLines)
{
try
{
if (!File.Exists(path))
{
return "今天还没有播放日志。";
}
int capacity = Math.Max(1, maxLines);
var tailLines = new System.Collections.Generic.Queue<string>(capacity);
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// 只要末尾窗口,避免整天日志全量流过;起点可能落在行中间,丢弃第一段半行
bool seeked = stream.Length > TailReadWindowBytes;
if (seeked)
{
stream.Seek(-TailReadWindowBytes, SeekOrigin.End);
}
using var reader = new StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks: !seeked);
if (seeked)
{
reader.ReadLine();
}
string? line;
while ((line = reader.ReadLine()) != null)
{
if (tailLines.Count == capacity)
{
tailLines.Dequeue();
}
tailLines.Enqueue(line);
}
return string.Join(Environment.NewLine, tailLines);
}
catch (Exception ex)
{
return $"读取日志失败: {ex.Message}";
}
}
public static void FlushAndStop(TimeSpan timeout)
{
try
{
if (!WriterThread.IsValueCreated)
{
return;
}
Queue.CompleteAdding();
WriterThread.Value.Join(timeout);
}
catch
{
// Logging must never block or affect shutdown.
}
}
private static void Write(string level, string message)
{
try
{
_ = WriterThread.Value;
var entry = new BroadcastLogEntry(DateTime.Now, level, Sanitize(message));
if (Queue.TryAdd(entry))
{
return;
}
if (Queue.TryTake(out _))
{
Interlocked.Increment(ref _droppedCount);
}
if (!Queue.TryAdd(entry))
{
Interlocked.Increment(ref _droppedCount);
}
}
catch
{
// Logging failures must never affect playback or UI actions.
}
}
private static string Sanitize(string message)
{
if (string.IsNullOrWhiteSpace(message))
{
return string.Empty;
}
return message.Replace('\r', ' ').Replace('\n', ' ');
}
private static void ProcessQueue()
{
try
{
var batch = new System.Collections.Generic.List<BroadcastLogEntry>(MaxWriteBatch);
foreach (var entry in Queue.GetConsumingEnumerable())
{
// 突发日志攒一批一次落盘,避免每行一对文件开/关
batch.Clear();
batch.Add(entry);
while (batch.Count < MaxWriteBatch && Queue.TryTake(out var extra))
{
batch.Add(extra);
}
WriteEntries(batch);
}
}
catch
{
// The logger is intentionally fail-closed and invisible to playback.
}
}
private static void WriteEntries(System.Collections.Generic.List<BroadcastLogEntry> entries)
{
try
{
Directory.CreateDirectory(LogDirectory);
var builder = new StringBuilder();
int dropped = Interlocked.Exchange(ref _droppedCount, 0);
if (dropped > 0)
{
builder.AppendLine(FormatLine(entries[0].Timestamp, "WARN", $"日志队列已满,丢弃 {dropped} 条旧日志"));
}
// 批次可能跨零点换日志文件,按目标文件分段落盘
string path = GetLogPath(entries[0].Timestamp);
foreach (var entry in entries)
{
string entryPath = GetLogPath(entry.Timestamp);
if (!string.Equals(entryPath, path, StringComparison.OrdinalIgnoreCase) && builder.Length > 0)
{
File.AppendAllText(path, builder.ToString(), Encoding.UTF8);
builder.Clear();
path = entryPath;
}
builder.AppendLine(FormatLine(entry.Timestamp, entry.Level, entry.Message));
}
if (builder.Length > 0)
{
File.AppendAllText(path, builder.ToString(), Encoding.UTF8);
}
}
catch (Exception ex)
{
Debug.WriteLine($"写入播放日志失败: {ex.Message}");
}
}
private static string FormatLine(DateTime timestamp, string level, string message)
{
return $"{timestamp:yyyy-MM-dd HH:mm:ss} [{level}] {message}";
}
internal static string GetLogPath(DateTime timestamp)
{
return Path.Combine(LogDirectory, $"broadcast-{timestamp:yyyyMMdd}.log");
}
private static void TryCleanupOldLogs()
{
try
{
if (!Directory.Exists(LogDirectory))
{
return;
}
DateTime cutoff = DateTime.Now.AddDays(-RetentionDays);
foreach (var file in Directory.GetFiles(LogDirectory, "broadcast-*.log"))
{
if (File.GetLastWriteTime(file) < cutoff)
{
File.Delete(file);
}
}
}
catch
{
// Cleanup is best-effort only.
}
}
private readonly struct BroadcastLogEntry
{
public BroadcastLogEntry(DateTime timestamp, string level, string message)
{
Timestamp = timestamp;
Level = level;
Message = message;
}
public DateTime Timestamp { get; }
public string Level { get; }
public string Message { get; }
}
}
}