Example #1
0
        public void WhenUsingCustomFormatter()
        {
            string fileName = "FlatFileOutProcConfigCF2.log";

            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;

            IEnumerable <string> entries = null;
            var svcConfiguration         = TraceEventServiceConfiguration.Load("Configurations\\CustomSink\\FlatFileCustomFormatter2.xml");

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                try
                {
                    collector.Start();
                    logger.LogSomeMessage("some message using formatter");

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 1, "----------");
                }
                finally
                {
                    collector.Stop();
                }
            }

            StringAssert.Contains(entries.First(), "Mock SourceId");
            StringAssert.Contains(entries.First(), "Mock EventId");
            StringAssert.Contains(entries.First(), "Payload : [message : some message using formatter]");
        }
Example #2
0
        public void WhenUsingCustomSinkWithoutSchema()
        {
            string fileName = "ProvidedCustomSink.log";

            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;

            IEnumerable <string> entries = null;
            var svcConfiguration         = TraceEventServiceConfiguration.Load("Configurations\\CustomSink\\MockFlatFileSink.xml");

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                try
                {
                    collector.Start();
                    logger.LogSomeMessage("some message");
                    logger.LogSomeMessage("some message2");
                    logger.LogSomeMessage("some message3");

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 3, "==-==");
                }
                finally
                {
                    collector.Stop();
                }
            }

            Assert.AreEqual <int>(3, entries.Count());
            Assert.IsNotNull(entries.SingleOrDefault(e => e.Contains("Payload : [message : some message]")));
            Assert.IsNotNull(entries.SingleOrDefault(e => e.Contains("Payload : [message : some message2]")));
            Assert.IsNotNull(entries.SingleOrDefault(e => e.Contains("Payload : [message : some message3]")));
        }
        public void WhenUsingSinkThroughConfig()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;

            DatabaseHelper.CleanLoggingDB(validConnectionString);
            var logger = MockEventSourceOutProc.Logger;

            System.Data.DataTable eventsDataTable = null;
            var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\SqlDatabase\\SqlDB.xml");

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                collector.Start();
                try
                {
                    for (int n = 0; n < 10; n++)
                    {
                        logger.LogSomeMessage("some message" + n.ToString());
                    }

                    eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 10);
                }
                finally
                {
                    collector.Stop();
                }
            }

            Assert.AreEqual(10, eventsDataTable.Rows.Count);
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message");
        }
        public void WhenEnumsInPayloadInJson()
        {
            string fileName = @".\Logs\FlatFileJsonAndEnums.log";

            FlatFileHelper.DeleteDirectory(@".\Logs");
            var logger = MockEventSourceOutProcEnum.Logger;

            IEnumerable <TestEventEntryCustomTimeStamp> entries;

            using (var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\WithFormatter\\FlatFileJsonAndEnums.xml"))
                using (var evtService = new TraceEventService(svcConfiguration))
                {
                    evtService.Start();
                    try
                    {
                        logger.SendEnumsEvent15(MockEventSourceOutProcEnum.MyColor.Blue, MockEventSourceOutProcEnum.MyFlags.Flag2);
                        entries = FlatFileHelper.PollUntilJsonEventsAreWritten <TestEventEntryCustomTimeStamp>(fileName, 1);
                    }
                    finally
                    {
                        evtService.Stop();
                    }
                }

            Assert.AreEqual(1, entries.Count());
            var entry = entries.First();

            Assert.AreEqual(2, entry.Payload.Count);
            Assert.AreEqual((long)MockEventSourceOutProcEnum.MyColor.Blue, (long)entry.Payload["a"]);
            Assert.AreEqual((long)MockEventSourceOutProcEnum.MyFlags.Flag2, (long)entry.Payload["b"]);
        }
Example #5
0
        public void WhenEventWithGuidPramLoggedInXml()
        {
            string fileName = "FlatFileXmlFormatterAndGuids.log";

            File.Delete(fileName);
            var logger = MockEventSourceOutProcEnum.Logger;

            var testGuid = Guid.NewGuid();
            IEnumerable <XElement> entries;

            using (var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\WithFormatter\\FlatFileXmlFormatterAndGuids.xml"))
                using (var evtService = new TraceEventService(svcConfiguration))
                {
                    evtService.Start();
                    try
                    {
                        logger.SaveExpenseStarted(testGuid);
                        entries = FlatFileHelper.PollUntilXmlEventsAreWritten(fileName, 1);
                    }
                    finally
                    {
                        evtService.Stop();
                    }
                }

            Assert.AreEqual(1, entries.Count());
            XmlFormattedEntry.Fill(entries.Single());
            Assert.AreEqual <Guid>(MockEventSourceOutProcEnum.Logger.Guid, Guid.Parse(XmlFormattedEntry.Provider.Attribute("Guid").Value));
            Assert.AreEqual <int>(4, Convert.ToInt32(XmlFormattedEntry.EventId.Value));
            StringAssert.Contains(XmlFormattedEntry.Payload.ToString(), testGuid.ToString());
        }
        /// <summary>
        /// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
        /// </summary>
        /// <param name="args">Data passed by the start command.</param>
        protected override void OnStart(string[] args)
        {
            try
            {
                string configFile    = GetConfigFileFullPath();
                var    configuration = TraceEventServiceConfiguration.Load(configFile, monitorChanges: true);
                configuration.Settings.PropertyChanged += this.OnTraceEventServiceSettingsChanged;
                this.service = new TraceEventService(configuration);

                if (this.consoleMode)
                {
                    this.service.StatusChanged += this.OnServiceStatusChanged;
                }

                this.ShowConfiguration(configuration, configFile);
                this.EnableNonTransientErrorsHandling();

                this.service.Start();
            }
            catch (Exception e)
            {
                // log and rethrow to notify SCM
                if (!this.consoleMode)
                {
                    this.EventLog.WriteEntry(e.ToString(), EventLogEntryType.Error);
                }

                throw;
            }
        }
Example #7
0
        /// <summary>
        /// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts.
        /// </summary>
        /// <param name="args">Data passed by the start command.</param>
        protected override void OnStart(string[] args)
        {
            try
            {
                string configFile = GetConfigFileFullPath();
                var configuration = TraceEventServiceConfiguration.Load(configFile, monitorChanges: true);
                configuration.Settings.PropertyChanged += this.OnTraceEventServiceSettingsChanged;
                this.service = new TraceEventService(configuration);
                
                if (this.consoleMode)
                {
                    this.service.StatusChanged += this.OnServiceStatusChanged;
                }

                this.ShowConfiguration(configuration, configFile);
                this.EnableNonTransientErrorsHandling();

                this.service.Start();
            }
            catch (Exception e)
            {
                // log and rethrow to notify SCM
                if (!this.consoleMode)
                {
                    this.EventLog.WriteEntry(e.ToString(), EventLogEntryType.Error);
                }

                throw;
            }
        }
Example #8
0
        public void WhenCustomFormatterThrowsAnExceptionAndUsedConfig()
        {
            string fileName = "FlatFileOutProcCustomFormatterHandleExceptionViaConfig.log";

            File.Delete(fileName);
            var           logger    = MockEventSourceOutProc.Logger;
            MockFormatter formatter = new MockFormatter(true); //this formatter throws

            TraceEventServiceConfiguration svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\CustomSink\\FlatFileCustomFormatter.xml");

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
                using (InMemoryEventListener collectErrorsListener = new InMemoryEventListener(true))
                {
                    try
                    {
                        collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, System.Diagnostics.Tracing.EventLevel.Error, Keywords.All);
                        collector.Start();
                        logger.LogSomeMessage("some message using formatter that throws");
                        collectErrorsListener.WaitEvents.Wait(5000);

                        StringAssert.Contains(collectErrorsListener.ToString(), "Payload : [message : System.InvalidOperationException: Operation is not valid due to the current state of the object.");
                    }
                    finally
                    {
                        collector.Stop();
                        collectErrorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                    }
                }
        }
        public void ReconfigSameConfigTwiceWith2Listeners()
        {
            var fileName = "flatFileReconfig.log";

            File.Delete(fileName);
            var logger     = MockEventSourceOutProc.Logger;
            var configFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Configurations\\Reconfiguration\\temp\\configFile.xml";

            UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListener.xml", configFile);

            TraceEventServiceConfiguration svcConfiguration = TraceEventServiceConfiguration.Load(configFile, true);

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                collector.Start();

                try
                {
                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-flatFileListener", 1);
                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-dummyListener", 1);

                    UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListener.xml", configFile);

                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-flatFileListener", 1);
                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-dummyListener", 1);
                }
                finally
                {
                    collector.Stop();
                    File.Delete(configFile);
                }
            }
        }
