public void WhenEnumsInPayload()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;
            DatabaseHelper.CleanLoggingDB(validConnectionString);
            var logger = MockEventSourceOutProcEnum.Logger;
            EventTextFormatter formatter = new EventTextFormatter();

            System.Data.DataTable eventsDataTable = null;
            var subject = new EventEntrySubject();
            subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", bufferingCount: 1);
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProcEnum", null, EventLevel.LogAlways);
            SinkSettings sinkSettings = new SinkSettings("sqlDBsink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    logger.SendEnumsEvent16(MockEventSourceOutProcEnum.MyColor.Blue, MockEventSourceOutProcEnum.MyFlags.Flag3);

                    eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 1);
                });

            Assert.AreEqual(1, eventsDataTable.Rows.Count);
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), @"""a"": 1");
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), @"""b"": 4");
        }
        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);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    for (int i = 0; i < 10; i++)
                    {
                        logger.Critical("Critical message");
                    }

                    events = AzureTableHelper.PollForEvents(connectionString, this.tableName, 10);
                });

            Assert.AreEqual<int>(10, events.Count());
            Assert.AreEqual<int>(2, events.First().EventId);
        }
        public void WhenUsingSinkProgrammatically()
        {
            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);

            System.Data.DataTable eventsDataTable = null;
            SinkSettings sinkSettings = new SinkSettings("sqlDBsink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    for (int n = 0; n < 10; n++)
                    {
                        logger.LogSomeMessage("some message" + n.ToString());
                    }

                    eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 10);
                });

            Assert.AreEqual(10, eventsDataTable.Rows.Count);
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message");
        }
        public void WhenUsingRollingSinkProgrammatic()
        {
            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;
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    for (int n = 0; n < 200; n++)
                    {
                        logger.LogSomeMessage("some message" + n.ToString());
                    }

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 200, EventTextFormatter.DashSeparator);
                });

            Assert.AreEqual(200, entries.Count());
            StringAssert.Contains(entries.First(), "some message0");
            StringAssert.Contains(entries.Last(), "some message199");
        }
        public void WhenConcurrentEventsRaised()
        {
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter();
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            InMemorySink sink = new InMemorySink(formatter);

            SinkSettings sinkSettings = new SinkSettings("memorySink", sink, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    sink.WaitSignalCondition = () => sink.EventWrittenCount == 100;
                    for (int n = 0; n < 100; n++)
                    {
                        logger.LogSomeMessage("some message" + n.ToString());
                    }

                    sink.WaitOnAsyncEvents.WaitOne(TimeSpan.FromSeconds(10));
                });

            StringAssert.Contains(sink.ToString(), "some message99");
        }
        public void when_creating_instance_with_null_values()
        {
            var sut = new TraceEventServiceConfiguration();

            Assert.AreEqual(0, sut.SinkSettings.Count);
            Assert.AreEqual(new TraceEventServiceSettings().SessionNamePrefix, sut.Settings.SessionNamePrefix);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TraceEventService" /> class.
        /// Note that the instance of <see cref="TraceEventServiceConfiguration"/> passed will not be disposed by this class.
        /// </summary>
        /// <param name="configuration">The <see cref="TraceEventServiceConfiguration"/> configuration instance.</param>
        /// <exception cref="ArgumentNullException">Configuration.EventSources; Configuration.Settings.</exception>
        /// <exception cref="ArgumentException">No Event Sources specified; Duplicate provider ID.</exception>
        /// <exception cref="UnauthorizedAccessException">Insufficient privileges.</exception>
        /// <exception cref="ConfigurationException">Configuration validation errors.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">MaxDegreeOfParallelism, BoundedCapacity, EventListenerMaxExecutionTimeInMilliseconds.</exception>
        public TraceEventService(TraceEventServiceConfiguration configuration)
        {
            Guard.ArgumentNotNull(configuration, "configuration");
            ThrowOnUnAuthorizedAccess();

            this.configuration = configuration;
            this.Status = ServiceStatus.NotStarted;
            this.configuration.SinkSettings.CollectionChanged += this.OnSinkSettingsChanged;
        }
 public static void WithConfiguration(TraceEventServiceConfiguration svcConfiguration, Action scenario)
 {
     using (TraceEventService collector = new TraceEventService(svcConfiguration))
     {
         collector.Start();
         try
         {
             scenario();
         }
         finally
         {
             collector.Stop();
         }
     }
 }
        public void WhenUsingTwoCollectorsForSameEventSource()
        {
            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");
        }
        protected override void Given()
        {
            this.formatter = new MockFormatter();
            this.inMemoryListener = new InMemoryEventListener(this.formatter);
            var sink = new Lazy<IObserver<EventEntry>>(() => this.inMemoryListener);
            this.sourceSettings = this.sourceSettings ?? new EventSourceSettings(EventSource.GetName(typeof(MyCompanyEventSource)));
            this.eventSources = new List<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();
        }
            protected override void Given()
            {
                base.Given();
                inMemoryListener = new InMemoryEventListener(new MockFormatter { BeforeWriteEventAction = f => { throw new Exception("unhandled_exception_test"); } });
                var sink = new Lazy<IObserver<EventEntry>>(() => inMemoryListener);
                sourceSettings = new EventSourceSettings(EventSource.GetName(typeof(MyCompanyEventSource)));
                eventSources = new List<EventSourceSettings> { sourceSettings };
                sinkSettings = new List<SinkSettings> { new SinkSettings("test", sink, eventSources) };
                configuration = new TraceEventServiceConfiguration(sinkSettings);
                this.sut = new TraceEventService(configuration);

                slabListener = new InMemoryEventListener();
                slabListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.Error, SemanticLoggingEventSource.Keywords.TraceEvent);
                this.sut.Start();
            }
        public void WhenCustomFormatterThrowsAnExceptionAndUsedProgramatically()
        {
            string fileName = "FlatFileOutProcCustomFormatterHandleException.log";
            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;
            MockFormatter formatter = new MockFormatter(true); //this formatter throws

            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.Informational);
            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);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    using (var collectErrorsListener = new InMemoryEventListener())
                    {
                        try
                        {
                            collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways, Keywords.All);

                            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
                        {
                            collectErrorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                        }
                    }
                });
        }
        public void WhenUsingTwoCollectorsForSameEventSourceWithDifferentSinkTypes()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;
            DatabaseHelper.CleanLoggingDB(validConnectionString);
            string fileName = "TwoCollectorsSameEventSourceDifferentSinkTypes.log";
            File.Delete(fileName);
            string header = "===========";
            var logger = MockEventSourceOutProc.Logger;
            EventTextFormatter formatter = new EventTextFormatter(header);
            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.LogToFlatFile(fileName, formatter);
            SinkSettings sinkSettings2 = new SinkSettings("ffSink", subject2, new List<EventSourceSettings>() { { settings } });

            System.Data.DataTable eventsDataTable = null;
            List<SinkSettings> sinks = new List<SinkSettings>() { sinkSettings, sinkSettings2 };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            IEnumerable<string> entries = null;
            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, 10);

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 10, header);
                }
                finally
                {
                    collector.Stop();
                    collector2.Stop();
                }
            }

            Assert.AreEqual(10, eventsDataTable.Rows.Count);
            StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message");

            Assert.AreEqual(10, entries.Count());
            StringAssert.Contains(entries.First(), "some message0");
            StringAssert.Contains(entries.Last(), "some message9");
        }
        private void InitializeTest(string serviceConfigFile, string fileName, out TraceEventServiceConfiguration svcConfiguration, out Guid activityId, out Guid oldActivityId, bool shouldMonitorChanges = false)
        {
            File.Delete(fileName);

            svcConfiguration = TraceEventServiceConfiguration.Load(serviceConfigFile, shouldMonitorChanges);

            activityId = new Guid("368D6088-9F44-4735-B37F-3E76242583A1");
            oldActivityId = EventSource.CurrentThreadActivityId;
            EventSource.SetCurrentThreadActivityId(activityId);
        }
        public void WhenInfoAndMoreVerboseLevelsAreFiltered()
        {
            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;
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    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);
                });

            Assert.AreEqual(200, entries.Count());
            StringAssert.Contains(entries.First(), "some error 0");
            StringAssert.Contains(entries.Last(), "some error 199");
        }
        public void WhenThreadId()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;
            DatabaseHelper.CleanLoggingDB(validConnectionString);
            var logger = MockEventSourceOutProcEnum.Logger;
            EventTextFormatter formatter = new EventTextFormatter();

            System.Data.DataTable eventsDataTable = null;
            var subject = new EventEntrySubject();
            subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", bufferingCount: 1);
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProcEnum", null, EventLevel.LogAlways);
            SinkSettings sinkSettings = new SinkSettings("sqlDBsink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    logger.SaveExpenseStarted(Guid.NewGuid());

                    eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 1);
                });

            Assert.AreEqual(1, eventsDataTable.Rows.Count);
            Assert.AreEqual(ThreadHelper.GetCurrentUnManagedThreadId(), Convert.ToInt32(eventsDataTable.Rows[0]["ThreadId"]));
        }
