예제 #1
0
        public void TestEventXml2PollingSource()
        {
            ListEventSink records = new ListEventSink();
            var           config  = TestUtility.GetConfig("Sources", "ApplicationLogWithEventData");

            using (WindowsEventPollingSource source = new WindowsEventPollingSource(LogName, PollingSourceQuery, false, new PluginContext(config, null, null, _bookmarkManager)))
            {
                source.Subscribe(records);
                source.Start();

                string msg     = $"Message generated by EventLogTest {DateTime.Now}";
                int    eventId = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId);

                System.Threading.Thread.Sleep(1000);

                source.Stop();
            }

            string xml       = ((RawEventRecordEnvelope)records[0]).GetMessage("xml2");
            var    xDocument = XDocument.Parse(xml);
            var    xRoot     = xDocument.Root;

            Assert.Equal("Event", xRoot.Name.LocalName);
            XNamespace ns = xRoot.GetDefaultNamespace();

            Assert.NotNull(xRoot.Element(ns + "System"));
            Assert.NotNull(xRoot.Element(ns + "EventData"));
        }
        private async Task CreateAndRunWatcher <TData>(string testName, string filter, IConfiguration config, Func <List <IEnvelope>, Task> testBody, IRecordParser <TData, LogContext> recordParser, ILogger logger, TestDirectory directory = null)
        {
            //Create a distinct directory based on testName so that tests can run in parallel
            string testDir = Path.Combine(TestUtility.GetTestHome(), testName);

            if (directory == null)
            {
                //The following will creates all directories and subdirectories in the specified path unless they already exist.
                Directory.CreateDirectory(testDir);

                //Clean up before the test rather than after so that we can inspect the files
                DeleteFiles(testDir, "*.*");
            }
            else
            {
                this.SetUpTestDirectory(directory, TestUtility.GetTestHome());
            }

            ListEventSink logRecords = new ListEventSink();

            DirectorySource <TData, LogContext> watcher = new DirectorySource <TData, LogContext>
                                                              (testDir, filter, 1000, new PluginContext(config, logger, null), recordParser);

            watcher.Subscribe(logRecords);
            watcher.Start();

            await testBody(logRecords);

            watcher.Stop();
        }
        public void TestEOSWithIncludeSubdirectories()
        {
            string sourceId = "TestEOSWithIncludeSubdirectories";
            var    subDir1  = "CPU";
            var    subDir2  = "Memory";

            var subdirectories = new string[] { subDir1, subDir2 };

            Setup(sourceId, subdirectories);

            WriteLogs("A", 2, subDir1);
            WriteLogs("B", 3, subDir2);

            ListEventSink logRecords = new ListEventSink();
            var           config     = TestUtility.GetConfig("Sources", "IncludeSubdirectories");
            DirectorySource <IDictionary <string, string>, LogContext> watcher = CreateDirectorySource(sourceId, "log_?.log", logRecords, config);

            watcher.InitialPosition = InitialPositionEnum.EOS;
            watcher.Start();
            Thread.Sleep(2000);
            watcher.Stop();
            Assert.Empty(logRecords);

            watcher.Start();
            WriteLogs("B", 1, subDir1);
            WriteLogs("C", 5, subDir2);
            Thread.Sleep(2000);
            watcher.Stop();

            Assert.Equal(6, logRecords.Count);
        }