Example #10
0
        public void SqlDatabaseCorrectConfigurationWithCustomTable()
        {
            var validConnectionString = ConfigurationManager.ConnectionStrings["valid"].ConnectionString;

            DatabaseHelper.CleanLoggingDB(validConnectionString);
            var logger = MockEventSourceOutProc.Logger;

            System.Data.DataTable eventsDataTable = null;
            var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\SqlDatabase\\SqlDatabaseCustomTable.xml");

            using (var evtService = new TraceEventService(svcConfiguration))
            {
                evtService.Start();
                try
                {
                    for (int n = 0; n < 10; n++)
                    {
                        logger.LogSomeMessage("some message" + n.ToString());
                    }

                    eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 10);
                }
                finally
                {
                    evtService.Stop();
                }
            }

            Assert.AreEqual(10, eventsDataTable.Rows.Count);
        }
        public void OutProcKeywordsFiltering()
        {
            var fileName = "keywordFiltering.log";

            File.Delete(fileName);
            var logger = MockEventSourceOutProcKeywords.Logger;

            IEnumerable <string> entries = null;

            using (TraceEventServiceConfiguration svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\KeywordFiltering\\keywordFiltering.xml"))
                using (TraceEventService collector = new TraceEventService(svcConfiguration))
                {
                    collector.Start();
                    try
                    {
                        logger.InformationalPage("some informational message filtered by Page keyword");
                        logger.InformationalDatabase("some informational message filtered by Database keyword");
                        logger.InformationalDiagnostic("some informational message filtered by Diagnostic keyword");
                        entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 2, "======");
                    }
                    finally
                    {
                        collector.Stop();
                    }
                }

            Assert.AreEqual(2, entries.Count());
            StringAssert.Contains(entries.First().ToString(), "some informational message filtered by Page keyword");
            StringAssert.Contains(entries.First().ToString(), "Keywords : 1");
            StringAssert.Contains(entries.Last().ToString(), "some informational message filtered by Database keyword");
            StringAssert.Contains(entries.Last().ToString(), "Keywords : 2");
        }
