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 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;
        }
Пример #3
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;
            }
        }
Пример #4
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();
        }
Пример #5
0
        public static SinkSubscription <ObservableEventListener> CreateSink(Action <EventEntry> feedback)
        {
            ObservableEventListener _listener    = new ObservableEventListener();
            IDisposable             subscription = _listener.Subscribe(feedback);

            return(new SinkSubscription <ObservableEventListener>(subscription, _listener));
        }
        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
            });
        }
Пример #7
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;
            }
        }
        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();
        }
Пример #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //loggerFactory
            //    .AddConsole(Configuration.GetSection("Logging"))
            //    .AddDebug();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Verbose()
                         .WriteTo.ColoredConsole(LogEventLevel.Verbose, "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{OzzyEvent}")
                         .CreateLogger();

            var listener = new ObservableEventListener();

            listener.EnableEvents(OzzyLogger <ICommonEvents> .LogEventSource, EventLevel.LogAlways);
            listener.EnableEvents(OzzyLogger <IDomainModelTracing> .LogEventSource, EventLevel.Informational);
            listener.EnableEvents(OzzyLogger <IDistibutedLockEvents> .LogEventSource, EventLevel.LogAlways);


            var log    = loggerFactory.CreateLogger <OzzyLoggerValue>();
            var parser = new MessageTemplateParser();

            listener.Subscribe(new SimpleEventObserver(e =>
            {
                var logEntry = new LogEvent(DateTime.UtcNow,
                                            GetSerilogLevel(e.Level),
                                            null,
                                            new MessageTemplate(new MessageTemplateToken[] { new TextToken(string.Format(e.Message, e.Payload.ToArray()), 0) }),
                                            e.Payload.Select((p, i) => new LogEventProperty(e.PayloadNames[i], new ScalarValue(p))).Append(new LogEventProperty("OzzyEvent", new OzzyDictionaryValue(e)))
                                            );
                Log.Logger.Write(logEntry);
                //log.Log(LogLevel.Information, new EventId(e.EventId), e, null, (s, ex) => string.Format(s.Message, s.Payload.ToArray()));
            }));


            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //    app.UseBrowserLink();
            //}
            //else
            //{
            //    app.UseExceptionHandler("/Home/Error");
            //}

            //app.UseStaticFiles();

            app.UseCors(builder =>
                        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseOzzy().Start();
        }
Пример #10
0
        public void InitializeTest()
        {
            var fhirModel = new FhirModel();

            eventListener = new ObservableEventListener();
            eventListener.EnableEvents(SparkEngineEventSource.Log, EventLevel.LogAlways,
                                       Keywords.All);
            eventListener.Subscribe(new LogObserver(result => lastLogEntry = result));
            sut = new ElementIndexer(fhirModel);
        }