예제 #4
0
        public void TestBookmark()
        {
            string sourceId = "TestDirectorySourceBookmark";

            Setup(sourceId);

            WriteLogs("A", 2);
            WriteLogs("B", 3);

            ListEventSink logRecords = new ListEventSink();
            DirectorySource <IDictionary <string, string>, LogContext> watcher = CreateDirectorySource(sourceId, logRecords);

            watcher.InitialPosition = InitialPositionEnum.Bookmark;
            watcher.Start();
            Thread.Sleep(2000);
            watcher.Stop();
            Assert.Empty(logRecords);

            WriteLogs("B", 1);
            WriteLogs("C", 5);

            watcher.Start();
            WriteLogs("D", 7);
            Thread.Sleep(2000);
            watcher.Stop();

            Assert.Equal(13, logRecords.Count);
        }
        public async Task InitialPositionBOS(bool polling)
        {
            var sink = new ListEventSink();
            var msg  = "A fresh message";

            // Write some events before the source is created
            for (var i = 0; i < 3; i++)
            {
                EventLog.WriteEntry(_logSource, msg, EventLogEntryType.Information);
            }

            await Task.Delay(100);

            var bm = new FileBookmarkManager(_bookmarkDir, NullLogger.Instance, _appDataFileProvider);

            var cts    = new CancellationTokenSource();
            var source = CreateSource(polling, LogName, bm, InitialPositionEnum.BOS);

            var subscription = source.Subscribe(sink);

            await bm.StartAsync(cts.Token);

            await source.StartAsync(cts.Token);

            await Task.Delay(1000);

            Assert.Equal(3, sink.Count);

            cts.Cancel();
            await source.StopAsync(default);
예제 #6
0
        public void TestInitialPositionEOS()
        {
            ListEventSink records = new ListEventSink();

            GenerateAndCaptureEvents(records, null);

            Assert.True(records.Count > 0);
        }
예제 #7
0
        public void TestEventData()
        {
            ListEventSink records = new ListEventSink();
            var           config  = TestUtility.GetConfig("Sources", "ApplicationLogWithEventData");

            GenerateAndCaptureEvents(records, config);

            Assert.True(((EventRecordEnvelope)records[0]).Data.EventData.Count > 0);
        }
예제 #8
0
        private async Task CreateAndRunWatcher <TData>(string filter, IConfiguration config, Func <List <IEnvelope>, Task> testBody, IRecordParser <TData, LogContext> recordParser)
        {
            ListEventSink logRecords = new ListEventSink();
            DirectorySource <TData, LogContext> watcher = new DirectorySource <TData, LogContext>
                                                              (TestUtility.GetTestHome(), filter, 1000, new PluginContext(config, NullLogger.Instance, null), recordParser, DirectorySourceFactory.CreateLogSourceInfo);

            watcher.Subscribe(logRecords);
            watcher.Start();

            await testBody(logRecords);

            watcher.Stop();
        }
예제 #9
0
        public void TestEventXml2()
        {
            ListEventSink records = new ListEventSink();
            var           config  = TestUtility.GetConfig("Sources", "ApplicationLogWithEventData");

            GenerateAndCaptureEvents(records, config);
            string xml       = ((EventRecordEnvelope)records[0]).GetMessage("xml2");
            var    xDocument = XDocument.Parse(xml);
            var    xRoot     = xDocument.Root;

            Assert.Equal("Event", xRoot.Name.LocalName);
            XNamespace ns = xRoot.GetDefaultNamespace();

            Assert.NotNull(xRoot.Element(ns + "System"));
            Assert.NotNull(xRoot.Element(ns + "EventData"));
        }
예제 #10
0
        private void GenerateAndCaptureEvents(ListEventSink records, IConfiguration config)
        {
            using (EventLogSource source = new EventLogSource(LogName, null, new PluginContext(config, null, null, _bookmarkManager)))
            {
                source.Subscribe(records);
                source.Start();

                string msg     = $"Message generated by EventLogTest {DateTime.Now}";
                int    eventId = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId);

                System.Threading.Thread.Sleep(1000);

                source.Stop();
            }
        }
