public static void With1Listener(IEnumerable<EventSource> loggers, Action<ObservableEventListener, InMemoryEventListener> scenario)
        {
            using (var errorsListener = new InMemoryEventListener())
            using (var listener = new ObservableEventListener())
            {
                try
                {
                    errorsListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.Verbose, Keywords.All);

                    scenario(listener, errorsListener);
                }
                finally
                {
                    foreach (var logger in loggers)
                    {
                        try
                        { listener.DisableEvents(logger); }
                        catch
                        { }
                    }

                    errorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                }
            }
        }
        static void Main(string[] args)
        {
            // optimizing IOCP performance
            int minWorkerThreads;
            int minCompletionPortThreads;

            ThreadPool.GetMinThreads(out minWorkerThreads, out minCompletionPortThreads);
            ThreadPool.SetMinThreads(minWorkerThreads, Math.Max(16, minCompletionPortThreads));

            int threadCount = Environment.ProcessorCount;

            if (args.Length > 0)
            {
                threadCount = int.Parse(args[0]);
            }

            var eventListener = new ObservableEventListener();

            eventListener.LogToConsole();
            eventListener.EnableEvents(BootstrapperEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(MqttIotHubAdapterEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(ChannelEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(BootstrapEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(ExecutorEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(MqttEventSource.Log, EventLevel.Verbose);

            try
            {
                var cts = new CancellationTokenSource();

                var certificate      = new X509Certificate2("protocol-gateway.contoso.com.pfx", "password");
                var settingsProvider = new AppConfigSettingsProvider();
                BlobSessionStatePersistenceProvider blobSessionStateProvider = BlobSessionStatePersistenceProvider.CreateAsync(
                    settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageConnectionString"),
                    settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageContainerName")).Result;

                TableQos2StatePersistenceProvider tableQos2StateProvider = TableQos2StatePersistenceProvider.CreateAsync(
                    settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageConnectionString"),
                    settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageTableName")).Result;

                var bootstrapper = new Bootstrapper(settingsProvider, blobSessionStateProvider, tableQos2StateProvider);
                Task.Run(() => bootstrapper.RunAsync(certificate, threadCount, cts.Token), cts.Token);

                while (true)
                {
                    string input = Console.ReadLine();
                    if (input != null && input.ToLowerInvariant() == "exit")
                    {
                        break;
                    }
                }

                cts.Cancel();
                bootstrapper.CloseCompletion.Wait(TimeSpan.FromSeconds(20));
            }
            finally
            {
                eventListener.Dispose();
            }
        }
Example #3
0
        public void Start(TflProcess process) {
            if (_started)
                return;

            _started = true;
            Name = process.Name;
            foreach (var log in process.Log) {
                switch (log.Provider) {
                    case "file":
                        log.Folder = log.Folder.Replace('/', '\\');
                        log.File = log.File.Replace('/', '\\');
                        log.Folder = (log.Folder.Equals(Common.DefaultValue) ? "logs" : log.Folder).TrimEnd('\\') + "\\";
                        log.File = (log.File.Equals(Common.DefaultValue) ? "tfl-" + process.Name + ".log" : log.File).TrimStart('\\');

                        var fileListener = new ObservableEventListener();
                        fileListener.EnableEvents(TflEventSource.Log, (EventLevel)Enum.Parse(typeof(EventLevel), log.Level));
                        SinkSubscriptions.Add(fileListener.LogToRollingFlatFile(log.Folder + log.File, 5000, "yyyy-MM-dd", RollFileExistsBehavior.Increment, RollInterval.Day, new LegacyLogFormatter(), 0, log.Async));
                        EventListeners.Add(fileListener);
                        break;
                    case "mail":
                        if (log.Subject.Equals(Common.DefaultValue)) {
                            log.Subject = process.Name + " " + log.Level;
                        }
                        var mailListener = new ObservableEventListener();
                        mailListener.EnableEvents(TflEventSource.Log, EventLevel.Error);
                        SinkSubscriptions.Add(mailListener.LogToEmail(log));
                        EventListeners.Add(mailListener);
                        break;
                }

            }

        }
Example #4
0
        public void WhenUsingCustomFormatter()
        {
            string fileName = "FlatFileInProcCustomFormatter.log";

            File.Delete(fileName);
            string header    = "----------";
            var    logger    = TestEventSourceNonTransient.Logger;
            var    formatter = new CustomFormatterWithWait(header);

            formatter.Detailed = System.Diagnostics.Tracing.EventLevel.LogAlways;

            IEnumerable <string> entries = null;

            using (var listener = new ObservableEventListener())
            {
                try
                {
                    listener.LogToFlatFile(fileName, formatter);
                    listener.EnableEvents(logger, System.Diagnostics.Tracing.EventLevel.LogAlways);

                    logger.EventWithPayload("payload1", 100);

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 1, header);
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            StringAssert.Contains(entries.First(), "Mock SourceId");
            StringAssert.Contains(entries.First(), "Mock EventId");
            StringAssert.Contains(entries.First(), "Payload : [payload1 : payload1] [payload2 : 100]");
        }
Example #5
0
 public void EnablingEmptyEventSourceNameThrows()
 {
     using (var listener = new ObservableEventListener())
     {
         listener.EnableEvents(string.Empty, EventLevel.LogAlways);
     }
 }
        public async Task TestEventSink()
        {
            var listener = new TcpListener(IPAddress.Loopback, 0);

            listener.Start();
            int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;

            var slabListener = new ObservableEventListener();

            slabListener.Subscribe(new TcpEventSink(IPAddress.Loopback, port,
                                                    new ExponentialBackoffTcpReconnectionPolicy(),
                                                    new TestEventFormatter()));
            var source = TestEventSource.GetInstance();

            slabListener.EnableEvents(source, EventLevel.LogAlways, Keywords.All);

            var listenerClient = await listener.AcceptTcpClientAsync();

            source.Message("Boris", "Meep");

            var receiverReader = new StreamReader(listenerClient.GetStream());
            var line           = await receiverReader.ReadLineAsync();

            Assert.Equal(
                "EventId=1 EventName=MessageInfo Level=Error \"FormattedMessage=Meep - Boris\" \"message=Boris\" \"caller=Meep\"",
                line);

            listenerClient.Close();
            listener.Stop();
            slabListener.Dispose();
        }
 private void EnableLoggingListener()
 {
     listener = new ObservableEventListener();
     listener.LogToWindowsAzureTable("CustomEvents", "DefaultEndpointsProtocol=https;AccountName=musiccloudstorage;AccountKey=...");
     //listener.EnableEvents(AuditEvent.Log, EventLevel.LogAlways, Keywords.All);
     listener.EnableEvents(ErrorEvent.Log, EventLevel.LogAlways, Keywords.All);
 }
 public void SetUp()
 {
     AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory);
     this.fileName = Path.ChangeExtension(Guid.NewGuid().ToString("N"), ".log");
     this.eventTextFormatter = new EventTextFormatter(EventTextFormatter.DashSeparator);
     this.listener = new ObservableEventListener();
 }
Example #9
0
        public void WhenEventWithEnumsInPayloadIsRaised()
        {
            this.tableName = "WhenEventWithEnumsInPayloadIsRaised";
            var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"];

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

            using (var listener = new ObservableEventListener())
            {
                try
                {
                    listener.LogToWindowsAzureTable("mytestinstance1", connectionString, this.tableName, bufferingInterval: TimeSpan.Zero);
                    listener.EnableEvents(logger, EventLevel.LogAlways);
                    logger.SendEnumsEvent17(MockEventSourceInProcEnum.MyColor.Green, MockEventSourceInProcEnum.MyFlags.Flag2);
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            var events = AzureTableHelper.PollForEvents(connectionString, this.tableName, 1);

            Assert.AreEqual(1, events.Count());
            Assert.AreEqual((int)EventTask.None, events.ElementAt(0).Task);
            Assert.AreEqual((int)EventOpcode.Resume, events.ElementAt(0).Opcode);
            Assert.AreEqual("{\n  \"a\": 2,\n  \"b\": 2\n}", events.ElementAt(0).Payload.ToString());
        }
Example #10
0
        public void WhenEventWithTaskNameInAttributeIsRaised()
        {
            this.tableName = "WhenEventWithTaskNameInAttributeIsRaised";
            var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"];

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

            using (var listener = new ObservableEventListener())
            {
                try
                {
                    listener.LogToWindowsAzureTable("mytestinstance", connectionString, this.tableName, bufferingInterval: TimeSpan.FromSeconds(10));
                    listener.EnableEvents(logger, EventLevel.LogAlways, Keywords.All);
                    logger.CriticalWithTaskName("Critical with task name");
                    logger.CriticalWithKeywordPage("Critical with no task name");
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            var events = AzureTableHelper.PollForEvents(connectionString, this.tableName, 2);

            Assert.AreEqual(2, events.Count());
            Assert.AreEqual("64513", events.First().Task.ToString());
            Assert.AreEqual("1", events.ElementAt(1).Task.ToString());
        }
Example #11
0
        public void WhenLoggingMultipleMessages()
        {
            this.tableName = "WhenLoggingMultipleMessages";
            var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"];

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

            using (var listener = new ObservableEventListener())
            {
                try
                {
                    listener.LogToWindowsAzureTable("mytestinstance", connectionString, this.tableName);
                    listener.EnableEvents(logger, EventLevel.LogAlways);
                    for (int n = 0; n < 300; n++)
                    {
                        logger.Informational("logging multiple messages " + n.ToString());
                    }
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            var events = AzureTableHelper.PollForEvents(connectionString, this.tableName, 300);

            Assert.AreEqual(300, events.Count());
        }
Example #12
0
        public void WhenNotEnabledWithKeywordsAndEventWithSpecificKeywordIsRaised()
        {
            this.tableName = "WhenNotEnabledWithKeywordsAndEventWithSpecificKeywordIsRaised";
            var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"];

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

            using (var listener = new ObservableEventListener())
            {
                try
                {
                    listener.LogToWindowsAzureTable("mytestinstance", connectionString, this.tableName, bufferingInterval: TimeSpan.FromSeconds(10));
                    listener.EnableEvents(logger, EventLevel.LogAlways);
                    logger.ErrorWithKeywordDiagnostic("Error with keyword EventlogClassic");
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            var eventsCount = AzureTableHelper.GetEventsCount(connectionString, this.tableName);

            Assert.AreEqual(0, eventsCount);
        }
Example #13
0
        public void UnderReleaseBufferLeak()
        {
            ResourceLeakDetector.DetectionLevel preservedLevel = ResourceLeakDetector.Level;
            try
            {
                ResourceLeakDetector.Level = ResourceLeakDetector.DetectionLevel.Paranoid;
                var eventListener = new ObservableEventListener();
                Mock <IObserver <EventEntry> > logListener = this.mockRepo.Create <IObserver <EventEntry> >();
                var eventTextFormatter = new EventTextFormatter();
                Func <EventEntry, bool> leakPredicate = y => y.TryFormatAsString(eventTextFormatter).Contains("LEAK");
                logListener.Setup(x => x.OnNext(It.Is <EventEntry>(y => leakPredicate(y)))).Verifiable();
                logListener.Setup(x => x.OnNext(It.Is <EventEntry>(y => !leakPredicate(y))));
                eventListener.Subscribe(logListener.Object);
                eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

                this.CreateAndForgetBuffer();

                GC.Collect();
                GC.WaitForPendingFinalizers();

                this.mockRepo.Verify();
            }
            finally
            {
                ResourceLeakDetector.Level = preservedLevel;
            }
        }
Example #14
0
        public void WhenExceptionOccursInCustomFormatter()
        {
            string fileName = "FlatFileInProcCustomFormatterHandleException.log";

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

            using (var listener = new ObservableEventListener())
                using (var collectErrorsListener = new InMemoryEventListener(true))
                {
                    try
                    {
                        collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, System.Diagnostics.Tracing.EventLevel.Error, Keywords.All);
                        listener.LogToFlatFile(fileName, new MockFormatter(true));
                        listener.EnableEvents(logger, System.Diagnostics.Tracing.EventLevel.LogAlways);
                        logger.EventWithPayload("payload1", 100);

                        StringAssert.Contains(collectErrorsListener.ToString(), "Payload : [message : System.InvalidOperationException: Operation is not valid due to the current state of the object.");
                    }
                    finally
                    {
                        listener.DisableEvents(logger);
                        collectErrorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                    }
                }
        }
Example #15
0
        public async Task TestUdpEventSink()
        {
            int port      = 11001;
            var udpclient = new UdpClient(port);

            var slabListener = new ObservableEventListener();

            slabListener.Subscribe(new UdpEventSink(IPAddress.Loopback, port, new TestEventFormatter()));
            var source = TestEventSource.GetInstance();

            slabListener.EnableEvents(source, EventLevel.LogAlways, Keywords.All);

            var t = udpclient.ReceiveAsync();

            source.Message("Boris", "Meep");

            var receivedText = Encoding.UTF8.GetString((await t).Buffer);

            Assert.Equal(
                "EventId=1 EventName=MessageInfo Level=Error \"FormattedMessage=Meep - Boris\" \"message=Boris\" \"caller=Meep\"\r\n",
                receivedText);

            udpclient.Close();
            slabListener.Dispose();
        }
        public async Task TestEventSink()
        {
            var listener = new TcpListener(IPAddress.Loopback, 0);
            listener.Start();
            int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;

            var slabListener = new ObservableEventListener();
            slabListener.Subscribe(new TcpEventSink(IPAddress.Loopback, port, 
                new ExponentialBackoffTcpReconnectionPolicy(),
                new TestEventFormatter()));
            var source = TestEventSource.GetInstance();
            slabListener.EnableEvents(source, EventLevel.LogAlways, Keywords.All);

            var listenerClient = await listener.AcceptTcpClientAsync();

            source.Message("Boris", "Meep");

            var receiverReader = new StreamReader(listenerClient.GetStream());
            var line = await receiverReader.ReadLineAsync();

            Assert.Equal(
                "EventId=1 EventName=MessageInfo Level=Error \"FormattedMessage=Meep - Boris\" \"message=Boris\" \"caller=Meep\"",
                line);

            listenerClient.Close();
            listener.Stop();
            slabListener.Dispose();
        }
Example #17
0
        public void UnderReleaseBufferLeak()
        {
            ResourceLeakDetector.DetectionLevel preservedLevel = ResourceLeakDetector.Level;
            try
            {
                ResourceLeakDetector.Level = ResourceLeakDetector.DetectionLevel.Paranoid;
                var eventListener = new ObservableEventListener();
                Mock<IObserver<EventEntry>> logListener = this.mockRepo.Create<IObserver<EventEntry>>();
                var eventTextFormatter = new EventTextFormatter();
                Func<EventEntry, bool> leakPredicate = y => y.TryFormatAsString(eventTextFormatter).Contains("LEAK");
                logListener.Setup(x => x.OnNext(It.Is<EventEntry>(y => leakPredicate(y)))).Verifiable();
                logListener.Setup(x => x.OnNext(It.Is<EventEntry>(y => !leakPredicate(y))));
                eventListener.Subscribe(logListener.Object);
                eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);

                this.CreateAndForgetBuffer();

                GC.Collect();
                GC.WaitForPendingFinalizers();

                this.mockRepo.Verify();
            }
            finally
            {
                ResourceLeakDetector.Level = preservedLevel;
            }
        }
Example #18
0
        /// <summary>
        /// Creates an event listener that logs using a <see cref="FlatFileSink"/>.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="formatter">The formatter.</param>
        /// <param name="isAsync">Specifies if the writing should be done asynchronously, or synchronously with a blocking call.</param>
        /// <returns>An event listener that uses <see cref="FlatFileSink"/> to log events.</returns>
        public static EventListener CreateListener(string fileName = null, IEventTextFormatter formatter = null, bool isAsync = false)
        {
            var listener = new ObservableEventListener();

            listener.LogToFlatFile(fileName, formatter, isAsync);
            return(listener);
        }
Example #19
0
        /// <summary>
        /// Creates an event listener that logs using a <see cref="T:SemanticLogging.SignalR.SignalRSink"/>.
        ///
        /// </summary>
        /// <param name="formatter">The formatter.</param>
        /// <returns>
        /// An event listener that uses <see cref="T:SemanticLogging.SignalR.SignalRSink"/> to display events.
        /// </returns>
        public static EventListener CreateListener(IEventTextFormatter formatter = null)
        {
            ObservableEventListener observableEventListener = new ObservableEventListener();

            LogToSignalR((IObservable <EventEntry>)observableEventListener, formatter);
            return((EventListener)observableEventListener);
        }
Example #20
0
 protected TestBase(ITestOutputHelper output)
 {
     this.Output        = output;
     this.eventListener = new ObservableEventListener();
     this.eventListener.LogToTestOutput(output);
     this.eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);
 }
Example #21
0
 protected TestBase(ITestOutputHelper output)
 {
     this.Output = output;
     this.eventListener = new ObservableEventListener();
     this.eventListener.LogToTestOutput(output);
     this.eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);
 }
        public void LogFailure2LogToFlatFileTest()
        {
            string   _filePath = $"{nameof(LogFailure2LogToFlatFileTest)}.log";
            FileInfo _logFile  = new FileInfo(_filePath);

            if (_logFile.Exists)
            {
                _logFile.Delete();
            }
            MessageHandlerFactory   _factory          = new MessageHandlerFactory();
            ObservableEventListener _listener         = new ObservableEventListener();
            UDPMessageHandlerSemanticEventSource _log = UDPMessageHandlerSemanticEventSource.Log;

            _listener.EnableEvents(_log, EventLevel.LogAlways, Keywords.All);
            SinkSubscription <FlatFileSink> _FlatFileSink = _listener.LogToFlatFile(_filePath);

            _logFile.Refresh();
            Assert.IsTrue(_logFile.Exists);
            Assert.AreEqual <long>(0, _logFile.Length);

            _log.Failure(nameof(UDPMessageHandlerSemanticEventSourceUnitTest), nameof(LogFailure2LogToFlatFileTest), "LogFailure");

            _FlatFileSink.Sink.FlushAsync();
            _logFile.Refresh();
            Assert.IsTrue(_logFile.Length > 100);
            _FlatFileSink.Dispose();
        }
        public void EventWithPayloadAndEnumsInXml()
        {
            string fileName = "LogUsingPayloadWithEnumsInProc";

            File.Delete(fileName);
            var formatter = new XmlEventTextFormatter(EventTextFormatting.Indented, "d");
            var logger    = MockEventSourceInProcEnum.Logger;

            using (var listener = new ObservableEventListener())
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, Keywords.All);
                listener.LogToFlatFile(fileName, formatter);
                try
                {
                    logger.SendEnumsEvent16(MockEventSourceInProcEnum.MyColor.Green, MockEventSourceInProcEnum.MyFlags.Flag1);
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            var rawOutput = FlatFileHelper.GetAllText(fileName);
            var entries   = XDocument.Parse("<Events>" + rawOutput + "</Events>").Root.Elements();

            Assert.AreEqual(1, entries.Count());
            XmlFormattedEntry.Fill(entries.First());
            Assert.AreEqual("a", XmlFormattedEntry.Payload.Elements().First().Attribute("Name").Value);
            Assert.AreEqual("2", XmlFormattedEntry.Payload.Elements().First().Value);
            Assert.AreEqual("b", XmlFormattedEntry.Payload.Elements().Last().Attribute("Name").Value);
            Assert.AreEqual("1", XmlFormattedEntry.Payload.Elements().Last().Value);
        }
Example #24
0
 public void SetUp()
 {
     AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory);
     this.fileName           = Path.ChangeExtension(Guid.NewGuid().ToString("N"), ".log");
     this.eventTextFormatter = new EventTextFormatter(EventTextFormatter.DashSeparator);
     this.listener           = new ObservableEventListener();
 }
Example #25
0
        public static SinkSubscription <ObservableEventListener> CreateSink(Action <EventEntry> feedback)
        {
            ObservableEventListener _listener    = new ObservableEventListener();
            IDisposable             subscription = _listener.Subscribe(feedback);

            return(new SinkSubscription <ObservableEventListener>(subscription, _listener));
        }
Example #26
0
        public void WhenUsingCustomSink()
        {
            var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString;

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

            string message = string.Concat("Message ", Guid.NewGuid());

            using (var eventListener = new ObservableEventListener())
            {
                try
                {
                    eventListener.LogToCustomSqlDatabase("TestInstanceName", validConnectionString);
                    eventListener.EnableEvents(logger, System.Diagnostics.Tracing.EventLevel.LogAlways, Keywords.All);
                    logger.LogSomeMessage(message);
                }
                finally
                {
                    eventListener.DisableEvents(logger);
                }
            }

            var dt = DatabaseHelper.GetLoggedTable(validConnectionString);

            Assert.AreEqual(1, dt.Rows.Count);
            var dr = dt.Rows[0];

            Assert.AreEqual(4, (int)dr["Level"]);
            Assert.AreEqual(8, (int)dr["EventID"]);
            Assert.AreEqual("TestInstanceName", dr["InstanceName"].ToString());
            StringAssert.Contains((string)dr["Payload"], message);
        }
Example #27
0
        public void CanDeferRequestsForMultipleSources()
        {
            using (EventListener listener = new ObservableEventListener())
            {
                listener.EnableEvents("DeferredEventSource1", EventLevel.Error, EventKeywords.AuditSuccess | EventKeywords.AuditFailure);
                listener.EnableEvents("DeferredEventSource2", EventLevel.Informational, EventKeywords.Sqm, new Dictionary <string, string> {
                    { "key1", "value1" }
                });
                listener.EnableEvents("DeferredEventSource3", EventLevel.Warning, EventKeywords.EventLogClassic, new Dictionary <string, string> {
                    { "key2", "value2" }
                });
                listener.EnableEvents("DeferredEventSource2", EventLevel.Warning, EventKeywords.EventLogClassic, new Dictionary <string, string> {
                    { "key2", "value2" }
                });
                listener.EnableEvents("DeferredEventSource1", EventLevel.Warning, EventKeywords.EventLogClassic, new Dictionary <string, string> {
                    { "key2", "value2" }
                });
                listener.EnableEvents("DeferredEventSource1", EventLevel.Informational, EventKeywords.Sqm, new Dictionary <string, string> {
                    { "key1", "value1" }
                });
                listener.DisableEvents("DeferredEventSource2");
                listener.EnableEvents("DeferredEventSource2", EventLevel.Error, EventKeywords.AuditSuccess | EventKeywords.AuditFailure);
                listener.DisableEvents("DeferredEventSource3");

                Assert.IsTrue(DeferredEventSource1.Log.IsEnabled(EventLevel.Informational, EventKeywords.Sqm));
                Assert.IsFalse(DeferredEventSource1.Log.IsEnabled(EventLevel.Verbose, EventKeywords.Sqm));
                Assert.IsTrue(DeferredEventSource2.Log.IsEnabled(EventLevel.Error, EventKeywords.AuditSuccess));
                Assert.IsFalse(DeferredEventSource2.Log.IsEnabled(EventLevel.Warning, EventKeywords.AuditSuccess));
                Assert.IsFalse(DeferredEventSource3.Log.IsEnabled());
            }
        }
Example #28
0
        public void WhenExceptinOccursInCustomFormater1()
        {
            string filename = "customFormatterException.log";

            File.Delete(filename);
            var logger    = MockEventSource.Logger;
            var formatter = new CustomFormatter(true);

            using (var listener = new ObservableEventListener())
                using (var collectErrorsListener = new InMemoryEventListener(true))
                {
                    try
                    {
                        collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, System.Diagnostics.Tracing.EventLevel.LogAlways, Keywords.All);
                        listener.LogToFlatFile(filename, formatter);
                        listener.EnableEvents(logger, System.Diagnostics.Tracing.EventLevel.LogAlways, Keywords.All);
                        logger.LogSomeMessage("testing");

                        collectErrorsListener.WaitEvents.Wait(3000);
                        StringAssert.Contains(collectErrorsListener.ToString(), "unhandled exception from formatter");
                    }
                    finally
                    {
                        listener.DisableEvents(logger);
                        collectErrorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                    }
                }
        }
        private void EnableNonTransientErrorsHandling()
        {
            var observable = new ObservableEventListener();

            this.slabNonTransientErrors = observable;

            if (this.consoleMode)
            {
                observable.LogToConsole();
            }
            else
            {
                observable.Subscribe(new ServiceEventLogSink(this.EventLog));
            }

            EventLevel level;

            if (!Enum.TryParse(ConfigurationManager.AppSettings[NonTransientErrorsEventLevelKey], out level))
            {
                level = EventLevel.LogAlways;
            }

            this.slabNonTransientErrors.EnableEvents(SemanticLoggingEventSource.Log, level, Keywords.All);

            // Capture any unhandled error in worker threads
            AppDomain.CurrentDomain.UnhandledException += this.OnAppDomainUnhandledException;

            // Handle unobserved task exceptions
            TaskScheduler.UnobservedTaskException += this.OnUnobservedTaskException;
        }
        static void Main(string[] args)
        {
            eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.LogAlways);

            TraceSource source = new TraceSource("DurableTask");

            source.Listeners.AddRange(Trace.Listeners);

            IOrchestrationServiceInstanceStore instanceStore = new AzureTableInstanceStore(TaskHubName, StorageConnectionString);

            ServiceBusOrchestrationService orchestrationServiceAndClient =
                new ServiceBusOrchestrationService(ServiceBusConnectionString, TaskHubName, instanceStore, null, null);

            orchestrationServiceAndClient.CreateIfNotExistsAsync().Wait();

            TaskHubClient taskHubClient = new TaskHubClient(orchestrationServiceAndClient);
            TaskHubWorker taskHub       = new TaskHubWorker(orchestrationServiceAndClient);

            taskHub.AddTaskOrchestrations(typeof(CounterOrchestration));
            taskHub.AddTaskActivities(typeof(Task1), typeof(Task2));

            var instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(CounterOrchestration), Guid.NewGuid().ToString(), new TestOrchestrationInput()).Result;

            taskHub.StartAsync().Wait();

            //taskHubClient.WaitForOrchestrationAsync(instance, TimeSpan.MaxValue).Wait();

            Thread.Sleep(int.MaxValue);
        }
Example #31
0
        static readonly TimeSpan TestTimeout          = TimeSpan.FromMinutes(5);       //TimeSpan.FromMinutes(1);

        public EndToEndTests(ITestOutputHelper output)
        {
            this.output        = output;
            this.eventListener = new ObservableEventListener();
            this.eventListener.LogToTestOutput(output);
            this.eventListener.EnableEvents(MqttIotHubAdapterEventSource.Log, EventLevel.Verbose);
            this.eventListener.EnableEvents(ChannelEventSource.Log, EventLevel.Verbose);
            this.eventListener.EnableEvents(BootstrapEventSource.Log, EventLevel.Verbose);
            this.eventListener.EnableEvents(ExecutorEventSource.Log, EventLevel.Verbose);
            this.eventListener.EnableEvents(MqttEventSource.Log, EventLevel.Verbose);

            this.settingsProvider = new AppConfigSettingsProvider();

            this.ProtocolGatewayPort = 8883; // todo: dynamic port choice to parallelize test runs (first free port)

            this.tlsCertificate = new X509Certificate2("tlscert.pfx", "password");

            string    serverAddress;
            IPAddress serverIp;

            if (this.settingsProvider.TryGetSetting("End2End.ServerAddress", out serverAddress) && IPAddress.TryParse(serverAddress, out serverIp))
            {
                this.ServerAddress = serverIp;
            }
        }
        private SinkTrace TraceSource(
            RequestHandler handler,
            HttpEventCollectorEventInfo.Metadata metadata = null,
            HttpEventCollectorSender.SendMode sendMode    = HttpEventCollectorSender.SendMode.Parallel,
            int batchInterval  = 0,
            int batchSizeBytes = 0,
            int batchSizeCount = 0,
            HttpEventCollectorSender.HttpEventCollectorMiddleware middleware = null)
        {
            var listener = new ObservableEventListener();
            var sink     = new HttpEventCollectorSink(
                uri: uri,
                token: token,
                formatter: new TestEventFormatter(),
                metadata: metadata,
                sendMode: sendMode,
                batchInterval: batchInterval,
                batchSizeBytes: batchSizeBytes,
                batchSizeCount: batchSizeCount,
                middleware: MiddlewareInterceptor(handler, middleware));

            listener.Subscribe(sink);

            var eventSource = TestEventSource.GetInstance();

            listener.EnableEvents(eventSource, EventLevel.LogAlways, Keywords.All);
            return(new SinkTrace()
            {
                Source = eventSource,
                Sink = sink,
                Listener = listener
            });
        }
        /// <summary>
        /// Creates an event listener that logs using a <see cref="RollingFlatFileSink"/>.
        /// </summary>
        /// <param name="fileName">The filename where the entries will be logged.</param>
        /// <param name="rollSizeKB">The maximum file size (KB) before rolling.</param>
        /// <param name="timestampPattern">The date format that will be appended to the new roll file.</param>
        /// <param name="rollFileExistsBehavior">Expected behavior that will be used when the roll file has to be created.</param>
        /// <param name="rollInterval">The time interval that makes the file to be rolled.</param>
        /// <param name="formatter">The formatter.</param>
        /// <param name="maxArchivedFiles">The maximum number of archived files to keep.</param>
        /// <param name="isAsync">Specifies if the writing should be done asynchronously, or synchronously with a blocking call.</param>
        /// <returns>An event listener that uses <see cref="RollingFlatFileSink"/> to log events.</returns>
        public static EventListener CreateListener(string fileName, int rollSizeKB, string timestampPattern, RollFileExistsBehavior rollFileExistsBehavior, RollInterval rollInterval, IEventTextFormatter formatter = null, int maxArchivedFiles = 0, bool isAsync = false)
        {
            var listener = new ObservableEventListener();

            listener.LogToRollingFlatFile(fileName, rollSizeKB, timestampPattern, rollFileExistsBehavior, rollInterval, formatter, maxArchivedFiles, isAsync);
            return(listener);
        }
Example #34
0
        public void WhenUsingCustomSinkAndMultipleEvents()
        {
            string fileName = "ProvidedCustomSink.log";

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

            IEnumerable <string> entries = null;

            using (var eventListener = new ObservableEventListener())
            {
                try
                {
                    eventListener.LogToMockFlatFile(fileName, "==-==");
                    eventListener.EnableEvents(logger, System.Diagnostics.Tracing.EventLevel.LogAlways, Keywords.All);
                    logger.LogSomeMessage("some message");
                    logger.LogSomeMessage("some message2");
                    logger.LogSomeMessage("some message3");

                    entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 3, "==-==");
                }
                finally
                {
                    eventListener.DisableEvents(logger);
                }
            }

            Assert.IsTrue(File.Exists(fileName));
            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]")));
        }
Example #35
0
        public static SinkSubscription <FlatFileSink> CreateSink(EventSource eventSource, string path)
        {
            ObservableEventListener _listener = new ObservableEventListener();

            _listener.EnableEvents(eventSource, EventLevel.LogAlways, Keywords.All);
            return(_listener.LogToFlatFile(path));
        }
Example #36
0
 public void EnablingNullEventSourceNameThrows()
 {
     using (var listener = new ObservableEventListener())
     {
         listener.EnableEvents((string)null, EventLevel.LogAlways);
     }
 }
Example #37
0
        public void TestExporter() {
            var listener = new ObservableEventListener();
            listener.EnableEvents(TflEventSource.Log, EventLevel.Verbose);
            var subscription = listener.LogToConsole(new LegacyLogFormatter());

            var file = Path.GetTempFileName();
            File.WriteAllText(file, @"t1,t2,t3,t4
Monday,10,1.1,1/1/2014
Tuesday,11,2.2,2/1/2014
Wednesday,12,3.3,3/1/2014
Wednesday,12,3.3,3/1/2014
Thursday,13,4.4,4/1/2014
Friday,14,5.5,5/1/2014
Saturday,15,6.6,6/1/2014");

            File.Delete(OUTPUT);

            var profile = new Profiler().Profile(file);
            new ProfileExporter().Export(profile, OUTPUT);

            subscription.Dispose();
            listener.DisableEvents(TflEventSource.Log);
            listener.Dispose();

            Assert.IsTrue(File.Exists(OUTPUT));
        }
Example #38
0
        /// <summary>
        /// This program hosts a Web API that has a controller decorated with a PerfIt filter and then
        /// sends an HTTP request to instrument.
        /// Since it is net452, it will raise ETW that can be captured by Enterprise Library. Note listener.LogToConsole();
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string baseAddress   = "http://localhost:34543/";
            var    configuration = new HttpSelfHostConfiguration(baseAddress);

            configuration.Routes.Add("def", new HttpRoute("api/{controller}"));
            var server = new HttpSelfHostServer(configuration);

            server.OpenAsync().Wait();

            var listener = new ObservableEventListener();

            listener.EnableEvents(InstrumentationEventSource.Instance, EventLevel.LogAlways,
                                  Keywords.All);

            listener.LogToConsole();

            var client = new HttpClient();
            var result = client.GetAsync(baseAddress + "api/test").Result;

            Console.WriteLine(result.Content.ReadAsStringAsync().Result);

            result.EnsureSuccessStatusCode();
            server.CloseAsync().Wait();

            Console.Read();
        }
Example #39
0
        public override void Initialize()
        {
            var eventListener = new ObservableEventListener();

            eventListener.EnableEvents(
                VirtoCommerceEventSource.Log,
                EventLevel.LogAlways,
                Keywords.All);

            

            var assetsConnection = ConfigurationManager.ConnectionStrings["AssetsConnectionString"];

            if (assetsConnection != null)
            {
                var properties = assetsConnection.ConnectionString.ToDictionary(";", "=");
                var provider = properties["provider"];
                var assetsConnectionString = properties.ToString(";", "=", "provider");

                if (string.Equals(provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    eventListener.LogToRollingFlatFile("AvaTax.log",
                        10000,
                        "hh",
                        RollFileExistsBehavior.Increment,
                        RollInterval.Day);
                }
                else
                    if (string.Equals(provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                    {
                        eventListener.LogToWindowsAzureTable(
                            "VirtoCommerce2", assetsConnectionString);

                    }
            }


            var settingsManager = _container.Resolve<ISettingsManager>();
            
            var avalaraTax = new AvaTaxSettings(_usernamePropertyName, _passwordPropertyName, _serviceUrlPropertyName, _companyCodePropertyName, _isEnabledPropertyName, _isValidateAddressPropertyName, settingsManager);
            
            _container.RegisterType<AvaTaxController>
                (new InjectionConstructor(
                    avalaraTax));

            _container.RegisterInstance<ITaxSettings>(avalaraTax);

            //Subscribe to cart changes. Calculate taxes   
            _container.RegisterType<IObserver<CartChangeEvent>, CalculateCartTaxesObserver>("CalculateCartTaxesObserver");

            //Subscribe to order changes. Calculate taxes   
            _container.RegisterType<IObserver<OrderChangeEvent>, CalculateOrderTaxesObserver>("CalculateOrderTaxesObserver");

            //Subscribe to order changes. Calculate taxes   
            _container.RegisterType<IObserver<OrderChangeEvent>, CancelOrderTaxesObserver>("CancelOrderTaxesObserver");

            //Subscribe to order changes. Adjust taxes   
            _container.RegisterType<IObserver<OrderChangeEvent>, CalculateTaxAdjustmentObserver>("CalculateTaxAdjustmentObserver");
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="TestBase" /> class.
        /// </summary>
        protected TestBase()
        {
            var observableEventListener = new ObservableEventListener();

            observableEventListener.EnableEvents(ExceptionLoggingEventSource.Log, EventLevel.LogAlways);

            observableEventListener.LogToConsole();
        }
Example #41
0
        private static void RegisterEFLogger()
        {
            var listener = new ObservableEventListener();
            listener.EnableEvents(EFLogging.Logger, EventLevel.LogAlways, Keywords.All);

            listener.LogToFlatFile("EFSqls.log");
            listener.LogToWindowsAzureTable(instanceName: "Protiviti", connectionString: "UseDevelopmentStorage=true",tableAddress:"EFSqls");
        }
Example #42
0
 /// <summary>
 /// Creates an event listener that logs using a <see cref="ElasticsearchSink" />.
 /// </summary>
 /// <param name="instanceName">The name of the instance originating the entries.</param>
 /// <param name="connectionString">The endpoint address for the Elasticsearch Service.</param>
 /// <param name="index">Index name prefix formatted as index-{0:yyyy.MM.DD}</param>
 /// <param name="type">The Elasticsearch entry type</param>
 /// <param name="flattenPayload">Flatten the payload collection when serializing event entries</param>
 /// <param name="bufferingInterval">The buffering interval between each batch publishing.</param>
 /// <param name="listenerDisposeTimeout">Defines a timeout interval for the flush operation when the listener is disposed.</param>
 /// <param name="maxBufferSize">The maximum number of entries that can be buffered while it's sending to Elasticsearch before the sink starts dropping entries.
 /// This means that if the timeout period elapses, some event entries will be dropped and not sent to the store. Calling <see cref="IDisposable.Dispose" /> on
 /// the <see cref="EventListener" /> will block until all the entries are flushed or the interval elapses.
 /// If <see langword="null" /> is specified, then the call will block indefinitely until the flush operation finishes.</param>
 /// <returns>
 /// An event listener that uses <see cref="ElasticsearchSink" /> to log events.
 /// </returns>
 public static EventListener CreateListener(string instanceName, string connectionString, string index, string type, bool flattenPayload = true,
     TimeSpan? bufferingInterval = null, TimeSpan? listenerDisposeTimeout = null, int maxBufferSize = Buffering.DefaultMaxBufferSize)
 {
     var listener = new ObservableEventListener();
     listener.LogToElasticsearch(instanceName, connectionString, index, type, flattenPayload, bufferingInterval,
         listenerDisposeTimeout, maxBufferSize);
     return listener;
 }
 /// <summary>
 /// Creates an event listener that logs using a <see cref="LogglySink" />.
 /// </summary>
 /// <param name="instanceName">The name of the instance originating the entries.</param>
 /// <param name="connectionString">The endpoint address for the Loggly Service.</param>
 /// <param name="customerToken">The loggly customerToken that must be part of the Url.</param>
 /// <param name="tag">The tag used in loggly updates. Default is to use the instanceName.</param>
 /// <param name="flattenPayload">Flatten the payload if you want the parameters serialized.</param>
 /// <param name="bufferingInterval">The buffering interval between each batch publishing.</param>
 /// <param name="listenerDisposeTimeout">Defines a timeout interval for the flush operation when the listener is disposed.</param>
 /// <param name="maxBufferSize">The maximum number of entries that can be buffered while it's sending to Loggly before the sink starts dropping entries.
 /// This means that if the timeout period elapses, some event entries will be dropped and not sent to the store. Calling <see cref="IDisposable.Dispose" /> on
 /// the <see cref="EventListener" /> will block until all the entries are flushed or the interval elapses.
 /// If <see langword="null" /> is specified, then the call will block indefinitely until the flush operation finishes.</param>
 /// <returns>
 /// An event listener that uses <see cref="LogglySink" /> to log events.
 /// </returns>
 public static EventListener CreateListener(string instanceName, string connectionString, string customerToken, string tag, bool flattenPayload,
     TimeSpan? bufferingInterval = null, TimeSpan? listenerDisposeTimeout = null, int maxBufferSize = Buffering.DefaultMaxBufferSize)
 {
     var listener = new ObservableEventListener();
     listener.LogToLoggly(instanceName, connectionString, customerToken, tag, flattenPayload, 
         bufferingInterval, listenerDisposeTimeout, maxBufferSize);
     return listener;
 }
        static void Main(string[] args)
        {
            // optimizing IOCP performance
            int minWorkerThreads;
            int minCompletionPortThreads;
            ThreadPool.GetMinThreads(out minWorkerThreads, out minCompletionPortThreads);
            ThreadPool.SetMinThreads(minWorkerThreads, Math.Max(16, minCompletionPortThreads));

            int threadCount = Environment.ProcessorCount;
            if (args.Length > 0)
            {
                threadCount = int.Parse(args[0]);
            }

            var eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(BootstrapperEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(MqttIotHubAdapterEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(ChannelEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(BootstrapEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(ExecutorEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(MqttEventSource.Log, EventLevel.Verbose);

            try
            {
                var cts = new CancellationTokenSource();

                var certificate = new X509Certificate2("protocol-gateway.contoso.com.pfx", "password");
                var settingsProvider = new AppConfigSettingsProvider();
                BlobSessionStatePersistenceProvider blobSessionStateProvider = BlobSessionStatePersistenceProvider.CreateAsync(
                    settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageConnectionString"),
                    settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageContainerName")).Result;

                TableQos2StatePersistenceProvider tableQos2StateProvider = TableQos2StatePersistenceProvider.CreateAsync(
                    settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageConnectionString"),
                    settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageTableName")).Result;

                var bootstrapper = new Bootstrapper(settingsProvider, blobSessionStateProvider, tableQos2StateProvider);
                Task.Run(() => bootstrapper.RunAsync(certificate, threadCount, cts.Token), cts.Token);

                while (true)
                {
                    string input = Console.ReadLine();
                    if (input != null && input.ToLowerInvariant() == "exit")
                    {
                        break;
                    }
                }

                cts.Cancel();
                bootstrapper.CloseCompletion.Wait(TimeSpan.FromSeconds(20));
            }
            finally
            {
                eventListener.Dispose();
            }
        }
 protected override void Given()
 {
     ColorMapper = new MockDefaultConsoleColorMapper();
     MockConsole = new MockConsoleOutput();
     Formatter = new EventTextFormatter(EventTextFormatter.DashSeparator) { VerbosityThreshold = EventLevel.Informational };
     Listener = new ObservableEventListener();
     Listener.LogToConsole(Formatter, ColorMapper);
     Listener.EnableEvents(TestEventSource.Log, EventLevel.LogAlways);
 }
Example #46
0
 public LogViewModel()
 {
     LoggedItems = new ObservableCollection<string>();
     EventListener = new ObservableEventListener();
     EventListener.EnableEvents(Logger.Write, EventLevel.Verbose);
     _syncContext = SynchronizationContext.Current;
     EventListener.LogToCollection(PublishLogItem);
     // Can only be called on the dispatcher's thread. 
 }
Example #47
0
        private static void RegisterLogger()
        {
            var listener = new ObservableEventListener();
            listener.EnableEvents(WebApiTracing.Log, EventLevel.LogAlways, Keywords.All);

            listener.LogToConsole();
            listener.LogToFlatFile("test.log");
            listener.LogToWindowsAzureTable(instanceName: "Protiviti", connectionString: "UseDevelopmentStorage=true");
        }
Example #48
0
        partial void InitializeDiagnostics()
        {
            var connectionString = RoleEnvironment.GetConfigurationSettingValue(AzureLoggingConfigurationSettingName);

            this.listener = new ObservableEventListener();
            this.listener.LogToWindowsAzureTable(RoleEnvironment.CurrentRoleInstance.Id, connectionString, bufferingInterval: TimeSpan.FromSeconds(30));

            this.SetupListener();
            RoleEnvironment.Changed += RoleEnvironment_Changed;
        }
Example #49
0
        static void Main(string[] args)
        {
            if (args.Length < 5)
            {
                Console.WriteLine("Mamemaki.Slab.BigQuery.PlayGround.exe <projectId> <datasetId> <tableId> <serviceAccountEmail> <privateKeyFile>");
                return;
            }
            var projectId = args[0];
            var datasetId = args[1];
            var tableId = args[2];
            var serviceAccountEmail = args[3];
            var privateKeyFile = args[4];
            var tableSchemaFile = args[5];

            using (var listenerConsole = new ObservableEventListener())
            using (var listener = new ObservableEventListener())
            {
                var formatterConsole = new EventTextFormatter(
                    "+=========================================+");

                // Setup listener for debug
                listenerConsole.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways);
                listenerConsole.EnableEvents(BigQuerySinkEventSource.Log, EventLevel.LogAlways);
                listenerConsole.LogToConsole(formatterConsole);

                // Setup listener for playgrond
                listener.EnableEvents(PlayGroundEventSource.Log, EventLevel.LogAlways);
                listener.LogToConsole(formatterConsole);
                listener.LogToBigQuery(
                    projectId: projectId,
                    datasetId: datasetId,
                    tableId: tableId,
                    authMethod: "private_key",
                    serviceAccountEmail: serviceAccountEmail,
                    privateKeyFile: privateKeyFile,
                    privateKeyPassphrase: "notasecret",
                    autoCreateTable: true,
                    tableSchemaFile: tableSchemaFile,
                    insertIdFieldName: "%uuid%",
                    bufferingInterval: TimeSpan.FromSeconds(1),
                    bufferingCount: 3,
                    bufferingFlushAllTimeout: Constants.DefaultBufferingFlushAllTimeout,
                    maxBufferSize: 30000);

                PlayGroundEventSource.Log.Trace("start");
                InsertRows(3);
                Thread.Sleep(1);
                InsertRows(3);
                PlayGroundEventSource.Log.Trace("end");
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();
        }
Example #50
0
 private void ConfigureLogging()
 {
     eventListener = new ObservableEventListener();
     eventListener.EnableEvents(SparkEngineEventSource.Log, EventLevel.LogAlways,
         Keywords.All);
     eventListener.EnableEvents(SparkMongoEventSource.Log, EventLevel.LogAlways,
         Keywords.All);
     eventListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways, Keywords.All);
     var formatter = new JsonEventTextFormatter(EventTextFormatting.Indented);
     eventListener.LogToFlatFile(@"C:\projects\fhir\log\spark.log", formatter);
 }
        public static void Start()
        {
            if (_listener != null)
            {
                throw new InvalidOperationException("Logging infrastucture already running");
            }

            _listener = new ObservableEventListener();
            _listener.EnableEvents(EtwSampleServerEventSource.Log, EventLevel.LogAlways);
            _listener.LogToConsole(new SampleFormatter());
        }
 /// <summary>
 /// Creates an event listener that logs using a <see cref="SeqSink" />.
 /// </summary>
 /// <param name="serverUrl">The base URL of the Seq server that log events will be written to.</param>
 /// <param name="apiKey">A Seq <i>API key</i> that authenticates the client to the Seq server.</param>
 /// <param name="bufferingInterval">The buffering interval between each batch publishing. Default value is <see cref="Buffering.DefaultBufferingInterval" />.</param>
 /// <param name="listenerDisposeTimeout">Time limit for flushing the entries after an <see cref="SeqSink.OnCompleted" /> call is received and before disposing the sink.</param>
 /// <param name="bufferingCount">Number of entries that will trigger batch publishing. Default is <see cref="Buffering.DefaultBufferingCount" /></param>
 /// <param name="maxBufferSize">The maximum number of entries that can be buffered before the sink starts dropping entries.
 /// This means that if the timeout period elapses, some event entries will be dropped and not sent to the store. Normally, calling <see cref="IDisposable.Dispose" /> on
 /// the <see cref="System.Diagnostics.Tracing.EventListener" /> will block until all the entries are flushed or the interval elapses.
 /// If <see langword="null" /> is specified, then the call will block indefinitely until the flush operation finishes.</param>
 /// <returns>
 /// An event listener that uses <see cref="SeqSink" /> to log events.
 /// </returns>
 public static EventListener CreateListener(
     string serverUrl,
     string apiKey = null,
     TimeSpan? bufferingInterval = null,
     TimeSpan? listenerDisposeTimeout = null,
     int bufferingCount = Buffering.DefaultBufferingCount,
     int maxBufferSize = Buffering.DefaultMaxBufferSize)
 {
     var listener = new ObservableEventListener();
     listener.LogToSeq(serverUrl, apiKey, bufferingInterval, listenerDisposeTimeout, bufferingCount, maxBufferSize);
     return listener;
 }
		protected void Application_Start()
		{
			var listener = new ObservableEventListener();
			listener.EnableEvents(WebApiTracing.Log, EventLevel.LogAlways, Keywords.All);
			listener.LogToFlatFile("test.log");

			AreaRegistration.RegisterAllAreas();
			GlobalConfiguration.Configure(WebApiConfig.Register);
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);
		}
Example #54
0
        static void Main(string[] args)
        {
            Options options = new Options();

            CommandLine.Parser.Default.ParseArguments(args, options);

            if (!options.ShowingHelp)
            {
                ObservableEventListener Listener = new ObservableEventListener();
                Listener.EnableEvents((EventSource)Harmonize.Instrumentation.Error, EventLevel.LogAlways, Keywords.All);
                Listener.EnableEvents((EventSource)Harmonize.Instrumentation.Harmonization, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener harmonyEventListener = new ObservableEventListener();
                //harmonyEventListener.EnableEvents((EventSource)With.Harmony.Instrumentation.State, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener owlCommandEventListener = new ObservableEventListener();
                //owlCommandEventListener.EnableEvents((EventSource)With.Owl.Intuition.Instrumentation.Command.Endpoint, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener owlPacketEventListener = new ObservableEventListener();
                //owlPacketEventListener.EnableEvents((EventSource)With.Owl.Intuition.Instrumentation.Packet.Endpoint, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener owlStateEventListener = new ObservableEventListener();
                //owlStateEventListener.EnableEvents((EventSource)With.Owl.Intuition.Instrumentation.State.Machine, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener xmppEventListener = new ObservableEventListener();
                //xmppEventListener.EnableEvents((EventSource)With.Harmony.Instrumentation.Xmpp, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener alljoynEventListener = new ObservableEventListener();
                //alljoynEventListener.EnableEvents(With.Alljoyn.Instrumentation.Coordinator, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener storeEventListener = new ObservableEventListener();
                //storeEventListener.EnableEvents((EventSource)State.Instrumentation.Store, EventLevel.LogAlways, Keywords.All);

                //ObservableEventListener messagingEventListener = new ObservableEventListener();
                //messagingEventListener.EnableEvents((EventSource)With.Messaging.Instrumentation.Messages, EventLevel.LogAlways, Keywords.All);

                options.TraceEvents.Split(',').Select(name => Listener.EnableEvents(name, EventLevel.LogAlways, Keywords.All)).ForEach(Cons.WriteLine);

                using (new CompositeDisposable(Listener.LogToConsole()))
                {
                    Client client = new Client(options);

                    client.Start();

                    System.Console.WriteLine("Started");
                    System.Console.WriteLine("Hit Return to stop");
                    System.Console.ReadLine();

                    client.Stop();
                }
            }
        }
Example #55
0
        public static void Configure()
        {
            List<EventSource> eventSources = new List<EventSource>(new[] { DomainEventSource.Log });

            ObservableEventListener logListner = new ObservableEventListener();

            foreach (var eventSource in eventSources)
            {
                logListner.EnableEvents(eventSource, EventLevel.Error , Keywords.All);
            }

            logListner.LogToFlatFile("log.txt");
        }
        public void SetupTest()
        {
            var listener = new ObservableEventListener();
            listener.EnableEvents(WebApiTracing.Log, EventLevel.LogAlways, Keywords.All);
            listener.LogToConsole();
            listener.LogToTestInMemorySink(_testResults);

            _cts = new CancellationTokenSource();

            _config.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional });
            _config.Services.Replace(typeof(ITraceWriter), new SlabTraceWriter());
            var server = new HttpServer(_config);
            _client = new HttpMessageInvoker(server);
        }
Example #57
0
        public static void RegisterLoggingSources(IEnumerable<EventSource> logSources, ISiteSettings settings)
        {
            var logListener = new ObservableEventListener();

            foreach (var logSource in logSources)
            {
                logListener.EnableEvents(
                  logSource, EventLevel.LogAlways, Keywords.All);
            }

            logListener.LogToFlatFile(
                    fileName: settings.LogFilePath,
                    formatter: new EventTextFormatter());
        }
        public static void Configure()
        {
            List<EventSource> eventSources = new List<EventSource>() { DomainEventSource.Log, SiteEventSource.Log };

            ObservableEventListener logListener = new ObservableEventListener();

            foreach (var eventSource in eventSources)
            {
                logListener.EnableEvents(eventSource, EventLevel.LogAlways, Keywords.All);
            }


            logListener.LogToFlatFile("./Log.txt");
        }
        public void TestInitialize()
        {
            obsListener = new ObservableEventListener();
            obsListener.EnableEvents(AExpenseEvents.Log, EventLevel.LogAlways, Keywords.All);

            DatabaseHelper.CleanLoggingDB(TracingDatabaseConnectionString);

            this.container = new UnityContainer();
            ContainerBootstrapper.Configure(container);

            this.ldapStore = container.Resolve<IProfileStore>();
            this.exceptionMgr = container.Resolve<ExceptionManager>();

        }
Example #60
0
        static void Main(string[] args) {

            var listener = new ObservableEventListener();
            listener.EnableEvents(TflEventSource.Log, EventLevel.Informational);
            var subscription = listener.LogToConsole(new LegacyLogFormatter());

            ValidateArguments(args);

            new ProfileExporter().Export(new Profiler().Profile(_input, _sample), _output);

            subscription.Dispose();
            listener.DisableEvents(TflEventSource.Log);
            listener.Dispose();
        }