Пример #11
0
        public void Test1()
        {
            var eventHappened = false;
            var listener      = new ObservableEventListener();

            listener.EnableEvents(OzzyLogger <ICommonEvents> .LogEventSource, EventLevel.Informational);
            listener.Subscribe(new SimpleEventObserver(e => eventHappened = true));
            OzzyLogger <ICommonEvents> .Log.Exception(new Exception());

            Assert.True(eventHappened);
        }
        public void MessageInconsistencyTest()
        {
            EventEntry _lastEvent                = null;
            int        _calls                    = 0;
            ObservableEventListener _listener    = new ObservableEventListener();
            IDisposable             subscription = _listener.Subscribe <EventEntry>(x => { _calls++; _lastEvent = x; });

            using (SinkSubscription <ObservableEventListener> _sinkSubscription = new SinkSubscription <ObservableEventListener>(subscription, _listener))
            {
                Assert.IsNotNull(_sinkSubscription.Sink);

                ReactiveNetworkingEventSource _log = Log;
                _sinkSubscription.Sink.EnableEvents(_log, EventLevel.LogAlways, EventKeywords.All);

                Assert.IsNull(_lastEvent);
                const int _position = 12345;
                _log.MessageInconsistency(_position);
                Assert.IsNotNull(_lastEvent);
                Assert.AreEqual <int>(1, _calls);

                //_lastEvent content
                Assert.AreEqual <int>(4, _lastEvent.EventId);
                Assert.AreEqual <Guid>(Guid.Empty, _lastEvent.ActivityId);
                string _message = "Unexpected end of message while reading 12345 element.";
                Assert.AreEqual <string>(_message, _lastEvent.FormattedMessage, _lastEvent.FormattedMessage);
                //schema
                EventSchema _Schema = _lastEvent.Schema;
                Assert.AreEqual <string>("ConsumerInfo", _Schema.EventName);
                Assert.AreEqual <int>(4, _Schema.Id);
                //Assert.IsTrue((_Schema.Keywords & SemanticEventSource.Keywords.Diagnostic2) > 0);
                //Assert.AreEqual<string>("PackageContent", _Schema.KeywordsDescription);
                Assert.AreEqual <EventLevel>(EventLevel.Warning, _Schema.Level);
                Assert.AreEqual <string>("Info", _Schema.OpcodeName);
                Assert.AreEqual <EventOpcode>(EventOpcode.Info, _Schema.Opcode);
                Assert.AreEqual <Guid>(new Guid("C8666C20-6FEF-4DD0-BB66-5807BA629DA8"), _Schema.ProviderId);
                Assert.AreEqual <string>("UAOOI-Networking-SemanticData-Diagnostics", _Schema.ProviderName);
                Assert.AreEqual <string>("Consumer", _Schema.TaskName);
                Assert.AreEqual <EventTask>(Tasks.Consumer, _Schema.Task);
                Assert.AreEqual <int>(0, _Schema.Version);

                //Payload
                Assert.AreEqual <string>("System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]", _lastEvent.Payload.ToString(), _lastEvent.Payload.ToString());
                Assert.AreEqual <int>(1, _lastEvent.Payload.Count);
                Assert.IsInstanceOfType(_lastEvent.Payload[0], typeof(Int32));
                Assert.AreEqual <Int32>(_position, (Int32)_lastEvent.Payload[0]);
                Assert.AreEqual <string>("position", _lastEvent.Schema.Payload[0]);
            }
        }
        public void JoiningMulticastGroupTest()
        {
            EventEntry _lastEvent                = null;
            int        _calls                    = 0;
            ObservableEventListener _listener    = new ObservableEventListener();
            IDisposable             subscription = _listener.Subscribe(x => { _calls++; _lastEvent = x; });

            using (SinkSubscription <ObservableEventListener> _sinkSubscription = new SinkSubscription <ObservableEventListener>(subscription, _listener))
            {
                Assert.IsNotNull(_sinkSubscription.Sink);

                UDPMessageHandlerSemanticEventSource _log = UDPMessageHandlerSemanticEventSource.Log;
                _sinkSubscription.Sink.EnableEvents(_log, EventLevel.LogAlways, Keywords.All);

                Assert.IsNull(_lastEvent);
                _log.JoiningMulticastGroup(new IPAddress(new byte[] { 192, 168, 0, 0 }));
                Assert.AreEqual <int>(1, _calls);
                Assert.IsNotNull(_lastEvent);

                //_lastEvent content
                Assert.AreEqual <int>(7, _lastEvent.EventId);
                Assert.AreEqual <Guid>(Guid.Empty, _lastEvent.ActivityId);
                string _message = "Joining the multicast group: 192.168.0.0";
                Assert.AreEqual <string>(_message, _lastEvent.FormattedMessage, _lastEvent.FormattedMessage);
                //schema
                EventSchema _Schema = _lastEvent.Schema;
                Assert.AreEqual <string>("StackStart", _Schema.EventName);
                Assert.AreEqual <int>(7, _Schema.Id);
                ////Assert.IsTrue((_Schema.Keywords & UDPMessageHandlerSemanticEventSource.Keywords.Diagnostic) > 0);
                //Assert.AreEqual<string>("PackageContent", _Schema.KeywordsDescription);
                Assert.AreEqual <EventLevel>(EventLevel.Informational, _Schema.Level);
                Assert.AreEqual <string>("Start", _Schema.OpcodeName);
                Assert.AreEqual <EventOpcode>(EventOpcode.Start, _Schema.Opcode);
                Assert.AreEqual <Guid>(new Guid("84C6B563-8282-47CB-9111-7B29D8B43E23"), _Schema.ProviderId);
                Assert.AreEqual <string>("UAOOI-Networking-UDPMessageHandler-Diagnostic", _Schema.ProviderName);
                Assert.AreEqual <string>("Stack", _Schema.TaskName);
                Assert.AreEqual <EventTask>(Tasks.Stack, _Schema.Task);
                Assert.AreEqual <int>(0, _Schema.Version);

                //Payload
                Assert.AreEqual <string>("System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]", _lastEvent.Payload.ToString(), _lastEvent.Payload.ToString());
                Assert.AreEqual <int>(1, _lastEvent.Payload.Count);
                Assert.IsInstanceOfType(_lastEvent.Payload[0], typeof(String));
                Assert.AreEqual <string>("192.168.0.0", (string)_lastEvent.Payload[0]);
                Assert.AreEqual <string>("multicastGroup", _lastEvent.Schema.Payload[0]);
            }
        }
        public void GetIMessageHandlerTest()
        {
            EventEntry _lastEvent                = null;
            int        _calls                    = 0;
            ObservableEventListener _listener    = new ObservableEventListener();
            IDisposable             subscription = _listener.Subscribe(x => { _calls++; _lastEvent = x; });

            using (SinkSubscription <ObservableEventListener> _sinkSubscription = new SinkSubscription <ObservableEventListener>(subscription, _listener))
            {
                Assert.IsNotNull(_sinkSubscription.Sink);

                UDPMessageHandlerSemanticEventSource _log = UDPMessageHandlerSemanticEventSource.Log;
                _sinkSubscription.Sink.EnableEvents(_log, EventLevel.LogAlways, Keywords.All);

                Assert.IsNull(_lastEvent);
                _log.GetIMessageHandler("NameOfIMessageHandlerMethod");
                Assert.AreEqual <int>(1, _calls);
                Assert.IsNotNull(_lastEvent);

                //_lastEvent content
                Assert.AreEqual <int>(2, _lastEvent.EventId);
                Assert.AreEqual <Guid>(Guid.Empty, _lastEvent.ActivityId);
                string _message = "The IMessageHandlerFactory.NameOfIMessageHandlerMethod method has been called.";
                Assert.AreEqual <string>(_message, _lastEvent.FormattedMessage, _lastEvent.FormattedMessage);
                //schema
                EventSchema _Schema = _lastEvent.Schema;
                Assert.AreEqual <string>("CodeBehaviorStart", _Schema.EventName);
                Assert.AreEqual <int>(2, _Schema.Id);
                ////Assert.IsTrue((_Schema.Keywords & UDPMessageHandlerSemanticEventSource.Keywords.Diagnostic) > 0);
                //Assert.AreEqual<string>("PackageContent", _Schema.KeywordsDescription);
                Assert.AreEqual <EventLevel>(EventLevel.Informational, _Schema.Level);
                Assert.AreEqual <string>("Start", _Schema.OpcodeName);
                Assert.AreEqual <EventOpcode>(EventOpcode.Start, _Schema.Opcode);
                Assert.AreEqual <Guid>(new Guid("84C6B563-8282-47CB-9111-7B29D8B43E23"), _Schema.ProviderId);
                Assert.AreEqual <string>("UAOOI-Networking-UDPMessageHandler-Diagnostic", _Schema.ProviderName);
                Assert.AreEqual <string>("CodeBehavior", _Schema.TaskName);
                Assert.AreEqual <EventTask>(Tasks.Infrastructure, _Schema.Task);
                Assert.AreEqual <int>(0, _Schema.Version);

                //Payload
                Assert.AreEqual <string>("System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]", _lastEvent.Payload.ToString(), _lastEvent.Payload.ToString());
                Assert.AreEqual <int>(1, _lastEvent.Payload.Count);
                Assert.IsInstanceOfType(_lastEvent.Payload[0], typeof(String));
                Assert.AreEqual <string>("NameOfIMessageHandlerMethod", (string)_lastEvent.Payload[0]);
                Assert.AreEqual <string>("iMessageHandlerName", _lastEvent.Schema.Payload[0]);
            }
        }