예제 #11
0
        public void TestInitialPositionBookMarkPollingSource()
        {
            ListEventSink records  = new ListEventSink();
            string        sourceId = "TestInitialPositionBookMark";

            DeleteExistingBookmarkFile(sourceId);

            //This should generate a water mark file
            using (WindowsEventPollingSource source = new WindowsEventPollingSource(LogName, PollingSourceQuery, false, new PluginContext(null, null, null, _bookmarkManager)))
            {
                source.Subscribe(records);
                source.Id = sourceId;
                source.InitialPosition = InitialPositionEnum.Bookmark;
                source.Start();

                var    nowUtc  = DateTime.UtcNow;
                string msg     = $"Message generated by EventLogTest {nowUtc}";
                int    eventId = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId);

                System.Threading.Thread.Sleep(1000);
                var foundRecord = records.FirstOrDefault(r => eventId.Equals(((RawEventRecordEnvelope)r).Data.Id));
                Assert.NotNull(foundRecord);
                Assert.True(foundRecord.Timestamp >= nowUtc); // Assert that the record exists and was created after the source stop.

                source.Stop();

                //Write some new logs after the source stop
                DateTime dateTime2Utc = DateTime.UtcNow;
                int      eventId2     = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                msg = $"Message generated by EventLogTest {dateTime2Utc}";
                records.Clear();
                EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId2);
                System.Threading.Thread.Sleep(1000);

                records.Clear();

                source.Reset();
                source.Start();
                System.Threading.Thread.Sleep(5000);
                //Should get the record when the source is stopped
                var foundRecord2 = records.FirstOrDefault(r => eventId2.Equals(((RawEventRecordEnvelope)r).Data.Id));
                Assert.NotNull(foundRecord2);
                Assert.True(foundRecord2.Timestamp >= dateTime2Utc); // Assert that the record exists and was created after the source stop.
            }
        }
예제 #12
0
        public void TestInitialPositionBookMark()
        {
            string        logName   = "Application";
            string        logSource = "Test";
            ListEventSink records   = new ListEventSink();
            string        sourceId  = "TestInitialPositionBookMark";

            DeleteExistingBookmarkFile(sourceId);

            //This should generate a water mark file
            using (EventLogSource source = new EventLogSource(logName, null, new PluginContext(null, null, null)))
            {
                source.Subscribe(records);
                source.Id = sourceId;
                source.InitialPosition = InitialPositionEnum.Bookmark;
                source.Start();

                var    nowUtc  = DateTime.UtcNow;
                string msg     = $"Message generated by EventLogTest {nowUtc}";
                int    eventId = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                if (!EventLog.SourceExists(logSource))
                {
                    EventLog.CreateEventSource(logSource, logName);
                }
                EventLog.WriteEntry(logSource, msg, EventLogEntryType.Information, eventId);

                System.Threading.Thread.Sleep(1000);
                source.Stop();

                //Write some new logs after the source stop
                DateTime dateTime2Utc = DateTime.UtcNow;
                msg = $"Message generated by EventLogTest {dateTime2Utc}";
                EventLog.WriteEntry(logSource, msg, EventLogEntryType.Information, eventId);
                System.Threading.Thread.Sleep(1000);


                records.Clear();
                source.Start();
                System.Threading.Thread.Sleep(1000);
                //Should get the record when the source is stopped
                var foundRecord = records.FirstOrDefault(r => msg.Equals(((EventRecordEnvelope)r).Data.Description));
                Assert.NotNull(foundRecord);
                Assert.True(foundRecord.Timestamp >= dateTime2Utc);
            }
        }
예제 #13
0
        public void TestInitialPositionTimeStamp()
        {
            string        logName          = "Application";
            string        logSource        = "EventLogTest";
            ListEventSink records          = new ListEventSink();
            DateTime      initialTimestamp = DateTime.Now.AddDays(-1);
            DateTime      nowUtc           = DateTime.UtcNow;
            string        sourceId         = "TestInitialPositionTimeStamp";

            DeleteExistingBookmarkFile(sourceId);

            using (EventLogSource source = new EventLogSource(logName, null, new PluginContext(null, null, null, _bookmarkManager)))
            {
                source.Subscribe(records);
                source.Id = sourceId;
                source.InitialPosition          = InitialPositionEnum.Timestamp;
                source.InitialPositionTimestamp = initialTimestamp;
                source.Start();

                do
                {
                    EventLog.WriteEntry(logSource, "A fresh message", EventLogEntryType.Information, 0);
                    System.Threading.Thread.Sleep(1000);
                }while (source.LastEventLatency > new TimeSpan(0, 0, 1));

                source.Stop();
                Assert.True(records.Count > 0, "There is an event after the timestamp.");
                Assert.True(records[0].Timestamp >= initialTimestamp.ToUniversalTime() && records[0].Timestamp < nowUtc, "There is an earlier event after the initial timestamp.");
                DateTime dateTime1 = records[records.Count - 1].Timestamp;

                //Write some new logs after the source stop
                DateTime dateTime2 = DateTime.Now;
                string   msg       = $"Message generated by EventLogTest {dateTime2}";
                int      eventId   = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                EventLog.WriteEntry(logSource, msg, EventLogEntryType.Information, eventId);
                System.Threading.Thread.Sleep(1000);

                records.Clear();
                source.Start();
                System.Threading.Thread.Sleep(2000);
                //Should get the record when the source is stopped
                Assert.True(records.Count > 0, "Should get the new record.");
                Assert.True(records[0].Timestamp >= dateTime1, "Should pick up new records.");
            }
        }
