/
EventLogReader.cs
325 lines (268 loc) · 10.5 KB
/
EventLogReader.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using Microsoft.Win32;
namespace System.Diagnostics.Eventing.Reader
{
/// <summary>
/// This public class is used for reading event records from event log.
/// </summary>
public class EventLogReader : IDisposable
{
private readonly EventLogQuery _eventQuery;
private int _batchSize;
//
// access to the data member reference is safe, while
// invoking methods on it is marked SecurityCritical as appropriate.
//
private readonly EventLogHandle _handle;
/// <summary>
/// events buffer holds batched event (handles).
/// </summary>
private IntPtr[] _eventsBuffer;
/// <summary>
/// The current index where the function GetNextEvent is (inside the eventsBuffer).
/// </summary>
private int _currentIndex;
/// <summary>
/// The number of events read from the batch into the eventsBuffer
/// </summary>
private int _eventCount;
/// <summary>
/// When the reader finishes (will always return only ERROR_NO_MORE_ITEMS).
/// For subscription, this means we need to wait for next event.
/// </summary>
private bool _isEof;
/// <summary>
/// Maintains cached display / metadata information returned from
/// EventRecords that were obtained from this reader.
/// </summary>
private readonly ProviderMetadataCachedInformation _cachedMetadataInformation;
public EventLogReader(string path)
: this(new EventLogQuery(path, PathType.LogName), null)
{
}
public EventLogReader(string path, PathType pathType)
: this(new EventLogQuery(path, pathType), null)
{
}
public EventLogReader(EventLogQuery eventQuery)
: this(eventQuery, null)
{
}
public EventLogReader(EventLogQuery eventQuery, EventBookmark bookmark)
{
ArgumentNullException.ThrowIfNull(eventQuery);
string logfile = null;
if (eventQuery.ThePathType == PathType.FilePath)
logfile = eventQuery.Path;
_cachedMetadataInformation = new ProviderMetadataCachedInformation(eventQuery.Session, logfile, 50);
// Explicit data
_eventQuery = eventQuery;
// Implicit
_batchSize = 64;
_eventsBuffer = new IntPtr[_batchSize];
//
// compute the flag.
//
int flag = 0;
if (_eventQuery.ThePathType == PathType.LogName)
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryChannelPath;
else
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryFilePath;
if (_eventQuery.ReverseDirection)
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryReverseDirection;
if (_eventQuery.TolerateQueryErrors)
flag |= (int)UnsafeNativeMethods.EvtQueryFlags.EvtQueryTolerateQueryErrors;
_handle = NativeWrapper.EvtQuery(_eventQuery.Session.Handle,
_eventQuery.Path, _eventQuery.Query,
flag);
EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark);
if (!bookmarkHandle.IsInvalid)
{
using (bookmarkHandle)
{
NativeWrapper.EvtSeek(_handle, 1, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark);
}
}
}
public int BatchSize
{
get
{
return _batchSize;
}
set
{
if (value < 1)
throw new ArgumentOutOfRangeException(nameof(value));
_batchSize = value;
}
}
private bool GetNextBatch(TimeSpan ts)
{
int timeout = -1;
if (ts != TimeSpan.MaxValue)
timeout = (int)ts.TotalMilliseconds;
// batchSize was changed by user, reallocate buffer.
if (_batchSize != _eventsBuffer.Length)
_eventsBuffer = new IntPtr[_batchSize];
int newEventCount = 0;
bool results = NativeWrapper.EvtNext(_handle, _batchSize, _eventsBuffer, timeout, 0, ref newEventCount);
if (!results)
{
_eventCount = 0;
_currentIndex = 0;
return false; // No more events in the result set
}
_currentIndex = 0;
_eventCount = newEventCount;
return true;
}
public EventRecord ReadEvent()
{
return ReadEvent(TimeSpan.MaxValue);
}
public EventRecord ReadEvent(TimeSpan timeout)
{
if (_isEof)
throw new InvalidOperationException();
if (_currentIndex >= _eventCount)
{
// buffer is empty, get next batch.
GetNextBatch(timeout);
if (_currentIndex >= _eventCount)
{
_isEof = true;
return null;
}
}
EventLogRecord eventInstance = new EventLogRecord(new EventLogHandle(_eventsBuffer[_currentIndex], true), _eventQuery.Session, _cachedMetadataInformation);
_currentIndex++;
return eventInstance;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
while (_currentIndex < _eventCount)
{
NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]);
_currentIndex++;
}
if (_handle != null && !_handle.IsInvalid)
_handle.Dispose();
}
internal void SeekReset()
{
//
// Close all unread event handles in the buffer
//
while (_currentIndex < _eventCount)
{
NativeWrapper.EvtClose(_eventsBuffer[_currentIndex]);
_currentIndex++;
}
// Reset the indexes used by Next
_currentIndex = 0;
_eventCount = 0;
_isEof = false;
}
internal void SeekCommon(long offset)
{
//
// modify offset that we're going to send to service to account for the
// fact that we've already read some events in our buffer that the user
// hasn't seen yet.
//
offset -= (_eventCount - _currentIndex);
SeekReset();
NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToCurrent);
}
public void Seek(EventBookmark bookmark)
{
Seek(bookmark, 0);
}
public void Seek(EventBookmark bookmark, long offset)
{
ArgumentNullException.ThrowIfNull(bookmark);
SeekReset();
using (EventLogHandle bookmarkHandle = EventLogRecord.GetBookmarkHandleFromBookmark(bookmark))
{
NativeWrapper.EvtSeek(_handle, offset, bookmarkHandle, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToBookmark);
}
}
public void Seek(SeekOrigin origin, long offset)
{
switch (origin)
{
case SeekOrigin.Begin:
SeekReset();
NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToFirst);
return;
case SeekOrigin.End:
SeekReset();
NativeWrapper.EvtSeek(_handle, offset, EventLogHandle.Zero, 0, UnsafeNativeMethods.EvtSeekFlags.EvtSeekRelativeToLast);
return;
case SeekOrigin.Current:
if (offset >= 0)
{
// We can reuse elements in the batch.
if (_currentIndex + offset < _eventCount)
{
//
// We don't call Seek here, we can reposition within the batch.
//
// Close all event handles between [currentIndex, currentIndex + offset)
int index = _currentIndex;
while (index < _currentIndex + offset)
{
NativeWrapper.EvtClose(_eventsBuffer[index]);
index++;
}
_currentIndex = (int)(_currentIndex + offset);
// Leave the eventCount unchanged
// Leave the same Eof
}
else
{
SeekCommon(offset);
}
}
else
{
SeekCommon(offset);
}
return;
}
}
public void CancelReading()
{
NativeWrapper.EvtCancel(_handle);
}
public IList<EventLogStatus> LogStatus
{
get
{
EventLogHandle queryHandle = _handle;
if (queryHandle.IsInvalid)
throw new InvalidOperationException();
string[] channelNames = (string[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryNames);
int[] errorStatuses = (int[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryStatuses);
if (channelNames.Length != errorStatuses.Length)
throw new InvalidOperationException();
var list = new List<EventLogStatus>(channelNames.Length);
for (int i = 0; i < channelNames.Length; i++)
{
EventLogStatus cs = new EventLogStatus(channelNames[i], errorStatuses[i]);
list.Add(cs);
}
return list.AsReadOnly();
}
}
}
}