Пример #15
0
        public void StartingApplicationTest()
        {
            EventEntry _lastEvent                = null;
            int        _calls                    = 0;
            ObservableEventListener _listener    = new ObservableEventListener();
            IDisposable             subscription = _listener.Subscribe(x => { _calls++; _lastEvent = x; });

            using (SinkSubscription <ObservableEventListener> _sinkSubscription = new SinkSubscription <ObservableEventListener>(subscription, _listener))
            {
                Assert.IsNotNull(_sinkSubscription.Sink);

                ReferenceApplicationEventSource _log = ReferenceApplicationEventSource.Log;
                _sinkSubscription.Sink.EnableEvents(_log, EventLevel.LogAlways, EventKeywords.All);

                Assert.IsNull(_lastEvent);
                _log.StartingApplication("Message handler name");
                Assert.IsNotNull(_lastEvent);
                Assert.AreEqual <int>(1, _calls);

                //_lastEvent content
                Assert.AreEqual <int>(2, _lastEvent.EventId);
                Assert.AreEqual <Guid>(Guid.Empty, _lastEvent.ActivityId);
                string _message = "The application has been started using the message handling provider Message handler name.";
                Assert.AreEqual <string>(_message, _lastEvent.FormattedMessage, _lastEvent.FormattedMessage);
                //schema
                EventSchema _Schema = _lastEvent.Schema;
                Assert.AreEqual <string>("InfrastructureStart", _Schema.EventName);
                Assert.AreEqual <int>(2, _Schema.Id);
                //Assert.IsTrue((_Schema.Keywords & SemanticEventSource.Keywords.Diagnostic2) > 0);
                //Assert.AreEqual<string>("PackageContent", _Schema.KeywordsDescription);
                Assert.AreEqual <EventLevel>(EventLevel.Informational, _Schema.Level);
                Assert.AreEqual <string>("Start", _Schema.OpcodeName);
                Assert.AreEqual <EventOpcode>(EventOpcode.Start, _Schema.Opcode);
                Assert.AreEqual <Guid>(new Guid("D8637D00-5EAD-4538-9286-8C6DE346D8C8"), _Schema.ProviderId);
                Assert.AreEqual <string>("UAOOI-Networking-ReferenceApplication-Diagnostic", _Schema.ProviderName);
                Assert.AreEqual <string>("Infrastructure", _Schema.TaskName);
                Assert.AreEqual <EventTask>(Tasks.Infrastructure, _Schema.Task);
                Assert.AreEqual <int>(0, _Schema.Version);

                //Payload
                Assert.AreEqual <string>("System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]", _lastEvent.Payload.ToString(), _lastEvent.Payload.ToString());
                Assert.AreEqual <int>(1, _lastEvent.Payload.Count);
            }
        }