예제 #14
0
        public void TestInitialPositionTimeStampPollingSource()
        {
            ListEventSink records          = new ListEventSink();
            DateTime      initialTimestamp = DateTime.Now.AddDays(-1);
            DateTime      nowUtc           = DateTime.UtcNow;
            string        sourceId         = "TestInitialPositionTimeStamp";

            DeleteExistingBookmarkFile(sourceId);

            using (WindowsEventPollingSource source = new WindowsEventPollingSource(LogName, PollingSourceQuery, false, new PluginContext(null, null, null, _bookmarkManager)))
            {
                source.Subscribe(records);
                source.Id = sourceId;
                source.InitialPosition          = InitialPositionEnum.Timestamp;
                source.InitialPositionTimestamp = initialTimestamp;
                source.Start();

                do
                {
                    EventLog.WriteEntry(LogSource, "A fresh message", EventLogEntryType.Information, 0);
                    System.Threading.Thread.Sleep(1000);
                }while (source.LastEventLatency > new TimeSpan(0, 0, 1));

                source.Stop();
                Assert.True(records.Count > 0, "There is an event after the timestamp.");
                Assert.True(records[0].Timestamp >= initialTimestamp.ToUniversalTime() && records[0].Timestamp < nowUtc, "There is an earlier event after the initial timestamp.");
                DateTime dateTime1 = records[records.Count - 1].Timestamp;

                //Write some new logs after the source stop
                DateTime dateTime2 = DateTime.Now;
                string   msg       = $"Message generated by EventLogTest {dateTime2}";
                int      eventId   = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                records.Clear();
                EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId);
                System.Threading.Thread.Sleep(1000);

                source.Reset();
                source.Start();
                System.Threading.Thread.Sleep(5000);
                //Should get the record when the source is stopped
                Assert.True(records.Count > 0, "Should get the new record.");
                var foundRecord = records.FirstOrDefault(r => eventId.Equals(((RawEventRecordEnvelope)r).Data.Id));
                Assert.True(foundRecord.Timestamp >= dateTime1); // Assert that the record exists and was created after the source stop.
            }
        }
        public void TestEventProcessing()
        {
            //Configure
            ListEventSink mockSink = new ListEventSink();

            using (EtwEventSource mockEtwSource = new MockEtwEventSource(MockTraceEvent.ClrProviderName, TraceEventLevel.Verbose, ulong.MaxValue, new PluginContext(null, null, null)))
            {
                mockEtwSource.Subscribe(mockSink);

                //Execute
                mockEtwSource.Start();
                mockEtwSource.Stop();
            }

            //Verify
            Assert.True(mockSink.Count == 1);
            Assert.True(mockSink[0] is EtwEventEnvelope);
            Assert.True(MockEtwEventEnvelope.ValidateEnvelope((EtwEventEnvelope)mockSink[0]), "Event envelope data or event data does not match expected values.");
        }