Exemple #17
0
        private void ShowConfiguration(TraceEventServiceConfiguration configuration, string file)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendFormat(Resources.LoadedConfigurationMessage, file);
            sb.AppendLine();
            sb.AppendLine();

            if (configuration.SinkSettings.Count > 0)
            {
                sb.AppendFormat(Resources.EventSessionMessage, configuration.Settings.SessionNamePrefix);
                sb.AppendLine();

                foreach (var sink in configuration.SinkSettings)
                {
                    sb.AppendLine();
                    sb.AppendFormat(Resources.SinkNameMessage, sink.Name);
                    sb.AppendLine();
                    sb.AppendLine(Resources.EventSourceListMessage);

                    foreach (var eventSource in sink.EventSources)
                    {
                        sb.AppendFormat(Resources.EventSourceNameMessage, eventSource.EventSourceId);
                        sb.AppendLine();
                        sb.AppendFormat(Resources.EventSourceDescriptionMessage, eventSource.Name, eventSource.Level, eventSource.MatchAnyKeyword);
                        sb.AppendLine();
                    }
                }
            }
            else
            {
                sb.AppendLine(Resources.UpdateConfigFileMessage);
            }

            if (this.consoleMode)
            {
                Console.WriteLine(sb.ToString());
            }
            else
            {
                this.EventLog.WriteEntry(sb.ToString(), EventLogEntryType.Information);
            }
        }
        public void WhenUsingCustomFormatterProgramatically()
        {
            string fileName = "FlatFileCustomFormatterProgrammatic.log";
            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;
            CustomFormatterWithWait formatter = new CustomFormatterWithWait();
            formatter.Detailed = EventLevel.LogAlways;
            formatter.Header = "---------------";
            formatter.DateTimeFormat = "d";

            IEnumerable<string> entries = null;
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, 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);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    logger.Critical("some message using formatter");

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 1, "---------------");
                });

            StringAssert.Contains(entries.First(), "Mock SourceId");
            StringAssert.Contains(entries.First(), "Mock EventId");
            StringAssert.Contains(entries.First(), "Payload : [message : some message using formatter]");
        }
            protected override void Given()
            {
                RemoveAnyExistingSession(SessionName2);
                base.Given();

                inMemoryListener2 = new InMemoryEventListener(formatter);
                var sink = new Lazy<IObserver<EventEntry>>(() => inMemoryListener2);
                var localSourceSettings = new EventSourceSettings(EventSource.GetName(typeof(MyCompanyEventSource)), level: EventLevel.Informational, matchAnyKeyword: MyCompanyEventSource.Keywords.Page);
                var localEventSources = new List<EventSourceSettings> { localSourceSettings };
                var localSinkSettings = new List<SinkSettings> { new SinkSettings("test", sink, localEventSources) };
                var localConfiguration = new TraceEventServiceConfiguration(localSinkSettings, new TraceEventServiceSettings { SessionNamePrefix = SessionName2 });
                this.sut2 = new TraceEventService(localConfiguration);
            }
 protected override void Given()
 {
     base.Given();
     var sink = new Lazy<IObserver<EventEntry>>(() => inMemoryListener);
     sourceSettings = new EventSourceSettings(EventSource.GetName(typeof(MyCompanyEventSource)), level: EventLevel.Warning);
     eventSources = new List<EventSourceSettings> { sourceSettings };
     sinkSettings = new List<SinkSettings> { new SinkSettings("test", sink, eventSources) };
     configuration = new TraceEventServiceConfiguration(sinkSettings);
     this.sut = new TraceEventService(configuration);
     this.sut.Start();
 }
 protected override void Given()
 {
     base.Given();
     inMemoryListener.WaitSignalCondition = () => inMemoryListener.EventWrittenCount == 2;
     var sink = new Lazy<IObserver<EventEntry>>(() => inMemoryListener);
     var localSourceSettings = new EventSourceSettings(EventSource.GetName(typeof(TestEventSource)));
     this.eventSources.Add(localSourceSettings);
     sinkSettings = new List<SinkSettings> { new SinkSettings("test", sink, eventSources) };
     configuration = new TraceEventServiceConfiguration(sinkSettings);
     this.sut = new TraceEventService(configuration);
     this.sut.Start();
 }
        /// <summary>
        /// Loads the specified file name.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="monitorChanges">If set to <c>true</c> monitor file changes.</param>
        /// <param name="createSinks">If set to <c>true</c> [create sinks].</param>
        /// <returns>
        /// The loaded <see cref="TraceEventServiceConfiguration" /> instance.
        /// </returns>
        /// <exception cref="ConfigurationException">All the validation errors detected when opening the file.</exception>
        public static TraceEventServiceConfiguration Load(string fileName, bool monitorChanges = false, bool createSinks = true)
        {
            var configReader = new ConfigurationReader(fileName);
            ConfigurationElement configElement = configReader.Read();

            var serviceSettings =
                new TraceEventServiceSettings
                {
                    SessionNamePrefix = configElement.TraceEventService.SessionNamePrefix
                };

            var sinkSettings = new List<SinkSettings>();

            foreach (var element in configElement.SinkConfigurationElements)
            {
                var eventSources =
                    element.EventSources.Select(
                        e =>
                            new EventSourceSettings(
                                e.Name,
                                e.EventId,
                                e.Level,
                                e.MatchAnyKeyword,
                                e.Arguments.Select(a => new KeyValuePair<string, string>(a.Key, a.Value)),
                                e.ProcessNameFilters.Select(p => p.Name)));
                var sink = createSinks ?
                    new SinkSettings(element.Name, element.SinkPromise.Value, eventSources) :
                    new SinkSettings(element.Name, element.SinkPromise, eventSources);
                sink.SinkConfiguration = element.SinkConfiguration;
                sinkSettings.Add(sink);
            }

            var configuration = new TraceEventServiceConfiguration(sinkSettings, serviceSettings);

            if (monitorChanges)
            {
                configuration.StartConfigurationWatcher(configReader.File);
            }

            return configuration;
        }
        private void ShowConfiguration(TraceEventServiceConfiguration configuration, string file)
        {
            var sb = new StringBuilder();

            sb.AppendFormat(Resources.LoadedConfigurationMessage, file);
            sb.AppendLine();
            sb.AppendLine();

            if (configuration.SinkSettings.Count > 0)
            {
                sb.AppendFormat(Resources.EventSessionMessage, configuration.Settings.SessionNamePrefix);
                sb.AppendLine();

                foreach (var sink in configuration.SinkSettings)
                {
                    sb.AppendLine();
                    sb.AppendFormat(Resources.SinkNameMessage, sink.Name);
                    sb.AppendLine();
                    sb.AppendLine(Resources.EventSourceListMessage);

                    foreach (var eventSource in sink.EventSources)
                    {
                        sb.AppendFormat(Resources.EventSourceNameMessage, eventSource.EventSourceId);
                        sb.AppendLine();
                        sb.AppendFormat(Resources.EventSourceDescriptionMessage, eventSource.Name, eventSource.Level, eventSource.MatchAnyKeyword);
                        sb.AppendLine();

                        if (eventSource.Arguments.Any())
                        {
                            sb.AppendFormat(
                                Resources.EventSourceArgumentsMessage,
                                string.Join(
                                    ", ",
                                    eventSource.Arguments.Select(kvp => string.Format("\"{0}\" = \"{1}\"", kvp.Key, kvp.Value))));
                            sb.AppendLine();
                        }

                        if (eventSource.ProcessNamesToFilter.Any())
                        {
                            sb.AppendFormat(Resources.EventSourceProcessNamesMessage, string.Join(", ", eventSource.ProcessNamesToFilter));
                            sb.AppendLine();
                        }
                    }
                }
            }
            else
            {
                sb.AppendLine(Resources.UpdateConfigFileMessage);
            }

            if (this.consoleMode)
            {
                Console.WriteLine(sb.ToString());
            }
            else
            {
                this.EventLog.WriteEntry(sb.ToString(), EventLogEntryType.Information);
            }
        }
        public void WhenUsingCustomSinkProgrammatically()
        {
            string fileName = "ProvidedCustomSink.log";
            File.Delete(fileName);
            var logger = MockEventSourceOutProc.Logger;
            var formatter = new EventTextFormatter();

            IEnumerable<string> entries = null;
            var subject = new EventEntrySubject();
            subject.LogToMockFlatFile(fileName, "==-==");
            EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways);
            SinkSettings sinkSettings = new SinkSettings("MockFlatFileSink", subject, new List<EventSourceSettings>() { { settings } });
            List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } };
            TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks);
            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
                {
                    logger.LogSomeMessage("some message");
                    logger.LogSomeMessage("some message2");
                    logger.LogSomeMessage("some message3");

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 3, "==-==");
                });

            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]")));
        }