Пример #16
0
        public void ReferenceApplicationEventSourceExtensionsTest()
        {
            List <EventEntry>       _lastEvents  = new List <EventEntry>();
            ObservableEventListener _listener    = new ObservableEventListener();
            IDisposable             subscription = _listener.Subscribe(x => { _lastEvents.Add(x); });

            using (SinkSubscription <ObservableEventListener> _sinkSubscription = new SinkSubscription <ObservableEventListener>(subscription, _listener))
            {
                Assert.IsNotNull(_sinkSubscription.Sink);

                ReferenceApplicationEventSource _log = ReferenceApplicationEventSource.Log;
                _sinkSubscription.Sink.EnableEvents(_log, EventLevel.LogAlways, EventKeywords.All);

                Assert.AreEqual <int>(0, _lastEvents.Count);
                NotImplementedException _ex = new NotImplementedException("testing exception", new NotImplementedException());
                _log.LogException(_ex);
                Assert.AreEqual <int>(2, _lastEvents.Count);

                //_lastEvent content
                Assert.AreEqual <int>(1, _lastEvents[0].EventId);
                Assert.AreEqual <Guid>(Guid.Empty, _lastEvents[0].ActivityId);
                string _message = "Application Failure: An exception has benn caught: of type NotImplementedException capturing the message: testing exception";
                Assert.AreEqual <string>(_message, _lastEvents[0].FormattedMessage);
                //schema
                EventSchema _Schema = _lastEvents[0].Schema;
                Assert.AreEqual <string>("InfrastructureInfo", _Schema.EventName);
                Assert.AreEqual <int>(1, _Schema.Id);
                //Assert.IsTrue((_Schema.Keywords & SemanticEventSource.Keywords.Diagnostic2) > 0);
                //Assert.AreEqual<string>("PackageContent", _Schema.KeywordsDescription);
                Assert.AreEqual <EventLevel>(EventLevel.Error, _Schema.Level);
                Assert.AreEqual <string>("Info", _Schema.OpcodeName);
                Assert.AreEqual <EventOpcode>(EventOpcode.Info, _Schema.Opcode);
                Assert.AreEqual <Guid>(new Guid("D8637D00-5EAD-4538-9286-8C6DE346D8C8"), _Schema.ProviderId);
                Assert.AreEqual <string>("UAOOI-Networking-ReferenceApplication-Diagnostic", _Schema.ProviderName);
                Assert.AreEqual <string>("Infrastructure", _Schema.TaskName);
                Assert.AreEqual <EventTask>(Tasks.Infrastructure, _Schema.Task);
                Assert.AreEqual <int>(0, _Schema.Version);

                //Payload
                Assert.AreEqual <string>("System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]", _lastEvents[0].Payload.ToString(), _lastEvents[0].Payload.ToString());
                Assert.AreEqual <int>(1, _lastEvents[0].Payload.Count);
            }
        }
        public void SetUp()
        {
            _clientMock.Setup(x => x.GetDatabase(InstanceName, null)).Returns(() => _databaseMock.Object);
            _databaseMock.Setup(x => x.GetCollection <BsonDocument>(CollectionName, null))
            .Returns(() => _collectionMock.Object);

            _sink = new MongoSink(
                _clientMock.Object,
                InstanceName,
                CollectionName,
                _bufferingInterval,
                int.MaxValue,
                int.MaxValue,
                TimeSpan.Zero);

            _eventListener = new ObservableEventListener();
            _eventListener.EnableEvents(TestEventSource.EventSource, EventLevel.LogAlways);
            _subscription = _eventListener.Subscribe(_sink);
        }