예제 #16
0
        public void TestInitialPositionBOS()
        {
            string        logName   = "Application";
            string        logSource = "Test";
            ListEventSink records   = new ListEventSink();
            DateTime      nowUtc    = DateTime.UtcNow;
            string        sourceId  = "TestInitialPositionTimeStamp";

            DeleteExistingBookmarkFile(sourceId);

            using (EventLogSource source = new EventLogSource(logName, null, new PluginContext(null, null, null)))
            {
                source.Subscribe(records);
                source.Id = sourceId;
                source.InitialPosition = InitialPositionEnum.BOS;
                source.Start();

                do
                {
                    EventLog.WriteEntry(logSource, "A fresh message", EventLogEntryType.Information, 0);
                    System.Threading.Thread.Sleep(1000);
                }while (source.LastEventLatency > new TimeSpan(0, 0, 1));
                System.Threading.Thread.Sleep(1000);

                source.Stop();
                Assert.True(records.Count > 0);
                Assert.True(records[0].Timestamp < nowUtc);

                //Write some new logs after the source stop
                DateTime dateTime2Utc = DateTime.UtcNow;
                string   msg          = $"Message generated by EventLogTest {dateTime2Utc}";
                int      eventId      = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                EventLog.WriteEntry(logSource, msg, EventLogEntryType.Information, eventId);
                System.Threading.Thread.Sleep(1000);

                records.Clear();
                source.Start();
                System.Threading.Thread.Sleep(1000);
                //Should get the record when the source is stopped
                Assert.True(records.Count > 0);
                Assert.True(records[0].Timestamp >= dateTime2Utc);
            }
        }
        public void TestInitialPositionBookMark()
        {
            string        logName   = "Application";
            string        logSource = "Test";
            ListEventSink records   = new ListEventSink();
            string        sourceId  = "TestInitialPositionBookMark";

            DeleteExistingBookmarkFile(sourceId);

            //This should generate a water mark file
            using (EventLogSource source = new EventLogSource(logName, null, new PluginContext(null, null, null)))
            {
                source.Subscribe(records);
                source.Id = sourceId;
                source.InitialPosition = InitialPositionEnum.Bookmark;
                source.Start();

                string msg     = $"Message generated by EvengLogTest {DateTime.Now}";
                int    eventId = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                if (!EventLog.SourceExists(logSource))
                {
                    EventLog.CreateEventSource(logSource, logName);
                }
                EventLog.WriteEntry(logSource, msg, EventLogEntryType.Information, eventId);

                System.Threading.Thread.Sleep(1000);
                source.Stop();

                //Write some new logs afte the source stop
                DateTime dateTime2 = DateTime.Now;
                msg = $"Message generated by EvengLogTest {dateTime2}";
                EventLog.WriteEntry(logSource, msg, EventLogEntryType.Information, eventId);
                System.Threading.Thread.Sleep(1000);


                records.Clear();
                source.Start();
                System.Threading.Thread.Sleep(1000);
                //Should get the record when the souce is stopped
                Assert.True(records.Count > 0);
                Assert.True(records[0].Timestamp >= dateTime2);
            }
        }
예제 #18
0
        public void TestInitialPositionEOSPollingSource()
        {
            ListEventSink records = new ListEventSink();

            using (WindowsEventPollingSource source = new WindowsEventPollingSource(LogName, null, false, new PluginContext(null, null, null, _bookmarkManager)))
            {
                source.Subscribe(records);
                source.Start();

                string msg     = $"Message generated by EventLogTest {DateTime.Now}";
                int    eventId = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId);

                System.Threading.Thread.Sleep(1000);

                source.Stop();
            }

            Assert.True(records.Count > 0);
        }
예제 #19
0
        private static void GenerateAndCaptureEvents(ListEventSink records, IConfiguration config)
        {
            string logName   = "Application";
            string logSource = "Test";

            using (EventLogSource source = new EventLogSource(logName, null, new PluginContext(config, null, null)))
            {
                source.Subscribe(records);
                source.Start();

                string msg     = $"Message generated by EvengLogTest {DateTime.Now}";
                int    eventId = (int)(DateTime.Now.Ticks % ushort.MaxValue);
                if (!EventLog.SourceExists(logSource))
                {
                    EventLog.CreateEventSource(logSource, logName);
                }
                EventLog.WriteEntry(logSource, msg, EventLogEntryType.Information, eventId);

                System.Threading.Thread.Sleep(1000);

                source.Stop();
            }
        }