Example #12
0
        public void WhenCustomDateTimeFormatInXml()
        {
            string fileName = "FlatFileXmlFormatterDateTimeFormat.log";

            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;

            IEnumerable <XElement> entries;

            using (var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\WithFormatter\\FlatFileXmlFormatterDateTimeFormat.xml"))
                using (var evtService = new TraceEventService(svcConfiguration))
                {
                    evtService.Start();
                    try
                    {
                        logger.LogSomeMessage("logging using xml Formatter not indented");
                        entries = FlatFileHelper.PollUntilXmlEventsAreWritten(fileName, 1);
                    }
                    finally
                    {
                        evtService.Stop();
                    }
                }

            Assert.AreEqual(1, entries.Count());
            XmlFormattedEntry.Fill(entries.Single());
            var    dt = DateTime.UtcNow;
            string expectedTimestamp = dt.Day.ToString() + dt.Month.ToString() + dt.Year.ToString();

            StringAssert.Contains(XmlFormattedEntry.TimeCreated.ToString(), @"SystemTime=""" + expectedTimestamp + @"""");
        }
        public void OutProcWhenFormatterWithValuesForProperties()
        {
            string fileName = "FlatFileFormatterOutProc.log";

            File.Delete(fileName);

            IEnumerable <string> entries = null;

            using (var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\FlatFile\\FlatFileFormatterOutProc.xml"))
                using (var eventCollectorService = new TraceEventService(svcConfiguration))
                {
                    eventCollectorService.Start();

                    try
                    {
                        MockEventSourceOutProc.Logger.LogSomeMessage("some message");
                        MockEventSourceOutProc.Logger.LogSomeMessage("some message2");
                        entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 2, "=======");
                    }
                    finally
                    {
                        eventCollectorService.Stop();
                    }
                }

            Assert.AreEqual(2, entries.Count());
            StringAssert.Contains(entries.First(), "some message");
            StringAssert.Contains(entries.Last(), "some message2");
        }
        protected override void Given()
        {
            TraceEventManifestsCache.Clear();

            this.formatter        = new MockFormatter();
            this.inMemoryListener = new InMemoryEventListener(this.formatter);
            var sink = new Lazy <IObserver <EventEntry> >(() => this.inMemoryListener);

            this.sourceSettings = this.sourceSettings ?? new SemanticLogging.Etw.Configuration.EventSourceSettings(EventSource.GetName(typeof(MyCompanyEventSource)));
            this.eventSources   = new List <SemanticLogging.Etw.Configuration.EventSourceSettings> {
                this.sourceSettings
            };
            this.sinkSettings = new List <SinkSettings> {
                new SinkSettings("test", sink, this.eventSources)
            };
            this.configuration = new TraceEventServiceConfiguration(sinkSettings, this.serviceSettings);

            try
            {
                this.sut = new TraceEventService(configuration);
            }
            catch (UnauthorizedAccessException uae)
            {
                Assert.Inconclusive(uae.Message);
            }

            // Clean up any previous unclosed session to avoid collisions
            this.RemoveAnyExistingSession();
        }
        public void ReconfigListenerAdded()
        {
            var fileName = "flatFileReconfig.log";

            File.Delete(fileName);
            var logger     = MockEventSourceOutProc.Logger;
            var configFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Configurations\\Reconfiguration\\temp\\configFile.xml";

            UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\NoListener.xml", configFile);

            IEnumerable <string> entries = null;

            using (TraceEventServiceConfiguration svcConfiguration = TraceEventServiceConfiguration.Load(configFile, true))
                using (TraceEventService collector = new TraceEventService(svcConfiguration))
                {
                    collector.Start();
                    try
                    {
                        TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig", 1);
                        UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListener.xml", configFile);
                        TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-flatFileListener", 1);

                        MockEventSourceOutProc.Logger.LogSomeMessage("some message to new added flat file");
                        entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 1, "======");
                    }
                    finally
                    {
                        collector.Stop();
                        File.Delete(configFile);
                    }
                }

            Assert.AreEqual(1, entries.Count());
            StringAssert.Contains(entries.First(), "some message to new added flat file");
        }
Example #16
0
        public void WhenUsingExternalConfig()
        {
            this.tableName = "outProcazuretablesusingconfig";
            var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"];

            AzureTableHelper.DeleteTable(connectionString, this.tableName);
            var logger = MockEventSourceOutProc.Logger;

            IEnumerable <WindowsAzureTableEventEntry> events = null;
            var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\AzureTables\\AzureTables.xml");

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                try
                {
                    collector.Start();
                    for (int i = 0; i < 10; i++)
                    {
                        logger.Critical("Critical message");
                    }

                    events = AzureTableHelper.PollForEvents(connectionString, this.tableName, 10);
                }
                finally
                {
                    collector.Stop();
                }
            }

            Assert.AreEqual <int>(10, events.Count());
            Assert.AreEqual <int>(2, events.First().EventId);
        }
        /// <summary>
        /// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
        /// </summary>
        protected override void OnStop()
        {
            // Short-cut if TraceEventService was not started or is already stopped.
            if (this.service == null)
            {
                return;
            }

            try
            {
                this.service.Dispose();
                this.service = null;
            }
            catch (Exception e)
            {
                // Notify in console error handling
                if (this.consoleMode)
                {
                    throw;
                }

                // Do not rethrow in Service mode so SCM can mark this service as stopped (this will allow to uninstall the service properly)
                this.EventLog.WriteEntry(e.ToString(), EventLogEntryType.Error);
            }
        }
        public void WhenUsingJsonFormatterWithCustomDateTimeFormat()
        {
            string fileName = "FlatFileJsonFormatterDateTimeFormat.log";

            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;

            IEnumerable <TestEventEntryCustomTimeStamp> entries;

            using (var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\WithFormatter\\FlatFileJsonFormatterDateTimeFormat.xml"))
                using (var evtService = new TraceEventService(svcConfiguration))
                {
                    evtService.Start();
                    try
                    {
                        logger.LogSomeMessage("logging using custom DateTime format");
                        entries = FlatFileHelper.PollUntilJsonEventsAreWritten <TestEventEntryCustomTimeStamp>(fileName, 1);
                    }
                    finally
                    {
                        evtService.Stop();
                    }
                }

            var    dt = DateTime.UtcNow;
            string expectedTimestamp = dt.Day.ToString() + dt.Month.ToString() + dt.Year.ToString();

            Assert.AreEqual(expectedTimestamp, entries.First().Timestamp);
        }
        public void TwoCollectorsSameEventSource()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;

            DatabaseHelper.CleanLoggingDB(validConnectionString);
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter  formatter = new EventTextFormatter();
            EventSourceSettings settings  = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);

            var subject = new EventEntrySubject();

            subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(1), 1);
            SinkSettings sinkSettings = new SinkSettings("dbSink", subject, new List <EventSourceSettings>()
            {
                { settings }
            });

            var subject2 = new EventEntrySubject();

            subject2.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(1), 1);
            SinkSettings sinkSettings2 = new SinkSettings("dbSink2", subject2, new List <EventSourceSettings>()
            {
                { settings }
            });

            System.Data.DataTable eventsDataTable = null;
            List <SinkSettings>   sinks           = new List <SinkSettings>()
            {
                sinkSettings, sinkSettings2
            };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
                using (TraceEventService collector2 = new TraceEventService(svcConfiguration))
                {
                    collector.Start();
                    collector2.Start();
                    try
                    {
                        for (int n = 0; n < 10; n++)
                        {
                            logger.LogSomeMessage("some message" + n.ToString());
                        }

                        eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 20);
                    }
                    finally
                    {
                        collector.Stop();
                        collector2.Stop();
                    }
                }

            Assert.AreEqual(20, eventsDataTable.Rows.Count);
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message");
        }
        public void ReconfigTwoSourcesListenerAddedThenRemoved()
        {
            var fileName = "flatFileReconfig.log";

            File.Delete(fileName);
            var logger     = MockEventSourceOutProc.Logger;
            var configFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Configurations\\Reconfiguration\\temp\\configFile.xml";

            UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListenerTwoSources.xml", configFile);

            TraceEventServiceConfiguration svcConfiguration = TraceEventServiceConfiguration.Load(configFile, true);

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                collector.Start();
                try
                {
                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-flatFileListener", 1);

                    MockEventSourceOutProc.Logger.LogSomeMessage("some message to new added flat file");
                    var entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 1, "======");
                    Assert.AreEqual(1, entries.Count());
                    StringAssert.Contains(entries.First(), "some message to new added flat file");

                    UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListenerTwoSourcesSameListener.xml", configFile);
                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-flatFileListener", 1);

                    MockEventSourceOutProc.Logger.LogSomeMessage("some message to new added flat file2");
                    MockEventSourceOutProc2.Logger.LogSomeMessage("some message to new added flat file3");
                    var entries2 = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 3, "======");
                    Assert.AreEqual(3, entries2.Count());
                    StringAssert.Contains(entries2.First(), "some message to new added flat file");
                    StringAssert.Contains(entries2.ElementAt(1), "some message to new added flat file2");
                    StringAssert.Contains(entries2.Last(), "some message to new added flat file3");

                    UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListenerTwoSources.xml", configFile);
                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-flatFileListener", 1);

                    MockEventSourceOutProc.Logger.LogSomeMessage("last message to new added flat file");
                    var entries3 = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 4, "======");
                    Assert.AreEqual(4, entries3.Count());
                    StringAssert.Contains(entries3.Last(), "last message to new added flat file");

                    UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListenerTwoSourcesNoListener.xml", configFile);
                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-flatFileListener", 0);
                }
                finally
                {
                    collector.Stop();
                    File.Delete(configFile);
                }
            }
        }
        public void TestingDynamicManifestUpdate()
        {
            var fileName = "twoflatFileListeners.log";

            File.Delete(fileName);
            var fileName2 = "twoflatFileListeners2.log";

            File.Delete(fileName2);

            var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\Reconfiguration\\TwoFlatFileListeners.xml");

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                collector.Start();
                try
                {
                    var newDomain = AppDomain.CreateDomain("TestintDynamicManifest", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);
                    try
                    {
                        var instance = (IsolatedExecutingClass)newDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(IsolatedExecutingClass).FullName);
                        instance.TestWithSource1();
                    }
                    finally
                    {
                        AppDomain.Unload(newDomain);
                    }

                    newDomain = AppDomain.CreateDomain("TestintDynamicManifest", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation);
                    try
                    {
                        var instance = (IsolatedExecutingClass)newDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(IsolatedExecutingClass).FullName);
                        instance.TestWithSource2();
                    }
                    finally
                    {
                        AppDomain.Unload(newDomain);
                    }

                    var entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 2, "======");
                    Assert.AreEqual(2, entries.Count());
                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName2, 2, "======");
                    Assert.AreEqual(2, entries.Count());
                }
                finally
                {
                    collector.Stop();
                }
            }
        }
Example #22
0
 public static void WithConfiguration(TraceEventServiceConfiguration svcConfiguration, Action scenario)
 {
     using (TraceEventService collector = new TraceEventService(svcConfiguration))
     {
         collector.Start();
         try
         {
             scenario();
         }
         finally
         {
             collector.Stop();
         }
     }
 }
        public void WhenSomeSessionNamesAreInvalid()
        {
            File.Delete("sessionLength.log");
            File.Delete("sessionLength2.log");

            var cfg = TraceEventServiceConfiguration.Load("Configurations\\SessionNameLongInOneSink.xml");

            using (TraceEventService svc = new TraceEventService(cfg))
            {
                svc.Start();

                Assert.IsTrue(TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfigService", 3));
                Assert.IsTrue(File.Exists("sessionLength.log"));
                Assert.IsTrue(File.Exists("sessionLength2.log"));
            }
        }
        public void WhenConfigValidAndComplete()
        {
            var logger = MockEventSourceOutProc.Logger;
            MockConsoleOutput mockConsole = new MockConsoleOutput();

            var svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\Console\\Console.xml");

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                collector.Start();

                for (int n = 0; n < 10; n++)
                {
                    logger.LogSomeMessage("some message to console " + n.ToString() + ".");
                }
            }
        }
        public void FlatFileSomeFilteredSomeNot()
        {
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);
            var fileName = "FlatFileAllFiltered.log";

            File.Delete(fileName);

            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.Error);
            var subject = new EventEntrySubject();

            subject.LogToFlatFile(fileName, formatter);

            SinkSettings sinkSettings = new SinkSettings("flatFileSink", subject, new List <EventSourceSettings>()
            {
                { settings }
            });
            List <SinkSettings> sinks = new List <SinkSettings>()
            {
                { sinkSettings }
            };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            IEnumerable <string>           entries          = null;

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                collector.Start();
                try
                {
                    for (int n = 0; n < 200; n++)
                    {
                        logger.LogSomeMessage("some message " + n.ToString());
                        logger.Critical("some error " + n.ToString());
                    }
                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 200, EventTextFormatter.DashSeparator);
                }
                finally
                {
                    collector.Stop();
                }
            }

            Assert.AreEqual(200, entries.Count());
            StringAssert.Contains(entries.First(), "some error 0");
            StringAssert.Contains(entries.Last(), "some error 199");
        }
        public void OutProcFiltering()
        {
            var fileName = "levelFiltering.log";

            File.Delete(fileName);
            var fileName2 = "levelFiltering2.log";

            File.Delete(fileName2);
            var fileName3 = "levelFiltering3.log";

            File.Delete(fileName3);
            var logger = MockEventSourceOutProcFiltering.Logger;

            IEnumerable <string> entries  = null;
            IEnumerable <string> entries2 = null;
            IEnumerable <string> entries3 = null;

            using (TraceEventServiceConfiguration svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\LevelFiltering\\LevelFiltering.xml"))
                using (TraceEventService collector = new TraceEventService(svcConfiguration))
                {
                    collector.Start();
                    try
                    {
                        logger.Informational("some informational message");
                        logger.Verbose("some verbose");
                        logger.Critical("some critical");
                        logger.Error("some error");
                        logger.Warning("some warning");

                        entries  = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 1, "======");
                        entries2 = FlatFileHelper.PollUntilTextEventsAreWritten(fileName2, 2, "======");
                        entries3 = FlatFileHelper.PollUntilTextEventsAreWritten(fileName3, 3, "======");
                    }
                    finally
                    {
                        collector.Stop();
                    }
                }

            StringAssert.Contains(entries.First().ToString(), "some critical");
            StringAssert.Contains(entries2.First().ToString(), "some critical");
            StringAssert.Contains(entries2.Last().ToString(), "some error");
            Assert.AreEqual(1, entries3.Where(e => e.Contains("some error")).Count());
            Assert.AreEqual(1, entries3.Where(e => e.Contains("some critical")).Count());
            Assert.AreEqual(1, entries3.Where(e => e.Contains("some warning")).Count());
        }
Example #27
0
        public void WhenUsingCustomFormatterProgramatically()
        {
            string fileName = "FlatFileCustomFormatterProgrammatic.log";

            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;
            CustomFormatterWithWait formatter = new CustomFormatterWithWait();

            formatter.Detailed       = System.Diagnostics.Tracing.EventLevel.LogAlways;
            formatter.Header         = "---------------";
            formatter.DateTimeFormat = "d";

            IEnumerable <string> entries  = null;
            EventSourceSettings  settings = new EventSourceSettings("MockEventSourceOutProc", null, System.Diagnostics.Tracing.EventLevel.Critical);
            var subject = new EventEntrySubject();

            subject.LogToFlatFile(fileName, formatter);
            SinkSettings sinkSettings = new SinkSettings("flatFileSink", subject, new List <EventSourceSettings>()
            {
                { settings }
            });
            List <SinkSettings> sinks = new List <SinkSettings>()
            {
                { sinkSettings }
            };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                try
                {
                    collector.Start();
                    logger.Critical("some message using formatter");

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 1, "---------------");
                }
                finally
                {
                    collector.Stop();
                }
            }

            StringAssert.Contains(entries.First(), "Mock SourceId");
            StringAssert.Contains(entries.First(), "Mock EventId");
            StringAssert.Contains(entries.First(), "Payload : [message : some message using formatter]");
        }
Example #28
0
        public void WhenConfiguringProgrammatically()
        {
            this.tableName = "testoutofprocazuretables";
            var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"];

            AzureTableHelper.DeleteTable(connectionString, this.tableName);
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter();

            IEnumerable <WindowsAzureTableEventEntry> events = null;
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            var subject = new EventEntrySubject();

            subject.LogToWindowsAzureTable("AzureInstance", connectionString, tableName, TimeSpan.FromSeconds(1));
            SinkSettings sinkSettings = new SinkSettings("azureSink", subject, new List <EventSourceSettings>()
            {
                { settings }
            });
            List <SinkSettings> sinks = new List <SinkSettings>()
            {
                { sinkSettings }
            };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                try
                {
                    collector.Start();
                    for (int i = 0; i < 10; i++)
                    {
                        logger.Critical("Critical message");
                    }

                    events = AzureTableHelper.PollForEvents(connectionString, this.tableName, 10);
                }
                finally
                {
                    collector.Stop();
                }
            }

            Assert.AreEqual <int>(10, events.Count());
            Assert.AreEqual <int>(2, events.First().EventId);
        }
Example #29
0
        public void WhenUsingRollingSinkProgramatic()
        {
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter(EventTextFormatter.DashSeparator);
            var fileName = "newRollingFlatfileSerial.log";

            File.Delete(fileName);
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            var subject = new EventEntrySubject();

            subject.LogToRollingFlatFile(fileName, 100, "d", RollFileExistsBehavior.Overwrite, RollInterval.Day, formatter);

            SinkSettings sinkSettings = new SinkSettings("rollingFlatFileSink", subject, new List <EventSourceSettings>()
            {
                { settings }
            });
            List <SinkSettings> sinks = new List <SinkSettings>()
            {
                { sinkSettings }
            };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            IEnumerable <string>           entries          = null;

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                collector.Start();
                try
                {
                    for (int n = 0; n < 200; n++)
                    {
                        logger.LogSomeMessage("some message" + n.ToString());
                    }

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 200, EventTextFormatter.DashSeparator);
                }
                finally
                {
                    collector.Stop();
                }
            }

            Assert.AreEqual(200, entries.Count());
            StringAssert.Contains(entries.First(), "some message0");
            StringAssert.Contains(entries.Last(), "some message199");
        }
        public void ReconfigListenerAddedWithErrorShouldNotRecycle()
        {
            var fileName = "flatfileListenerOk.log";

            File.Delete(fileName);
            var logger     = MockEventSourceOutProc.Logger;
            var configFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Configurations\\Reconfiguration\\temp\\configFile.xml";

            UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\NoListener.xml", configFile);

            TraceEventServiceConfiguration svcConfiguration = TraceEventServiceConfiguration.Load(configFile, true);

            using (var collector = new TraceEventService(svcConfiguration))
                using (var collectErrorsListener = new InMemoryEventListener(true))
                {
                    collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways, Keywords.All);
                    collector.Start();
                    try
                    {
                        TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig", 1);
                        UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListenerError.xml", configFile);
                        TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-flatFileListener", 0);
                        TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-2flatFileListener", 1);

                        MockEventSourceOutProc.Logger.LogSomeMessage("Some informational from a new listener.");
                        var entries2 = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 1, "======");
                        Assert.AreEqual(1, entries2.Count());
                        StringAssert.Contains(entries2.First(), "Some informational from a new listener.");

                        collectErrorsListener.WaitEvents.Wait(TimeSpan.FromSeconds(3));
                        StringAssert.Contains(collectErrorsListener.ToString(), "One or more errors occurred when loading the TraceEventService configuration file.");
                        StringAssert.Contains(collectErrorsListener.ToString(), "The given path's format is not supported.");
                        StringAssert.Contains(collectErrorsListener.ToString(), "The configuration was partially successfully loaded. Check logs for further error details.");
                    }
                    finally
                    {
                        collector.Stop();
                        File.Delete(configFile);
                        collectErrorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                    }
                }
        }
        public void ReconfigChangeSessionRecycles()
        {
            var fileName = "flatFileReconfig.log";

            File.Delete(fileName);
            var logger     = MockEventSourceOutProc.Logger;
            var configFile = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Configurations\\Reconfiguration\\temp\\configFile.xml";

            UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListener.xml", configFile);

            TraceEventServiceConfiguration svcConfiguration = TraceEventServiceConfiguration.Load(configFile, true);

            using (TraceEventService collector = new TraceEventService(svcConfiguration))
            {
                try
                {
                    collector.Start();

                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-flatFileListener", 1);
                    TraceSessionHelper.WaitAndAssertCountOfSessions("ServiceReconfig-dummyListener", 1);

                    UpdateServiceConfigurationFile("Configurations\\Reconfiguration\\FlatFileListenerDiffSession.xml", configFile);
                }
                finally
                {
                    collector.Stop();
                    File.Delete(configFile);
                }
            }

            //using (TraceEventServiceConfiguration svcConfiguration = TraceEventServiceConfiguration.Load("Configurations\\Reconfiguration\\FlatFileListenerDiffSession.xml"))
            //using (TraceEventService collector = new TraceEventService(svcConfiguration))
            //{
            //    collector.Start();

            //    Assert.AreEqual(0, TraceSessionHelper.CountSessionStartingWith("ServiceReconfig-flatFileListener"));
            //    Assert.AreEqual(0, TraceSessionHelper.CountSessionStartingWith("ServiceReconfig-dummyListener"));

            //    Assert.AreEqual(1, TraceSessionHelper.CountSessionStartingWith("ServiceReconfig2-flatFileListener"));
            //    Assert.AreEqual(1, TraceSessionHelper.CountSessionStartingWith("ServiceReconfig2-dummyListener"));
            //}
        }
        /// <summary>
        /// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). Specifies actions to take when a service stops running.
        /// </summary>
        protected override void OnStop()
        {
            // Short-cut if TraceEventService was not started or is already stopped.
            if (this.service == null)
            {
                return;
            }

            try
            {
                this.service.Dispose();
                this.service = null;
                this.DisableNonTransientErrorsHandling();
                if (!this.consoleMode)
                {
                    this.EventLog.WriteEntry(Resources.ServiceStoppedMessage);
                }
            }
            catch (Exception e)
            {
                // Notify in console error handling
                if (this.consoleMode)
                {
                    throw;
                }

                // Do not rethrow in Service mode so SCM can mark this service as stopped (this will allow to uninstall the service properly)
                this.EventLog.WriteEntry(e.ToString(), EventLogEntryType.Error);
            }
        }