Пример #18
0
        private static IEnumerable <ObservableEventListener> SetupLoggingEventListeners(WebSettings args,
                                                                                        PusherEventSource pusherEventSource)
        {
            // Log run diagnostics and request group summaries to console
            // Using custom Observer instead of the verbose consoleLoggingListener.LogToConsole();
            var consoleLoggingListener = new ObservableEventListener();

            consoleLoggingListener.Subscribe(
                Observer.Create <EventEntry>(entry => Console.WriteLine(entry.FormattedMessage)));
            consoleLoggingListener.EnableEvents(
                pusherEventSource,
                EventLevel.Informational,
                PusherEventSource.Keywords.RunDiagnostics | PusherEventSource.Keywords.GroupingSummary);

            yield return(consoleLoggingListener);

            // Log all responses to rolling flat file only if total requests for run is under limit
            var totalRequestsExpectedOverRun = Enumerable.Range(args.StartCount, args.TimeDuration)
                                               .Select(requestCount => requestCount > args.MaxRequestCount
                    ? args.MaxRequestCount // Factor in capped maximum requests/second
                    : requestCount)
                                               .Sum();

            if (totalRequestsExpectedOverRun > SpecificationConstants.MaxTotalRequestsAllowedForResponseLogging)
            {
                pusherEventSource.LogInfo(
                    $@"Note: Total request count {totalRequestsExpectedOverRun} 
                            exceeds limit of {SpecificationConstants
                        .MaxTotalRequestsAllowedForResponseLogging} to allow logging of all responses to file.");
                yield break;
            }

            var flatFileLoggingListener = new ObservableEventListener();


            flatFileLoggingListener.EnableEvents(
                pusherEventSource,
                EventLevel.Informational,
                PusherEventSource.Keywords.RequestResponse | PusherEventSource.Keywords.GroupingSummary);

            yield return(flatFileLoggingListener);
        }
Пример #19
0
        public Tuple <int, int> GetProcessIdAndThreadIdThoughEvent()
        {
            using (var listener = new ObservableEventListener())
            {
                var observer = new SimpleObserver <EventEntry>();

                listener.EnableEvents(TestEventSource.Log, EventLevel.Informational, EventKeywords.None);
                listener.Subscribe(observer);

                TestEventSource.Log.Informational("some info");

                EventEntry entry;
                if (observer.Elements.TryTake(out entry, TimeSpan.FromSeconds(10)))
                {
                    return(Tuple.Create(entry.ProcessId, entry.ThreadId));
                }

                throw new TimeoutException("timed out waiting for envent");
            }
        }
Пример #20
0
        public void Leak()
        {
            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);

            var bufPool = new PooledByteBufferAllocator(100, 1000);
            IByteBuffer buffer = bufPool.Buffer(10);

            buffer = null;

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

            this.mockRepo.Verify();
        }