예제 #20
0
        public void TestTimestamp()
        {
            string sourceId = "TestDirectorySourceTimestamp";

            Setup(sourceId);

            WriteLogs("A", 1);
            Thread.Sleep(200);

            DateTime timestamp = DateTime.Now;

            Thread.Sleep(1000);

            WriteLogs("A", 2);
            WriteLogs("B", 3);

            ListEventSink logRecords = new ListEventSink();
            DirectorySource <IDictionary <string, string>, LogContext> watcher = CreateDirectorySource(sourceId, logRecords);

            watcher.InitialPosition          = InitialPositionEnum.Timestamp;
            watcher.InitialPositionTimestamp = timestamp;
            watcher.Start();
            Thread.Sleep(2000);
            watcher.Stop();
            Assert.Equal(5, logRecords.Count);
            logRecords.Clear();

            WriteLogs("B", 1);
            WriteLogs("C", 5);

            watcher.Start();
            WriteLogs("D", 7);
            Thread.Sleep(2000);
            watcher.Stop();

            Assert.Equal(13, logRecords.Count);
        }
예제 #21
0
        public async Task TestJsonLog(string sourceId)
        {
            var config = TestUtility.GetConfig("Sources", sourceId);
            var dir    = config["Directory"];

            Directory.CreateDirectory(dir);
            var logFile = Path.Combine(dir, $"{Guid.NewGuid()}.log");

            File.WriteAllText(logFile, LOG);

            try
            {
                var source = new DirectorySource <JObject, LogContext>(dir, config["FileNameFilter"],
                                                                       1000, new PluginContext(config, NullLogger.Instance, null),
                                                                       new SingleLineJsonParser(config["TimestampField"], config["TimestampFormat"], NullLogger.Instance))
                {
                    InitialPosition = InitialPositionEnum.BOS
                };
                var sink = new ListEventSink();
                source.Subscribe(sink);
                source.Start();

                await Task.Delay(2000);

                Assert.Equal(2, sink.Count);

                var record0 = sink[0] as LogEnvelope <JObject>;
                Assert.Equal(new DateTime(2018, 9, 21, 8, 38, 50, 972), record0.Timestamp);
                Assert.Equal("UserProfile", record0.Data["ul-log-data"]["method_name"]);
                Assert.Equal("INFO", record0.Data["ul-tag-status"]);
            }
            finally
            {
                File.Delete(logFile);
            }
        }
예제 #22
0
 public void SetUp()
 {
     _list      = new NuGenList <int>();
     _eventSink = new ListEventSink <int>(_list);
 }
        private DirectorySource <IDictionary <string, string>, LogContext> CreateDirectorySource(string sourceId, string filter, ListEventSink logRecords, IConfiguration config = null)
        {
            DirectorySource <IDictionary <string, string>, LogContext> watcher = new DirectorySource <IDictionary <string, string>, LogContext>
                                                                                     (BookmarkDirectory,
                                                                                     filter,
                                                                                     1000,
                                                                                     new PluginContext(config, NullLogger.Instance, null),
                                                                                     new TimeStampRecordParser(RECORD_TIME_STAMP_FORMAT, null, DateTimeKind.Utc));

            watcher.Id = sourceId;
            watcher.Subscribe(logRecords);
            return(watcher);
        }
