-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLogger.cs
More file actions
533 lines (478 loc) · 16.4 KB
/
Copy pathLogger.cs
File metadata and controls
533 lines (478 loc) · 16.4 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
namespace lifeviz;
internal static class Logger
{
private const int QueueCapacity = 512;
private const int MaxBatchSize = 256;
private const int QueuePollMilliseconds = 100;
private const int FlushIntervalMilliseconds = 500;
private const int ShutdownDrainTimeoutMilliseconds = 5000;
private const int StreamBufferSize = 64 * 1024;
private const int MaxQueuedRecordChars = 8 * 1024;
private const int MaxExceptionMessageChars = 2048;
private const int MaxExceptionDepth = 4;
private const long MaxSessionLogBytes = 8L * 1024 * 1024;
private const string RecordTruncatedSuffix = " ... [truncated]";
private const string DiskLimitMarker =
"--- LifeViz disk log limit reached; further messages are omitted for this session. ---";
private static readonly object Sync = new();
private static readonly Encoding LogEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
private static readonly int NewLineByteCount = LogEncoding.GetByteCount(Environment.NewLine);
private static readonly int DiskLimitMarkerByteCount =
LogEncoding.GetByteCount(DiskLimitMarker) + NewLineByteCount;
private static LogSession? _session;
public static void Initialize()
{
lock (Sync)
{
if (_session != null)
{
return;
}
StreamWriter? writer = null;
BlockingCollection<string>? queue = null;
LogSession? session = null;
try
{
writer = TryCreateWriter();
queue = new BlockingCollection<string>(new ConcurrentQueue<string>(), QueueCapacity);
var createdSession = new LogSession(
queue,
writer,
$"--- LifeViz session started {DateTime.UtcNow:O} ---");
session = createdSession;
var worker = new Thread(() => WriterLoop(createdSession))
{
IsBackground = true,
Name = "LifeViz.Logger",
Priority = ThreadPriority.BelowNormal
};
createdSession.Worker = worker;
Volatile.Write(ref _session, createdSession);
worker.Start();
}
catch
{
if (session != null)
{
Interlocked.Exchange(ref session.ShutdownStarted, 1);
}
Volatile.Write(ref _session, null);
if (session != null)
{
CloseWriter(session);
}
else
{
try
{
writer?.Dispose();
}
catch
{
}
}
try
{
queue?.Dispose();
}
catch
{
}
}
}
}
public static void Shutdown()
{
LogSession? session;
lock (Sync)
{
session = _session;
if (session == null || Interlocked.Exchange(ref session.ShutdownStarted, 1) != 0)
{
return;
}
session.EndMessage = $"--- LifeViz session ended {DateTime.UtcNow:O} ---";
try
{
session.Queue.CompleteAdding();
}
catch (ObjectDisposedException)
{
// The writer already completed its teardown.
}
}
if (session.Worker == Thread.CurrentThread)
{
return;
}
if (!session.Worker.Join(ShutdownDrainTimeoutMilliseconds))
{
SafeWriteConsole(
$"{DateTime.UtcNow:O} [WARN] Logger shutdown drain exceeded " +
$"{ShutdownDrainTimeoutMilliseconds} ms; remaining messages will finish on the background worker.");
}
}
public static void Info(string message) => Write("INFO", message, null);
public static void Warn(string message) => Write("WARN", message, null);
public static void Error(string message, Exception? ex = null) => Write("ERROR", message, ex);
private static void Write(string level, string message, Exception? ex)
{
Publish(BuildRecord(level, message, ex));
}
private static void Publish(string record)
{
LogSession? session = Volatile.Read(ref _session);
if (session == null)
{
// Preserve useful diagnostic output for calls made before initialization.
SafeWriteConsole(record);
return;
}
if (Volatile.Read(ref session.ShutdownStarted) != 0)
{
return;
}
try
{
if (session.Queue.IsAddingCompleted)
{
return;
}
if (session.Queue.TryAdd(record))
{
return;
}
Interlocked.Increment(ref session.DroppedCount);
}
catch (ObjectDisposedException)
{
// Shutdown disposed the queue between the checks above.
}
catch (InvalidOperationException)
{
// Shutdown completed the queue between the checks above.
}
}
private static void WriterLoop(LogSession session)
{
var flushClock = Stopwatch.StartNew();
bool flushPending = false;
try
{
WriteRecord(session, session.StartMessage, includeConsole: false);
flushPending = true;
while (!session.Queue.IsCompleted)
{
int batchCount = 0;
if (session.Queue.TryTake(out string? record, QueuePollMilliseconds))
{
WriteRecord(
session,
record,
includeConsole: Volatile.Read(ref session.ShutdownStarted) == 0);
flushPending = true;
batchCount++;
while (batchCount < MaxBatchSize && session.Queue.TryTake(out record))
{
WriteRecord(
session,
record,
includeConsole: Volatile.Read(ref session.ShutdownStarted) == 0);
batchCount++;
}
}
long dropped = Interlocked.Exchange(ref session.DroppedCount, 0);
if (dropped > 0)
{
WriteRecord(
session,
$"{DateTime.UtcNow:O} [WARN] Logger dropped {dropped} message(s) because its bounded queue was full.",
includeConsole: Volatile.Read(ref session.ShutdownStarted) == 0);
flushPending = true;
}
if (flushPending && flushClock.ElapsedMilliseconds >= FlushIntervalMilliseconds)
{
FlushWriter(session);
flushClock.Restart();
flushPending = false;
}
}
long finalDropped = Interlocked.Exchange(ref session.DroppedCount, 0);
if (finalDropped > 0)
{
WriteRecord(
session,
$"{DateTime.UtcNow:O} [WARN] Logger dropped {finalDropped} message(s) because its bounded queue was full.",
includeConsole: false);
}
if (!string.IsNullOrWhiteSpace(session.EndMessage))
{
WriteRecord(session, session.EndMessage, includeConsole: false);
}
FlushWriter(session);
}
catch (Exception ex)
{
SafeWriteConsole($"{DateTime.UtcNow:O} [WARN] LifeViz logging worker stopped unexpectedly. {ex.Message}");
}
finally
{
Interlocked.Exchange(ref session.ShutdownStarted, 1);
try
{
if (!session.Queue.IsAddingCompleted)
{
session.Queue.CompleteAdding();
}
}
catch
{
// The queue may already be disposed during exceptional startup teardown.
}
CloseWriter(session);
lock (Sync)
{
if (ReferenceEquals(_session, session))
{
Volatile.Write(ref _session, null);
}
}
try
{
session.Queue.Dispose();
}
catch
{
// Ignore final queue cleanup errors.
}
}
}
private static void WriteRecord(LogSession session, string record, bool includeConsole)
{
if (includeConsole)
{
SafeWriteConsole(record);
}
StreamWriter? writer = session.Writer;
if (writer == null || session.DiskLimitReached)
{
return;
}
try
{
int recordByteCount = LogEncoding.GetByteCount(record) + NewLineByteCount;
long contentLimit = MaxSessionLogBytes - DiskLimitMarkerByteCount;
if (session.BytesWritten + recordByteCount > contentLimit)
{
writer.WriteLine(DiskLimitMarker);
session.BytesWritten += DiskLimitMarkerByteCount;
writer.Flush();
session.DiskLimitReached = true;
SafeWriteConsole(DiskLimitMarker);
CloseWriter(session);
return;
}
writer.WriteLine(record);
session.BytesWritten += recordByteCount;
}
catch (Exception ex)
{
DisableFileLogging(session, ex);
}
}
private static void FlushWriter(LogSession session)
{
try
{
session.Writer?.Flush();
}
catch (Exception ex)
{
DisableFileLogging(session, ex);
}
}
private static void DisableFileLogging(LogSession session, Exception ex)
{
CloseWriter(session);
if (Interlocked.Exchange(ref session.FileFailureReported, 1) == 0)
{
SafeWriteConsole($"{DateTime.UtcNow:O} [WARN] LifeViz file logging was disabled. {ex.Message}");
}
}
private static StreamWriter? TryCreateWriter()
{
FileStream? stream = null;
try
{
string directory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"lifeviz",
"logs");
Directory.CreateDirectory(directory);
string path = Path.Combine(directory, "lifeviz.log");
stream = new FileStream(
path,
FileMode.Create,
FileAccess.Write,
FileShare.Read,
StreamBufferSize,
FileOptions.SequentialScan);
return new StreamWriter(stream, LogEncoding, StreamBufferSize, leaveOpen: false)
{
AutoFlush = false
};
}
catch
{
try
{
stream?.Dispose();
}
catch
{
}
// If file logging can't start, retain asynchronous console logging.
return null;
}
}
private static void CloseWriter(LogSession session)
{
StreamWriter? writer = session.Writer;
session.Writer = null;
if (writer == null)
{
return;
}
try
{
writer.Dispose();
}
catch
{
// Ignore shutdown and log-limit cleanup errors.
}
}
private static string BuildRecord(string level, string message, Exception? ex)
{
var builder = new StringBuilder(Math.Min(512, MaxQueuedRecordChars));
builder.Append(DateTime.UtcNow.ToString("O"));
builder.Append(" [");
builder.Append(level);
builder.Append("] ");
int messageBudget = ex == null
? MaxQueuedRecordChars - builder.Length
: Math.Min(MaxQueuedRecordChars / 2, MaxQueuedRecordChars - builder.Length);
AppendLimited(builder, message ?? string.Empty, messageBudget);
if (ex != null && builder.Length < MaxQueuedRecordChars)
{
AppendLimited(builder, Environment.NewLine, MaxQueuedRecordChars - builder.Length);
AppendException(builder, ex);
}
return builder.ToString();
}
private static void AppendException(StringBuilder builder, Exception exception)
{
Exception? current = exception;
int depth = 0;
while (current != null && depth < MaxExceptionDepth && builder.Length < MaxQueuedRecordChars)
{
if (depth > 0)
{
AppendLimited(
builder,
$"{Environment.NewLine}--- Inner exception ---{Environment.NewLine}",
MaxQueuedRecordChars - builder.Length);
}
try
{
AppendLimited(
builder,
current.GetType().FullName ?? current.GetType().Name,
MaxQueuedRecordChars - builder.Length);
AppendLimited(builder, ": ", MaxQueuedRecordChars - builder.Length);
AppendLimited(
builder,
current.Message ?? string.Empty,
Math.Min(MaxExceptionMessageChars, MaxQueuedRecordChars - builder.Length));
string? stackTrace = current.StackTrace;
if (!string.IsNullOrWhiteSpace(stackTrace) && builder.Length < MaxQueuedRecordChars)
{
AppendLimited(builder, Environment.NewLine, MaxQueuedRecordChars - builder.Length);
AppendLimited(builder, stackTrace, MaxQueuedRecordChars - builder.Length);
}
}
catch
{
AppendLimited(
builder,
"<exception details unavailable>",
MaxQueuedRecordChars - builder.Length);
}
current = current.InnerException;
depth++;
}
if (current != null && builder.Length < MaxQueuedRecordChars)
{
AppendLimited(builder, RecordTruncatedSuffix, MaxQueuedRecordChars - builder.Length);
}
}
private static void AppendLimited(StringBuilder builder, string value, int budget)
{
int available = Math.Min(Math.Max(0, budget), MaxQueuedRecordChars - builder.Length);
if (available <= 0 || value.Length == 0)
{
return;
}
if (value.Length <= available)
{
builder.Append(value);
return;
}
int retainedLength = Math.Max(0, available - RecordTruncatedSuffix.Length);
if (retainedLength > 0)
{
builder.Append(value.AsSpan(0, retainedLength));
}
int suffixLength = Math.Min(RecordTruncatedSuffix.Length, available - retainedLength);
if (suffixLength > 0)
{
builder.Append(RecordTruncatedSuffix.AsSpan(0, suffixLength));
}
}
private static void SafeWriteConsole(string record)
{
try
{
Console.WriteLine(record);
}
catch
{
// Console output is best-effort, especially for the WinExe build.
}
}
private sealed class LogSession
{
public LogSession(BlockingCollection<string> queue, StreamWriter? writer, string startMessage)
{
Queue = queue;
Writer = writer;
StartMessage = startMessage;
}
public BlockingCollection<string> Queue { get; }
public Thread Worker { get; set; } = null!;
public StreamWriter? Writer { get; set; }
public string StartMessage { get; }
public string? EndMessage { get; set; }
public long BytesWritten { get; set; }
public long DroppedCount;
public int ShutdownStarted;
public int FileFailureReported;
public bool DiskLimitReached { get; set; }
}
}