Пример #21
0
        protected override void InitializeLocalLogging()
        {
            _platformEventStream = new ObservableEventListener();
            _platformEventStream.EnableEvents(EventSources.PlatformSources, TraceLevel);

            var formatter = new EventTextFormatter(dateTimeFormat: "O");

            _platformEventStream.Subscribe(evt =>
            {
                StringBuilder b = new StringBuilder();
                using (var writer = new StringWriter(b))
                {
                    formatter.WriteEvent(evt, writer);
                }
                Trace.WriteLine(b.ToString());
            });

            try
            {
                var logsResource = RoleEnvironment.GetLocalResource("Logs");

                var logFile = Path.Combine(logsResource.RootPath, "Platform", "Platform.log.json");

                // Initialize core platform logging
                _subscriptions.Add(_platformEventStream.LogToRollingFlatFile(
                                       fileName: logFile,
                                       rollSizeKB: 1024,
                                       timestampPattern: "yyyyMMdd-HHmmss",
                                       rollFileExistsBehavior: RollFileExistsBehavior.Increment,
                                       rollInterval: RollInterval.Hour,
                                       formatter: new JsonEventTextFormatter(EventTextFormatting.Indented, dateTimeFormat: "O"),
                                       maxArchivedFiles: 768, // We have a buffer size of 1024MB for this folder
                                       isAsync: false));
            }
            catch (Exception ex)
            {
                ServicePlatformEventSource.Log.FatalException(ex);
                throw;
            }
        }