예제 #24
0
        private DirectorySource <IDictionary <string, string>, LogContext> CreateDirectorySource(string sourceId, ListEventSink logRecords)
        {
            DirectorySource <IDictionary <string, string>, LogContext> watcher = new DirectorySource <IDictionary <string, string>, LogContext>
                                                                                     (BookmarkDirectory,
                                                                                     "log_?.log",
                                                                                     1000,
                                                                                     new PluginContext(null, NullLogger.Instance, null),
                                                                                     new TimeStampRecordParser(RECORD_TIME_STAMP_FORMAT, null, DateTimeKind.Utc),
                                                                                     DirectorySourceFactory.CreateLogSourceInfo);

            watcher.Id = sourceId;
            watcher.Subscribe(logRecords);
            return(watcher);
        }
        public void TestInitialPositionBOS(bool acknowledge)
        {
            var records  = new ListEventSink();
            var sourceId = "TestEvtInitialPositionTimeStamp";
            var eventId  = (int)(DateTime.Now.Ticks % ushort.MaxValue);
            var msg      = "A fresh message";

            // Write some events before the source is created
            for (int i = 0; i < 3; i++)
            {
                EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId);
            }

            var now = DateTime.UtcNow;

            using (var source = CreateSource(sourceId, eventId))
            {
                source.Subscribe(records);
                source.Id = sourceId;
                source.InitialPosition = InitialPositionEnum.BOS;
                source.Start();

                for (int i = 0; i < 5; i++)
                {
                    EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId);
                }

                Thread.Sleep(5000);

                if (acknowledge)
                {
                    // Send the acknowledgements as if they had come from sources.
                    var bookmark = Assert.IsType <BookmarkInfo>(BookmarkManager.GetBookmark(sourceId));
                    BookmarkManager.SaveBookmark(bookmark.Id, records.Last().Position, null);
                }

                source.Stop();
                Thread.Sleep(1000);

                Assert.True(records[0].Timestamp < now, $"First record should have been written before {now}, but was written at {records[0].Timestamp}");

                var lastRecordTimestamp = records.Last().Timestamp;
                Assert.True(lastRecordTimestamp > now, $"Last record should have been written after {now}, but was written at {records.Last().Timestamp}");

                records.Clear();

                //Write some new logs after the source stop
                var newmsg = "A fresh message after source stop";
                EventLog.WriteEntry(LogSource, newmsg, EventLogEntryType.Information, eventId);
                Thread.Sleep(1000);
                source.Start();
                Thread.Sleep(3000);

                IEnvelope lastRecord;
                if (acknowledge)
                {
                    lastRecord = Assert.Single(records);
                }
                else
                {
                    Assert.Equal(9, records.Count);
                    lastRecord = records.Last();
                }

                Assert.True(lastRecord.Timestamp > lastRecordTimestamp);
                Assert.Matches("after source stop", lastRecord.GetMessage("string"));
            }
        }
        public void TestInitialPositionBookMark(bool acknowledge)
        {
            var records  = new ListEventSink();
            var sourceId = "TestEvtInitialPositionBookMark";
            var eventId  = (int)(DateTime.Now.Ticks % ushort.MaxValue);
            var msg      = "A fresh message";

            // Write some events before the source is created
            for (int i = 0; i < 3; i++)
            {
                EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId);
            }

            var now = DateTime.UtcNow;

            using (var source = CreateSource(sourceId, eventId))
            {
                source.Subscribe(records);
                source.Id = sourceId;
                source.InitialPosition = InitialPositionEnum.Bookmark;
                source.Start();

                Thread.Sleep(2000);

                // When using Bookmark as Initial position, and there is no bookmark, it should not process old events.
                Assert.Empty(records);

                EventLog.WriteEntry(LogSource, msg, EventLogEntryType.Information, eventId);

                Thread.Sleep(1000);

                if (acknowledge)
                {
                    // Send the acknowledgements as if they had come from sources.
                    var bookmark = Assert.IsType <BookmarkInfo>(BookmarkManager.GetBookmark(sourceId));
                    BookmarkManager.SaveBookmark(bookmark.Id, records.Last().Position, null);
                }

                source.Stop();
                Thread.Sleep(1000);

                var lastRecordTimestamp = Assert.Single(records).Timestamp;
                Assert.True(lastRecordTimestamp > now);

                records.Clear();

                //Write some new logs after the source stop
                var newmsg = "A fresh message after source stop";
                EventLog.WriteEntry(LogSource, newmsg, EventLogEntryType.Information, eventId);
                Thread.Sleep(1000);
                source.Start();
                Thread.Sleep(1000);

                // If it's a clean shutdown (i.e. config reload), the bookmark isn't removed from BookmarkManager,
                // so the source should pick up where it left off according to the previous bookmark value.
                if (acknowledge)
                {
                    var lastRecord = Assert.Single(records);
                    Assert.True(lastRecord.Timestamp > lastRecordTimestamp);
                    Assert.Matches("after source stop", lastRecord.GetMessage("string"));
                }
                else
                {
                    // When using Bookmark as Initial position, and there is no bookmark, it should not process old events.
                    // Since we didn't commit the bookmark in this theory, no records should be returned.
                    Assert.Empty(records);
                }
            }
        }
 private DirectorySource <IDictionary <string, string>, LogContext> CreateDirectorySource(string sourceId, ListEventSink logRecords)
 {
     return(CreateDirectorySource(sourceId, "log_?.log", logRecords));
 }
예제 #28
0
		public void SetUp()
		{
			_list = new NuGenList<int>();
			_eventSink = new ListEventSink<int>(_list);
		}