-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathLogfileReader.cs
More file actions
2523 lines (2243 loc) · 94.3 KB
/
LogfileReader.cs
File metadata and controls
2523 lines (2243 loc) · 94.3 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections.Concurrent;
using System.Globalization;
using System.Text;
using ColumnizerLib;
using LogExpert.Core.Classes.xml;
using LogExpert.Core.Entities;
using LogExpert.Core.Enums;
using LogExpert.Core.EventArguments;
using LogExpert.Core.Interfaces;
using NLog;
namespace LogExpert.Core.Classes.Log;
public partial class LogfileReader : IAutoLogLineMemoryColumnizerCallback, IDisposable
{
#region Fields
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly string _fileName;
private readonly int _max_buffers;
private readonly int _maxLinesPerBuffer;
private readonly Lock _monitor = new();
private readonly MultiFileOptions _multiFileOptions;
private readonly IPluginRegistry _pluginRegistry;
private readonly CancellationTokenSource _cts = new();
private readonly ReaderType _readerType;
private readonly int _maximumLineLength;
private readonly LogBufferPool _bufferPool;
private readonly Lock _logBufferLock = new();
private readonly ReaderWriterLockSlim _bufferListLock = new(LockRecursionPolicy.SupportsRecursion);
private readonly MemoryMappedFileReader _mmfReader;
private const int PROGRESS_UPDATE_INTERVAL_MS = 100;
private const int WAIT_TIME = 1000;
private SortedList<int, LogBuffer> _bufferList;
private bool _contentDeleted;
private long _lastProgressUpdate;
private long _fileLength;
private Task _garbageCollectorTask;
private Task _monitorTask;
private bool _isDeleted;
private IList<ILogFileInfo> _logFileInfoList = [];
private ConcurrentDictionary<int, LogBufferCacheEntry> _lruCacheDict;
private bool _shouldStop;
private bool _disposed;
private ILogFileInfo _watchedILogFileInfo;
private volatile bool _isLineCountDirty = true;
private volatile bool _isFailModeCheckCallPending;
private volatile bool _isFastFailOnGetLogLine;
private readonly ThreadLocal<int> _lastBufferIndex = new(() => -1);
#endregion
#region cTor
/// Public constructor for single file.
public LogfileReader (string fileName, EncodingOptions encodingOptions, bool multiFile, int bufferCount, int linesPerBuffer, MultiFileOptions multiFileOptions, ReaderType readerType, IPluginRegistry pluginRegistry, int maximumLineLength)
: this([fileName], encodingOptions, multiFile, bufferCount, linesPerBuffer, multiFileOptions, readerType, pluginRegistry, maximumLineLength)
{
}
/// Public constructor for multiple files.
public LogfileReader (string[] fileNames, EncodingOptions encodingOptions, int bufferCount, int linesPerBuffer, MultiFileOptions multiFileOptions, ReaderType readerType, IPluginRegistry pluginRegistry, int maximumLineLength)
: this(fileNames, encodingOptions, true, bufferCount, linesPerBuffer, multiFileOptions, readerType, pluginRegistry, maximumLineLength)
{
// In this overload, we assume multiFile is always true.
}
// Single private constructor that contains the common initialization logic.
private LogfileReader (string[] fileNames, EncodingOptions encodingOptions, bool multiFile, int bufferCount, int linesPerBuffer, MultiFileOptions multiFileOptions, ReaderType readerType, IPluginRegistry pluginRegistry, int maximumLineLength)
{
// Validate input: at least one file must be provided.
if (fileNames == null || fileNames.Length < 1)
{
throw new ArgumentException(Resources.LogfileReader_Error_Message_MustProvideAtLeastOneFile, nameof(fileNames));
}
//Set default maximum line length if invalid value provided.
if (maximumLineLength <= 0)
{
maximumLineLength = 500;
}
_maximumLineLength = maximumLineLength;
_readerType = readerType;
EncodingOptions = encodingOptions;
_max_buffers = bufferCount;
_maxLinesPerBuffer = linesPerBuffer;
_multiFileOptions = multiFileOptions;
_pluginRegistry = pluginRegistry;
_disposed = false;
_bufferPool = new LogBufferPool(_max_buffers * 2);
InitLruBuffers();
ILogFileInfo fileInfo = null;
IsMultiFile = multiFile || fileNames.Length == 1;
_fileName = fileNames[0];
IEnumerable<string> names = IsMultiFile
// For multi-file rollover mode: get rollover names.
? new RolloverFilenameHandler(GetLogFileInfo(_fileName), _multiFileOptions).GetNameList(_pluginRegistry)
: [_fileName];
foreach (var name in names)
{
fileInfo = AddFile(name);
}
if (IsMultiFile)
{
// Use the full name of the last file as _fileName.
_fileName = fileInfo.FullName;
}
_watchedILogFileInfo = fileInfo;
if (!IsMultiFile && _watchedILogFileInfo.Uri?.Scheme is null or "file")
{
try
{
_mmfReader = new MemoryMappedFileReader(_watchedILogFileInfo.FullName, EncodingOptions.Encoding ?? Encoding.Default);
}
catch (IOException)
{
_mmfReader = null; // fallback to buffer path
}
}
StartGCThread();
}
#endregion
#region Events
public event EventHandler<LogEventArgs> FileSizeChanged;
public event EventHandler<LoadFileEventArgs> LoadFile;
public event EventHandler<LoadFileEventArgs> LoadingStarted;
public event EventHandler<EventArgs> LoadingFinished;
public event EventHandler<EventArgs> FileNotFound;
public event EventHandler<EventArgs> Respawned;
#endregion
#region Properties
/// <summary>
/// Gets the total number of lines contained in all buffers.
/// </summary>
/// <remarks>
/// The value is recalculated on demand if the underlying buffers have changed since the last access. Accessing this
/// property is thread-safe.
/// </remarks>
public int LineCount
{
get
{
if (_isLineCountDirty)
{
field = 0;
if (_bufferListLock.IsReadLockHeld || _bufferListLock.IsWriteLockHeld)
{
foreach (var buffer in _bufferList.Values)
{
field += buffer.LineCount;
}
}
else
{
AcquireBufferListReaderLock();
try
{
foreach (var buffer in _bufferList.Values)
{
field += buffer.LineCount;
}
}
finally
{
ReleaseBufferListReaderLock();
}
}
_isLineCountDirty = false;
}
return field;
}
private set;
}
/// <summary>
/// Gets a value indicating whether the current operation involves multiple files.
/// </summary>
public bool IsMultiFile { get; }
/// <summary>
/// Gets the character encoding currently used for reading or writing operations.
/// </summary>
public Encoding CurrentEncoding { get; private set; }
/// <summary>
/// Gets the size of the file, in bytes.
/// </summary>
public long FileSize { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether XML mode is enabled.
/// </summary>
public bool IsXmlMode { get; set; }
/// <summary>
/// Gets or sets the XML log configuration used to control logging behavior and settings.
/// </summary>
public IXmlLogConfiguration XmlLogConfig { get; set; }
/// <summary>
/// Gets or sets the columnizer used to preprocess data before further processing.
/// </summary>
public IPreProcessColumnizerMemory PreProcessColumnizer { get; set; }
/// <summary>
/// Gets or sets the encoding options used for text processing operations.
/// </summary>
private EncodingOptions EncodingOptions
{
get;
set
{
{
field = new EncodingOptions
{
DefaultEncoding = value.DefaultEncoding,
Encoding = value.Encoding
};
}
}
}
#endregion
#region Public methods
/// <summary>
/// Reads all log files and refreshes the internal buffer and related state to reflect the current contents of the
/// files. Public for unit test reasons
/// </summary>
/// <remarks>
/// This method resets file size and line count tracking, clears any cached data, and repopulates the buffer with
/// the latest data from the log files. If an I/O error occurs while reading the files, the internal state is
/// updated to indicate that the files are unavailable. After reading, a file size changed event is raised to notify
/// listeners of the update.
/// </remarks>
//TODO: Make this private
public void ReadFiles ()
{
_lastProgressUpdate = 0;
FileSize = 0;
LineCount = 0;
_isDeleted = false;
ClearLru();
AcquireBufferListWriterLock();
_bufferList.Clear();
ReleaseBufferListWriterLock();
try
{
foreach (var info in _logFileInfoList)
{
ReadToBufferList(info, 0, LineCount);
}
if (_logFileInfoList.Count > 0)
{
var info = _logFileInfoList[_logFileInfoList.Count - 1];
_fileLength = info.Length;
_watchedILogFileInfo = info;
}
}
catch (IOException e)
{
_logger.Warn(e, "IOException");
_fileLength = 0;
_isDeleted = true;
LineCount = 0;
}
LogEventArgs args = new()
{
PrevFileSize = 0,
PrevLineCount = 0,
LineCount = LineCount,
FileSize = FileSize
};
OnFileSizeChanged(args);
}
/// <summary>
/// Synchronizes the internal buffer state with the current set of log files, updating or removing buffers as
/// necessary to reflect file changes. Public for unit tests.
/// </summary>
/// <remarks>
/// Call this method after external changes to the underlying log files, such as file rotation or deletion, to
/// ensure the buffer accurately represents the current log file set. This method may remove, update, or re-read
/// buffers to match the current files. Thread safety is ensured during the operation.
/// </remarks>
/// <returns>
/// The total number of lines removed from the buffer as a result of deleted or replaced log files. Returns 0 if no
/// lines were removed.
/// </returns>
//TODO: Make this private
public int ShiftBuffers ()
{
_logger.Info(CultureInfo.InvariantCulture, "ShiftBuffers() begin for {0}{1}", _fileName, IsMultiFile ? " (MultiFile)" : "");
AcquireBufferListWriterLock();
try
{
ClearBufferState();
var offset = 0;
_isLineCountDirty = true;
lock (_monitor)
{
RolloverFilenameHandler rolloverHandler = new(_watchedILogFileInfo, _multiFileOptions);
var fileNameList = rolloverHandler.GetNameList(_pluginRegistry);
ResetBufferCache();
IList<ILogFileInfo> lostILogFileInfoList = [];
IList<ILogFileInfo> readNewILogFileInfoList = [];
IList<ILogFileInfo> newFileInfoList = [];
var enumerator = _logFileInfoList.GetEnumerator();
while (enumerator.MoveNext())
{
var logFileInfo = enumerator.Current;
var fileName = logFileInfo.FullName;
_logger.Debug(CultureInfo.InvariantCulture, "Testing file {0}", fileName);
var node = fileNameList.Find(fileName);
if (node == null)
{
_logger.Warn(CultureInfo.InvariantCulture, "File {0} not found", fileName);
continue;
}
if (node.Previous != null)
{
fileName = node.Previous.Value;
var newILogFileInfo = GetLogFileInfo(fileName);
_logger.Debug(CultureInfo.InvariantCulture, "{0} exists\r\nOld size={1}, new size={2}", fileName, logFileInfo.OriginalLength, newILogFileInfo.Length);
// is the new file the same as the old buffer info?
if (newILogFileInfo.Length == logFileInfo.OriginalLength)
{
ReplaceBufferInfos(logFileInfo, newILogFileInfo);
newFileInfoList.Add(newILogFileInfo);
}
else
{
_logger.Debug(CultureInfo.InvariantCulture, "Buffer for {0} must be re-read.", fileName);
// not the same. so must read the rest of the list anew from the files
readNewILogFileInfoList.Add(newILogFileInfo);
while (enumerator.MoveNext())
{
fileName = enumerator.Current.FullName;
node = fileNameList.Find(fileName);
if (node == null)
{
_logger.Warn(CultureInfo.InvariantCulture, "File {0} not found", fileName);
continue;
}
if (node.Previous != null)
{
fileName = node.Previous.Value;
_logger.Debug(CultureInfo.InvariantCulture, "New name is {0}", fileName);
readNewILogFileInfoList.Add(GetLogFileInfo(fileName));
}
else
{
_logger.Warn(CultureInfo.InvariantCulture, "No previous file for {0} found", fileName);
}
}
}
}
else
{
_logger.Info(CultureInfo.InvariantCulture, "{0} does not exist", fileName);
lostILogFileInfoList.Add(logFileInfo);
}
}
if (lostILogFileInfoList.Count > 0)
{
_logger.Info(CultureInfo.InvariantCulture, "Deleting buffers for lost files");
foreach (var logFileInfo in lostILogFileInfoList)
{
var lastDeletedBufferInfo = DeleteBuffersForInfo(logFileInfo, false);
if (lastDeletedBufferInfo != null)
{
offset += lastDeletedBufferInfo.Value.StartLine + lastDeletedBufferInfo.Value.LineCount;
}
}
_logger.Info(CultureInfo.InvariantCulture, "Adjusting StartLine values in {0} buffers by offset {1}", _bufferList.Count, offset);
foreach (var buffer in _bufferList.Values.ToList())
{
SetNewStartLineForBuffer(buffer, buffer.StartLine - offset);
}
#if DEBUG
if (_bufferList.Values.Count > 0)
{
_logger.Debug(CultureInfo.InvariantCulture, "First buffer now has StartLine {0}", _bufferList.Values[0].StartLine);
}
#endif
}
// Read anew all buffers following a buffer info that couldn't be matched with the corresponding existing file
_logger.Info(CultureInfo.InvariantCulture, "Deleting buffers for files that must be re-read");
foreach (var iLogFileInfo in readNewILogFileInfoList)
{
DeleteBuffersForInfo(iLogFileInfo, true);
}
_logger.Info(CultureInfo.InvariantCulture, "Deleting buffers for the watched file");
DeleteBuffersForInfo(_watchedILogFileInfo, true);
_logger.Info(CultureInfo.InvariantCulture, "Re-Reading files");
foreach (var iLogFileInfo in readNewILogFileInfoList)
{
ReadToBufferList(iLogFileInfo, 0, LineCount);
newFileInfoList.Add(iLogFileInfo);
}
_logFileInfoList = newFileInfoList;
_watchedILogFileInfo = GetLogFileInfo(_watchedILogFileInfo.FullName);
_logFileInfoList.Add(_watchedILogFileInfo);
_logger.Info(CultureInfo.InvariantCulture, "Reading watched file");
ReadToBufferList(_watchedILogFileInfo, 0, LineCount);
}
_logger.Info(CultureInfo.InvariantCulture, "ShiftBuffers() end. offset={0}", offset);
return offset;
}
finally
{
ReleaseBufferListWriterLock();
}
}
/// <summary>
/// Acquires a read lock on the buffer list, waiting up to 10 seconds before forcing entry if the lock is not
/// immediately available.
/// </summary>
/// <remarks>
/// If the read lock cannot be acquired within 10 seconds, the method will forcibly enter the lock and log a
/// warning. Callers should ensure that holding the read lock for extended periods does not block other operations.
/// </remarks>
private void AcquireBufferListReaderLock ()
{
if (!_bufferListLock.TryEnterReadLock(TimeSpan.FromSeconds(10)))
{
_logger.Warn("Reader lock wait timed out, forcing entry");
_bufferListLock.EnterReadLock();
}
}
/// <summary>
/// Releases the reader lock on the buffer list, allowing other threads to acquire write access.
/// </summary>
/// <remarks>
/// Call this method after completing operations that require read access to the buffer list. Failing to release the
/// reader lock may result in deadlocks or prevent other threads from obtaining write access.
/// </remarks>
private void ReleaseBufferListReaderLock ()
{
_bufferListLock.ExitReadLock();
}
/// <summary>
/// Releases the writer lock on the buffer list, allowing other threads to acquire the lock.
/// </summary>
/// <remarks>
/// Call this method after completing operations that required exclusive access to the buffer list. Failing to
/// release the writer lock may result in deadlocks or reduced concurrency.
/// </remarks>
private void ReleaseBufferListWriterLock ()
{
_bufferListLock.ExitWriteLock();
}
/// <summary>
/// Acquires the writer lock for the buffer list, blocking the calling thread until the lock is obtained.
/// </summary>
/// <remarks>
/// If the writer lock cannot be acquired within 10 seconds, a warning is logged and the method will continue to
/// wait until the lock becomes available. This method should be used to ensure exclusive access to the buffer list
/// when performing write operations.
/// </remarks>
private void AcquireBufferListWriterLock ()
{
if (!_bufferListLock.TryEnterWriteLock(TimeSpan.FromSeconds(10)))
{
_logger.Warn("Writer lock wait timed out");
_bufferListLock.EnterWriteLock();
}
}
//TODO Make Task Based
public ILogLineMemory GetLogLineMemory (int lineNum)
{
return GetLogLineMemoryInternal(lineNum).Result;
}
/// <summary>
/// Get the text content of the given line number. The actual work is done in an async thread. This method waits for
/// thread completion for only 1 second. If the async thread has not returned, the method will return <code>
/// null</code>. This is because this method is also called from GUI thread (e.g. LogWindow draw events). Under some
/// circumstances, repeated calls to this method would lead the GUI to freeze. E.g. when trying to re-load content
/// from disk but the file was deleted. Especially on network shares.
/// </summary>
/// <remarks>
/// Once the method detects a timeout it will enter a kind of 'fast fail mode'. That means all following calls will
/// be returned with <code> null</code> immediately (without 1 second wait). A background call to
/// GetLogLineInternal() will check if a result is available. If so, the 'fast fail mode' is switched off. In most
/// cases a fail is caused by a deleted file. But it may also be caused by slow network connections. So all this
/// effort is needed to prevent entering an endless 'fast fail mode' just because of temporary problems.
/// </remarks>
/// <param name="lineNum">line to retrieve</param>
/// <returns></returns>
public async Task<ILogLineMemory> GetLogLineMemoryWithWait (int lineNum)
{
ILogLineMemory result = null;
if (!_isFastFailOnGetLogLine)
{
// Fast path: if the buffer is in memory, skip the thread-pool hop entirely
bool canFastPath = false;
AcquireBufferListReaderLock();
try
{
var (logBuffer, _) = GetBufferForLineWithIndex(lineNum);
canFastPath = logBuffer is { IsDisposed: false };
}
finally
{
ReleaseBufferListReaderLock();
}
if (canFastPath)
{
result = GetLogLineMemoryInternal(lineNum).Result;
_isFastFailOnGetLogLine = false;
}
else
{
// Slow path: buffer disposed or not found — use Task.Run with timeout
var task = Task.Run(() => GetLogLineMemoryInternal(lineNum).AsTask());
if (task.Wait(WAIT_TIME))
{
result = await task.ConfigureAwait(false);
_isFastFailOnGetLogLine = false;
}
else
{
_isFastFailOnGetLogLine = true;
_logger.Info(CultureInfo.InvariantCulture, "Entering fast-fail mode for line {0}. No result after {1}ms.", lineNum, WAIT_TIME);
}
}
}
else
{
_logger.Info(CultureInfo.InvariantCulture, "Fast-fail returning null for line {0}", lineNum);
if (!_isFailModeCheckCallPending)
{
_isFailModeCheckCallPending = true;
var logLine = await GetLogLineMemoryInternal(lineNum).ConfigureAwait(true);
GetLineMemoryFinishedCallback(logLine);
}
}
return result;
}
/// <summary>
/// Returns the file name of the actual file for the given line. Needed for MultiFile.
/// </summary>
/// <param name="lineNum"></param>
/// <returns></returns>
public string GetLogFileNameForLine (int lineNum)
{
var logBuffer = GetBufferForLine(lineNum);
return logBuffer?.FileInfo.FullName;
}
/// <summary>
/// Returns the ILogFileInfo for the actual file for the given line. Needed for MultiFile.
/// </summary>
/// <param name="lineNum"></param>
/// <returns></returns>
public ILogFileInfo GetLogFileInfoForLine (int lineNum)
{
var logBuffer = GetBufferForLine(lineNum);
return logBuffer?.FileInfo;
}
/// <summary>
/// Returns the line number (starting from the given number) where the next multi file starts.
/// </summary>
/// <param name="lineNum"></param>
/// <returns></returns>
public int GetNextMultiFileLine (int lineNum)
{
var result = -1;
AcquireBufferListReaderLock();
try
{
var (logBuffer, index) = GetBufferForLineWithIndex(lineNum);
if (logBuffer != null && index != -1)
{
for (var i = index; i < _bufferList.Values.Count; ++i)
{
if (_bufferList.Values[i].FileInfo != logBuffer.FileInfo)
{
result = _bufferList.Values[i].StartLine;
break;
}
}
}
}
finally
{
ReleaseBufferListReaderLock();
}
return result;
}
/// <summary>
/// Finds the starting line number of the previous file segment before the specified line number across multiple
/// files.
/// </summary>
/// <remarks>
/// This method is useful when navigating through a collection of files represented as contiguous line segments. If
/// the specified line number is within the first file segment, the method returns -1 to indicate that there is no
/// previous file segment.
/// </remarks>
/// <param name="lineNum">
/// The line number for which to locate the previous file segment. Must be a valid line number within the buffer.
/// </param>
/// <returns>The starting line number of the previous file segment if one exists; otherwise, -1.</returns>
public int GetPrevMultiFileLine (int lineNum)
{
var result = -1;
AcquireBufferListReaderLock();
try
{
var (logBuffer, index) = GetBufferForLineWithIndex(lineNum);
if (logBuffer != null && index != -1)
{
for (var i = index; i >= 0; --i)
{
if (_bufferList.Values[i].FileInfo != logBuffer.FileInfo)
{
result = _bufferList.Values[i].StartLine + _bufferList.Values[i].LineCount;
break;
}
}
}
}
finally
{
ReleaseBufferListReaderLock();
}
return result;
}
/// <summary>
/// Returns the actual line number in the file for the given 'virtual line num'. This is needed for multi file mode.
/// 'Virtual' means that the given line num is a line number in the collections of the files currently viewed
/// together in multi file mode as one large virtual file. This method finds the real file for the line number and
/// maps the line number to the correct position in that file. This is needed when launching external tools to
/// provide correct line number arguments.
/// </summary>
/// <param name="lineNum"></param>
/// <returns></returns>
public int GetRealLineNumForVirtualLineNum (int lineNum)
{
var result = -1;
AcquireBufferListReaderLock();
try
{
var (logBuffer, index) = GetBufferForLineWithIndex(lineNum);
if (logBuffer != null)
{
logBuffer = GetFirstBufferForFileByLogBuffer(logBuffer, index);
if (logBuffer != null)
{
result = lineNum - logBuffer.StartLine;
}
}
}
finally
{
ReleaseBufferListReaderLock();
}
return result;
}
/// <summary>
/// Begins monitoring by starting the background monitoring process.
/// </summary>
/// <remarks>
/// This method initiates monitoring if it is not already running. To stop monitoring, call the corresponding stop
/// method if available. This method is not thread-safe; ensure that it is not called concurrently with other
/// monitoring control methods.
/// </remarks>
public void StartMonitoring ()
{
_logger.Info(CultureInfo.InvariantCulture, "startMonitoring()");
_monitorTask = Task.Run(MonitorThreadProc, _cts.Token);
_shouldStop = false;
}
/// <summary>
/// Stops monitoring the log file and terminates any background monitoring or cleanup tasks.
/// </summary>
/// <remarks>
/// Call this method to halt all ongoing monitoring activity and release associated resources. After calling this
/// method, monitoring cannot be resumed without restarting the monitoring process.
/// </remarks>
public void StopMonitoring ()
{
_logger.Info(CultureInfo.InvariantCulture, "stopMonitoring()");
_shouldStop = true;
_cts.Cancel();
try
{
var timeout = TimeSpan.FromSeconds(5);
_ = _monitorTask?.Wait(timeout);
_ = _garbageCollectorTask?.Wait(timeout);
}
catch (AggregateException ex) when (ex.InnerExceptions.All(e => e is OperationCanceledException))
{
//Expected exceptions due to task cancellation, can be safely ignored.
}
catch (AggregateException ex)
{
_logger.Warn(ex, "Exception while waiting for monitor or GC task to complete");
}
CloseFiles();
}
/// <summary>
/// calls stopMonitoring() in a background thread and returns to the caller immediately. This is useful for a fast
/// responding GUI (e.g. when closing a file tab)
/// </summary>
public void StopMonitoringAsync ()
{
var task = Task.Run(StopMonitoring);
}
/// <summary>
/// Deletes all buffer lines and disposes their content. Use only when the LogfileReader is about to be closed!
/// </summary>
public void DeleteAllContent ()
{
if (_contentDeleted)
{
_logger.Debug(CultureInfo.InvariantCulture, "Buffers for {0} already deleted.", Util.GetNameFromPath(_fileName));
return;
}
_logger.Info(CultureInfo.InvariantCulture, "Deleting all log buffers for {0}. Used mem: {1:N0}", Util.GetNameFromPath(_fileName), GC.GetTotalMemory(false));
AcquireBufferListWriterLock();
ClearBufferState();
//AcquireDisposeWriterLock();
foreach (var logBuffer in _bufferList.Values)
{
if (!logBuffer.IsDisposed)
{
logBuffer.DisposeContent();
}
}
_lruCacheDict.Clear();
_bufferList.Clear();
//ReleaseDisposeWriterLock();
ReleaseBufferListWriterLock();
_contentDeleted = true;
_logger.Info(CultureInfo.InvariantCulture, "Deleting complete. Used mem: {0:N0}", GC.GetTotalMemory(false));
}
/// <summary>
/// Clears the Buffer so that no stale buffer references are kept
/// </summary>
private void ClearBufferState ()
{
_lastBufferIndex.Value = -1;
}
/// <summary>
/// Explicit change the encoding.
/// </summary>
/// <param name="encoding"></param>
public void ChangeEncoding (Encoding encoding)
{
CurrentEncoding = encoding;
EncodingOptions.Encoding = encoding;
ResetBufferCache();
ClearLru();
}
/// <summary>
/// For unit tests only.
/// </summary>
/// <returns></returns>
public IList<ILogFileInfo> GetLogFileInfoList ()
{
return _logFileInfoList;
}
/// <summary>
/// For unit tests only
/// </summary>
/// <returns></returns>
public IList<LogBuffer> GetBufferList ()
{
return _bufferList.Values;
}
#endregion
#region Internals
#if DEBUG
/// <summary>
/// Logs detailed buffer information for the specified line number to the debug output.
/// </summary>
/// <remarks>
/// This method is intended for debugging purposes and is only available in debug builds. It logs buffer details and
/// file position information to assist with diagnostics.
/// </remarks>
/// <param name="lineNum">The zero-based line number for which buffer information is logged.</param>
public void LogBufferInfoForLine (int lineNum)
{
AcquireBufferListReaderLock();
try
{
var (buffer, _) = GetBufferForLineWithIndex(lineNum);
if (buffer == null)
{
_logger.Error("Cannot find buffer for line {0}, file: {1}{2}", lineNum, _fileName, IsMultiFile ? " (MultiFile)" : "");
return;
}
_logger.Info(CultureInfo.InvariantCulture, "-----------------------------------");
_logger.Info(CultureInfo.InvariantCulture, "Buffer info for line {0}", lineNum);
DumpBufferInfos(buffer);
_logger.Info(CultureInfo.InvariantCulture, "File pos for current line: {0}", buffer.GetFilePosForLineOfBlock(lineNum - buffer.StartLine));
_logger.Info(CultureInfo.InvariantCulture, "-----------------------------------");
}
finally
{
ReleaseBufferListReaderLock();
}
}
/// <summary>
/// Logs diagnostic information about the current state of the buffer and LRU cache for debugging purposes.
/// </summary>
/// <remarks>
/// This method is intended for use in debug builds to assist with troubleshooting and analyzing buffer management.
/// It outputs details such as the number of LRU cache entries, buffer counts, and dispose statistics to the logger.
/// This method does not modify the state of the buffers or cache.
/// </remarks>
public void LogBufferDiagnostic ()
{
_logger.Info(CultureInfo.InvariantCulture, "-------- Buffer diagnostics -------");
var cacheCount = _lruCacheDict.Count;
_logger.Info(CultureInfo.InvariantCulture, "LRU entries: {0}", cacheCount);
AcquireBufferListReaderLock();
_logger.Info(CultureInfo.InvariantCulture, "File: {0}\r\nBuffer count: {1}\r\nDisposed buffers: {2}", _fileName, _bufferList.Count, _bufferList.Count - cacheCount);
var lineNum = 0;
long disposeSum = 0;
long maxDispose = 0;
long minDispose = int.MaxValue;
for (var i = 0; i < _bufferList.Values.Count; ++i)
{
var buffer = _bufferList.Values[i];
if (buffer.StartLine != lineNum)
{
_logger.Error("Start line of buffer is: {0}, expected: {1}", buffer.StartLine, lineNum);
_logger.Info(CultureInfo.InvariantCulture, "Info of buffer follows:");
DumpBufferInfos(buffer);
}
lineNum += buffer.LineCount;
disposeSum += buffer.DisposeCount;
maxDispose = Math.Max(maxDispose, buffer.DisposeCount);
minDispose = Math.Min(minDispose, buffer.DisposeCount);
}
ReleaseBufferListReaderLock();
_logger.Info(CultureInfo.InvariantCulture, "Dispose count sum is: {0}\r\nMin dispose count is: {1}\r\nMax dispose count is: {2}\r\n-----------------------------------", disposeSum, minDispose, maxDispose);
}
#endif
#endregion
#region Private Methods
/// <summary>
/// Adds a log file to the collection and returns information about the added file.
/// </summary>
/// <param name="fileName">The path of the log file to add. Cannot be null or empty.</param>
/// <returns>An object that provides information about the added log file.</returns>
private ILogFileInfo AddFile (string fileName)
{
_logger.Info(CultureInfo.InvariantCulture, "Adding file to ILogFileInfoList: " + fileName);
var info = GetLogFileInfo(fileName);
_logFileInfoList.Add(info);
return info;
}
/// <summary>
/// Retrieves a contiguous range of log lines starting at the specified line number. Acquires locks once for the
/// entire batch, amortising synchronisation overhead.
/// </summary>
/// <param name="startLine">The zero-based line number of the first line to retrieve.</param>
/// <param name="count">The number of lines to retrieve. May be clamped to available lines.</param>
/// <returns>
/// An array of <see cref="ILogLineMemory"/> instances. The array length may be less than <paramref name="count"/>
/// if the end of file is reached. Entries may be null if a buffer is unavailable.
/// </returns>
public ILogLineMemory[] GetLogLineMemories (int startLine, int count)
{
if (_isDeleted || count <= 0)
{
return [];
}
var result = new ILogLineMemory[count];
var filled = 0;
AcquireBufferListReaderLock();
try
{
var lineNum = startLine;
while (filled < count)
{
var (logBuffer, _) = GetBufferForLineWithIndex(lineNum);
if (logBuffer == null)
{
break;
}
// Protect against concurrent disposal