Пример #22
0
        public void Leak()
        {
            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);

            var         bufPool = new PooledByteBufferAllocator(100, 1000);
            IByteBuffer buffer  = bufPool.Buffer(10);

            buffer = null;

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

            this.mockRepo.Verify();
        }
        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 void ReactiveSubscribeTest()
        {
            EventEntry _lastEvent                = null;
            int        _calls                    = 0;
            ObservableEventListener _listener    = new ObservableEventListener();
            IDisposable             subscription = _listener.Subscribe(x => { _calls++; _lastEvent = x; });

            using (SinkSubscription <ObservableEventListener> _sinkSubscription = new SinkSubscription <ObservableEventListener>(subscription, _listener))
            {
                Assert.IsNotNull(_sinkSubscription.Sink);

                UDPMessageHandlerSemanticEventSource _log = UDPMessageHandlerSemanticEventSource.Log;
                _sinkSubscription.Sink.EnableEvents(_log, EventLevel.LogAlways, Keywords.All);

                Assert.IsNull(_lastEvent);
                _log.ReceivedMessageContent(new IPEndPoint(new IPAddress(new byte[] { 192, 168, 0, 0 }), 25), 100, new byte[] { 1, 2, 3, 4 });
                Assert.AreEqual <int>(1, _calls);
                Assert.IsNotNull(_lastEvent);

                //_lastEvent content
                Assert.AreEqual <int>(5, _lastEvent.EventId);
                Assert.AreEqual <Guid>(Guid.Empty, _lastEvent.ActivityId);
                string _message = "Received message: 192.168.0.0:25 [100]: 1,2,3,4";
                Assert.AreEqual <string>(_message, _lastEvent.FormattedMessage, _lastEvent.FormattedMessage);

                Assert.AreEqual <string>("System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]", _lastEvent.Payload.ToString(), _lastEvent.Payload.ToString());
                Assert.AreEqual <int>(1, _lastEvent.Payload.Count);
                Assert.IsInstanceOfType(_lastEvent.Payload[0], typeof(String));
                Assert.AreEqual <string>("192.168.0.0:25 [100]: 1,2,3,4", _lastEvent.Payload[0].ToString());
                Assert.AreEqual <string>("payload0", _lastEvent.Schema.Payload[0]);

                Assert.AreEqual <string>("Info", _lastEvent.Schema.OpcodeName);
                Assert.AreEqual <EventOpcode>(EventOpcode.Info, _lastEvent.Schema.Opcode);
                Assert.AreEqual <string>("Consumer", _lastEvent.Schema.TaskName);
                Assert.AreEqual <EventTask>(Tasks.Consumer, _lastEvent.Schema.Task);
            }
        }
Пример #25
0
        public static SinkSubscription <ObservableEventListener> CreateSink(this ObservableEventListener eventStream, Action <EventEntry> feedback)
        {
            IDisposable subscription = eventStream.Subscribe(feedback);

            return(new SinkSubscription <ObservableEventListener>(subscription, eventStream));
        }
        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;
        }
        public void SetUp()
        {
            _clientMock.Setup(x => x.GetDatabase(InstanceName, null)).Returns(() => _databaseMock.Object);
            _databaseMock.Setup(x => x.GetCollection<BsonDocument>(CollectionName, null))
                .Returns(() => _collectionMock.Object);

            _sink = new MongoSink(
                _clientMock.Object,
                InstanceName,
                CollectionName,
                _bufferingInterval,
                int.MaxValue,
                int.MaxValue,
                TimeSpan.Zero);

            _eventListener = new ObservableEventListener();
            _eventListener.EnableEvents(TestEventSource.EventSource, EventLevel.LogAlways);
            _subscription = _eventListener.Subscribe(_sink);
        }
        protected override void InitializeLocalLogging()
        {
            _platformEventStream = new ObservableEventListener();
            _platformEventStream.EnableEvents(EventSources.PlatformSources, TraceLevel);

            var formatter = new EventTextFormatter(dateTimeFormat: "O");
            _platformEventStream.Subscribe(evt =>
            {
                StringBuilder b = new StringBuilder();
                using (var writer = new StringWriter(b))
                {
                    formatter.WriteEvent(evt, writer);
                }
                Trace.WriteLine(b.ToString());
            });

            try
            {
                var logsResource = RoleEnvironment.GetLocalResource("Logs");

                var logFile = Path.Combine(logsResource.RootPath, "Platform", "Platform.log.json");

                // Initialize core platform logging
                _subscriptions.Add(_platformEventStream.LogToRollingFlatFile(
                    fileName: logFile,
                    rollSizeKB: 1024,
                    timestampPattern: "yyyyMMdd-HHmmss",
                    rollFileExistsBehavior: RollFileExistsBehavior.Increment,
                    rollInterval: RollInterval.Hour,
                    formatter: new JsonEventTextFormatter(EventTextFormatting.Indented, dateTimeFormat: "O"),
                    maxArchivedFiles: 768, // We have a buffer size of 1024MB for this folder
                    isAsync: false));
            }
            catch (Exception ex)
            {
                ServicePlatformEventSource.Log.FatalException(ex);
                throw;
            }
        }
        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
            };
        }