Ejemplo n.º 1
0
        public void EventWithActivityIdInXml()
        {
            var formatter = new XmlEventTextFormatter();
            var logger    = MockEventSrcForXml.Logger;

            var    activityId         = Guid.NewGuid();
            var    previousActivityId = Guid.Empty;
            string rawOutput          = string.Empty;

            using (var listener = new InMemoryEventListener(formatter))
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForXml.Keywords.Errors);
                try
                {
                    EventSource.SetCurrentThreadActivityId(activityId, out previousActivityId);
                    logger.LogUsingMessage(MockEventSrcForXml.LogMessage);
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                    EventSource.SetCurrentThreadActivityId(previousActivityId);
                }
            }

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

            XmlFormattedEntry.Fill(entries.First());
            Assert.AreEqual <Guid>(EventSource.GetGuid(typeof(MockEventSrcForXml)), Guid.Parse(XmlFormattedEntry.Provider.Attribute("Guid").Value));
            Assert.AreEqual(1, XmlFormattedEntry.Payload.Elements().Count());
            Assert.AreEqual("message", XmlFormattedEntry.Payload.Elements().First().Attribute("Name").Value);
            Assert.AreEqual(MockEventSrcForXml.LogMessage, XmlFormattedEntry.Payload.Elements().First().Value);
            Assert.AreEqual <Guid>(activityId, Guid.Parse(XmlFormattedEntry.Correlation.Attribute("ActivityID").Value));
            Assert.IsNull(XmlFormattedEntry.Correlation.Attribute("RelatedActivityID"));
        }
        public void TwoEventsWithPayloadsAndMessageInXml()
        {
            var formatter = new XmlEventTextFormatter();
            var logger    = MockEventSrcForXml.Logger;

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener(formatter))
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForXml.Keywords.Errors);
                try
                {
                    logger.LogUsingMessage(MockEventSrcForXml.LogMessage);
                    logger.LogUsingMessage(MockEventSrcForXml.LogMessage + "2");
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

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

            Assert.AreEqual(2, entries.Count());
            XmlFormattedEntry.Fill(entries.First());
            Assert.AreEqual("message", XmlFormattedEntry.Payload.Elements().First().Attribute("Name").Value);
            Assert.AreEqual(MockEventSrcForXml.LogMessage, XmlFormattedEntry.Payload.Elements().First().Value);
            XmlFormattedEntry.Fill(entries.Last());
            Assert.AreEqual("message", XmlFormattedEntry.Payload.Elements().Last().Attribute("Name").Value);
            Assert.AreEqual(MockEventSrcForXml.LogMessage + "2", XmlFormattedEntry.Payload.Elements().First().Value);
            Assert.AreEqual(MockEventSrcForXml.LogMessage, XmlFormattedEntry.Message.Elements().First().Value);
        }
Ejemplo n.º 3
0
        public void WhenCustomFormatterThrowsAnExceptionAndUsedConfig()
        {
            string fileName = "FlatFileOutProcCustomFormatterHandleExceptionViaConfig.log";

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

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

            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
            {
                using (InMemoryEventListener collectErrorsListener = new InMemoryEventListener())
                {
                    try
                    {
                        collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.Error, Keywords.All);
                        logger.LogSomeMessage("some message using formatter that throws");
                        collectErrorsListener.WaitEvents.Wait(5000);

                        StringAssert.Contains(collectErrorsListener.ToString(), "Payload : [message : System.InvalidOperationException: Operation is not valid due to the current state of the object.");
                    }
                    finally
                    {
                        collectErrorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                    }
                }
            });
        }
Ejemplo n.º 4
0
        public void EventWithPayloadAndMessageAndDateTimeFormatInJson()
        {
            var logger    = MockEventSrcForJson.Logger;
            var formatter = new JsonEventTextFormatter();

            formatter.DateTimeFormat = "dd/MM/yyyy";

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener()
            {
                Formatter = formatter
            })
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForJson.Keywords.Errors);
                try
                {
                    logger.LogUsingMessage(MockEventSrcForJson.LogMessage);
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            string today    = System.DateTime.Today.ToString(formatter.DateTimeFormat);
            string tomorrow = System.DateTime.Today.AddDays(1).ToString(formatter.DateTimeFormat);

            Assert.IsTrue(rawOutput.Contains(today) || rawOutput.Contains(tomorrow));
        }
Ejemplo n.º 5
0
        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);
                    }
                }
        }
        public void EventWithInformationalMessageformatDetailedInJson()
        {
            var logger = MockEventSourceNoTask.Logger;

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener()
            {
                Formatter = new JsonEventTextFormatter()
            })
            {
                listener.EnableEvents(logger, EventLevel.LogAlways);
                try
                {
                    logger.InformationalMessageFormat("test");
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            var entries = JsonConvert.DeserializeObject <TestEventEntry[]>("[" + rawOutput + "]");
            var entry   = entries.FirstOrDefault();

            Assert.IsFalse(rawOutput.StartsWith("{\r\n")); // No Formatting (Default)
            Assert.AreEqual <EventLevel>(EventLevel.Informational, entry.Level);
            Assert.AreEqual <EventKeywords>(EventKeywords.None, entry.EventKeywords);
            Assert.AreEqual <EventOpcode>(0, entry.Opcode);
            Assert.AreEqual("**test**", entry.Message);
            Assert.AreEqual <byte>(0, entry.Version);
            Assert.AreEqual(1, entry.Payload.Count);
            StringAssert.Contains(entry.Payload.First().ToString(), "test");
        }
Ejemplo n.º 7
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);
                    }
                }
        }
Ejemplo n.º 8
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);
                    }
                }
        }
        public void ShouldFilterByEventKeywords()
        {
            using (var listener = new InMemoryEventListener())
            {
                listener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways, SemanticLoggingEventSource.Keywords.Formatting);

                SemanticLoggingEventSource.Log.ConsoleSinkWriteFailed("test");

                listener.DisableEvents(SemanticLoggingEventSource.Log);

                Assert.AreEqual(string.Empty, listener.ToString());
            }
        }
Ejemplo n.º 10
0
        public void EventWithPayloadAndMessageWithDateTimeFormatInXml()
        {
            var formatter = new XmlEventTextFormatter();

            formatter.DateTimeFormat = "dd/MM/yyyy";
            var logger = MockEventSrcForXml.Logger;

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener(formatter))
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForXml.Keywords.Errors);
                try
                {
                    logger.LogUsingMessage(MockEventSrcForXml.LogMessage);
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

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

            XmlFormattedEntry.Fill(entries.First());
            Assert.IsFalse(rawOutput.StartsWith("{\r\n")); // No Formatting (Default)
            string today    = System.DateTime.Today.ToString(formatter.DateTimeFormat);
            string tomorrow = System.DateTime.Today.AddDays(1).ToString("dd/MM/yyyy");

            Assert.IsTrue(rawOutput.Contains(today) || rawOutput.Contains(tomorrow));
            Assert.AreEqual <Guid>(EventSource.GetGuid(typeof(MockEventSrcForXml)), Guid.Parse(XmlFormattedEntry.Provider.Attribute("Guid").Value));
            Assert.AreEqual <int>(MockEventSrcForXml.LogUsingMessageEventID, Convert.ToInt32(XmlFormattedEntry.EventId.Value));
            Assert.AreEqual <byte>(0, Convert.ToByte(XmlFormattedEntry.Version.Value));
            Assert.AreEqual <int>((int)EventLevel.Informational, Int32.Parse(XmlFormattedEntry.Level.Value));
            Assert.AreEqual <int>((int)MockEventSrcForXml.Tasks.Page, Int32.Parse(XmlFormattedEntry.Task.Value));
            Assert.AreEqual <long>((long)EventKeywords.None, Int64.Parse(XmlFormattedEntry.Keywords.Value.Replace("0x", string.Empty)));
            Assert.AreEqual <int>((int)EventOpcode.Start, Int32.Parse(XmlFormattedEntry.Opcode.Value));
            Assert.AreEqual <byte>(0, Convert.ToByte(XmlFormattedEntry.Version.Value));
            Assert.AreEqual <int>(System.Diagnostics.Process.GetCurrentProcess().Id, Int32.Parse(XmlFormattedEntry.ProcessId.Value));
            Assert.AreEqual <int>(ThreadHelper.GetCurrentUnManagedThreadId(), Int32.Parse(XmlFormattedEntry.ThreadId.Value));
            DateTime dt;

            Assert.IsTrue(DateTime.TryParseExact(XmlFormattedEntry.TimeCreated.Attribute("SystemTime").Value, formatter.DateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt));
            Assert.AreEqual(1, XmlFormattedEntry.Payload.Elements().Count());
            Assert.AreEqual("message", XmlFormattedEntry.Payload.Elements().First().Attribute("Name").Value);
            Assert.AreEqual(MockEventSrcForXml.LogMessage, XmlFormattedEntry.Payload.Elements().First().Value);
            Assert.AreEqual(MockEventSrcForXml.LogMessage, XmlFormattedEntry.Message.Elements().First().Value);
        }
        public void ShouldWriteByEventKeywords()
        {
            using (var listener = new InMemoryEventListener())
            {
                listener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways, SemanticLoggingEventSource.Keywords.Sink);

                SemanticLoggingEventSource.Log.ConsoleSinkWriteFailed("test");

                listener.DisableEvents(SemanticLoggingEventSource.Log);

                StringAssert.Contains(listener.ToString(), "EventId : 200");
                StringAssert.Contains(listener.ToString(), "Level : Critical");
                StringAssert.Contains(listener.ToString(), "Payload : [message : test]");
            }
        }
        public void ShouldWriteWithNoFiltering()
        {
            using (var listener = new InMemoryEventListener())
            {
                listener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways, Keywords.All);

                SemanticLoggingEventSource.Log.DatabaseSinkPublishEventsFailed("test");

                listener.DisableEvents(SemanticLoggingEventSource.Log);

                StringAssert.Contains(listener.ToString(), "EventId : 101");
                StringAssert.Contains(listener.ToString(), "Level : Error");
                StringAssert.Contains(listener.ToString(), "Payload : [message : test]");
            }
        }
Ejemplo n.º 13
0
        public void WhenCustomFormatterThrowsAnExceptionAndUsedProgramatically()
        {
            string fileName = "FlatFileOutProcCustomFormatterHandleException.log";

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

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

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

            TestScenario.WithConfiguration(
                svcConfiguration,
                () =>
            {
                using (var collectErrorsListener = new InMemoryEventListener())
                {
                    try
                    {
                        collectErrorsListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways, Keywords.All);

                        logger.LogSomeMessage("some message using formatter that throws");
                        collectErrorsListener.WaitEvents.Wait(5000);

                        StringAssert.Contains(collectErrorsListener.ToString(), "Payload : [message : System.InvalidOperationException: Operation is not valid due to the current state of the object.");
                    }
                    finally
                    {
                        collectErrorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                    }
                }
            });
        }
Ejemplo n.º 14
0
        public void WhenSinkAddedWithErrorDoesNotRecycle()
        {
            var fileName = "flatfileListenerOk.log";

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

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

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

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

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

                        collectErrorsListener.WaitEvents.Wait(TimeSpan.FromSeconds(3));
                        StringAssert.Contains(collectErrorsListener.ToString(), "One or more errors occurred when loading the TraceEventService configuration file.");
                        StringAssert.Contains(collectErrorsListener.ToString(), "The given path's format is not supported.");
                        StringAssert.Contains(collectErrorsListener.ToString(), "The configuration was partially successfully loaded. Check logs for further error details.");
                    }
                    finally
                    {
                        File.Delete(configFile);
                        collectErrorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                    }
                }
            });
        }
Ejemplo n.º 15
0
        public void EventWithPayloadKeywrdsNoMsgInXml()
        {
            var logger    = MockEventSrcForXml.Logger;
            var formatter = new XmlEventTextFormatter();

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener(formatter))
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForXml.Keywords.Errors);
                try
                {
                    logger.UsingKeywords(MockEventSrcForXml.LogMessage, long.MaxValue);
                    rawOutput = listener.ToString();
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            Assert.AreEqual(-1, rawOutput.IndexOf("\r\n"));
            var entries = XDocument.Parse("<Events>" + rawOutput + "</Events>").Root.Elements();

            XmlFormattedEntry.Fill(entries.Single());
            Assert.AreEqual <Guid>(EventSource.GetGuid(typeof(MockEventSrcForXml)), Guid.Parse(XmlFormattedEntry.Provider.Attribute("Guid").Value));
            Assert.AreEqual <int>(MockEventSrcForXml.UsingKeywordsEventID, Convert.ToInt32(XmlFormattedEntry.EventId.Value));
            Assert.AreEqual <byte>(0, Convert.ToByte(XmlFormattedEntry.Version.Value));
            Assert.AreEqual <int>((int)EventLevel.Informational, Int32.Parse(XmlFormattedEntry.Level.Value));
            Assert.AreEqual <int>((int)MockEventSrcForXml.Tasks.DBQuery, Int32.Parse(XmlFormattedEntry.Task.Value));
            Assert.AreEqual <long>((long)MockEventSrcForXml.Keywords.Errors, Int64.Parse(XmlFormattedEntry.Keywords.Value.Replace("0x", string.Empty)));
            Assert.AreEqual <int>((int)EventOpcode.Start, Int32.Parse(XmlFormattedEntry.Opcode.Value));
            Assert.AreEqual <int>(System.Diagnostics.Process.GetCurrentProcess().Id, Int32.Parse(XmlFormattedEntry.ProcessId.Value));
            Assert.AreEqual <int>(ThreadHelper.GetCurrentUnManagedThreadId(), Int32.Parse(XmlFormattedEntry.ThreadId.Value));
            DateTime dt;

            Assert.IsTrue(DateTime.TryParseExact(XmlFormattedEntry.TimeCreated.Attribute("SystemTime").Value, EventEntry.DefaultDateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt));
            Assert.AreEqual(2, XmlFormattedEntry.Payload.Elements().Count());
            Assert.AreEqual("message", XmlFormattedEntry.Payload.Elements().First().Attribute("Name").Value);
            Assert.AreEqual(MockEventSrcForXml.LogMessage, XmlFormattedEntry.Payload.Elements().First().Value);
            Assert.AreEqual("longArg", XmlFormattedEntry.Payload.Elements().Last().Attribute("Name").Value);
            Assert.AreEqual(long.MaxValue.ToString(), XmlFormattedEntry.Payload.Elements().Last().Value);
        }
        public void EventWithPayloadAloneInXml()
        {
            var    formatter  = new XmlEventTextFormatter();
            string payloadMsg = ("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<test/>");
            var    logger     = MockEventSrcForXml.Logger;

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener(formatter))
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForXml.Keywords.Errors);
                try
                {
                    logger.LogUsingMessage(payloadMsg);
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

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

            XmlFormattedEntry.Fill(entries.First());
            Assert.IsFalse(rawOutput.StartsWith("{\r\n")); // No Formatting (Default)
            Assert.AreEqual <Guid>(EventSource.GetGuid(typeof(MockEventSrcForXml)), Guid.Parse(XmlFormattedEntry.Provider.Attribute("Guid").Value));
            Assert.AreEqual <int>(MockEventSrcForXml.LogUsingMessageEventID, Convert.ToInt32(XmlFormattedEntry.EventId.Value));
            Assert.AreEqual <byte>(0, Convert.ToByte(XmlFormattedEntry.Version.Value));
            Assert.AreEqual <int>((int)EventLevel.Informational, Int32.Parse(XmlFormattedEntry.Level.Value));
            Assert.AreEqual <int>((int)EventTask.None, Int32.Parse(XmlFormattedEntry.Task.Value));
            Assert.AreEqual <long>((long)EventKeywords.None, Int64.Parse(XmlFormattedEntry.Keywords.Value.Replace("0x", string.Empty)));
            Assert.AreEqual <int>((int)EventOpcode.Start, Int32.Parse(XmlFormattedEntry.Opcode.Value));
            Assert.AreEqual <byte>(0, Convert.ToByte(XmlFormattedEntry.Version.Value));
            DateTime dt;

            Assert.IsTrue(DateTime.TryParseExact(XmlFormattedEntry.TimeCreated.Attribute("SystemTime").Value, EventEntry.DefaultDateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt));
            Assert.AreEqual(1, XmlFormattedEntry.Payload.Elements().Count());
            Assert.AreEqual("message", XmlFormattedEntry.Payload.Elements().First().Attribute("Name").Value);
            Assert.AreEqual(payloadMsg, XmlFormattedEntry.Payload.Elements().First().Value);
        }
Ejemplo n.º 17
0
        public void EventWithPayloadKeywrdsNoMessageInJson()
        {
            var logger = MockEventSrcForJson.Logger;

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener()
            {
                Formatter = new JsonEventTextFormatter()
            })
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForJson.Keywords.Errors);
                try
                {
                    logger.UsingKeywords(MockEventSrcForJson.LogMessage, long.MaxValue);
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            var entries = JsonConvert.DeserializeObject <TestEventEntry[]>("[" + rawOutput + "]");
            var entry   = entries.First();

            Assert.IsFalse(rawOutput.StartsWith("{\r\n")); // No Formatting (Default)
            Assert.AreEqual <Guid>(EventSource.GetGuid(typeof(MockEventSrcForJson)), entry.ProviderId);
            Assert.AreEqual <int>(MockEventSrcForJson.UsingKeywordsEventID, entry.EventId);
            Assert.AreEqual <EventLevel>(EventLevel.Informational, entry.Level);
            Assert.AreEqual <string>("None", entry.EventKeywords.ToString());
            Assert.AreEqual <EventOpcode>(EventOpcode.Start, entry.Opcode);
            Assert.AreEqual <int>(System.Diagnostics.Process.GetCurrentProcess().Id, entry.ProcessId);
            Assert.AreEqual <int>(ThreadHelper.GetCurrentUnManagedThreadId(), entry.ThreadId);
            Assert.AreEqual <byte>(0, entry.Version);
            Assert.AreEqual <EventTask>(MockEventSrcForJson.Tasks.DBQuery, entry.Task);
            Assert.AreEqual(null, entry.Message);
            Assert.AreEqual(2, entry.Payload.Count);
            StringAssert.Contains(entry.Payload.First().ToString(), MockEventSrcForJson.LogMessage);
            StringAssert.Contains(entry.Payload.Last().ToString(), long.MaxValue.ToString());
        }
        public void EventWithPayloadKeywrdsNoMsgIndentedInJson()
        {
            var logger = MockEventSrcForJson.Logger;

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener()
            {
                Formatter = new JsonEventTextFormatter(EventTextFormatting.Indented)
            })
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForJson.Keywords.Errors);
                try
                {
                    logger.UsingKeywords(MockEventSrcForJson.LogMessage, long.MaxValue);
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            Assert.AreEqual(17, rawOutput.Split('\n').Length); //Assert is indented
            var entries = JsonConvert.DeserializeObject <TestEventEntry[]>("[" + rawOutput + "]");
            var entry   = entries.First();

            Assert.AreEqual <Guid>(EventSource.GetGuid(typeof(MockEventSrcForJson)), entry.ProviderId);
            Assert.AreEqual <int>(MockEventSrcForJson.UsingKeywordsEventID, entry.EventId);
            Assert.AreEqual <EventLevel>(EventLevel.Informational, entry.Level);
            Assert.AreEqual <string>("None", entry.EventKeywords.ToString());
            Assert.AreEqual <EventOpcode>(EventOpcode.Start, entry.Opcode);
            Assert.AreEqual <byte>(0, entry.Version);
            Assert.AreEqual <EventTask>(EventTask.None, entry.Task);
            Assert.AreEqual(null, entry.Message);
            Assert.AreEqual(2, entry.Payload.Count);
            StringAssert.Contains(entry.Payload.First().ToString(), MockEventSrcForJson.LogMessage);
            StringAssert.Contains(entry.Payload.Last().ToString(), long.MaxValue.ToString());
        }
        public void EventWithPayloadAndMessageInJson()
        {
            var logger = MockEventSrcForJson.Logger;

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener()
            {
                Formatter = new JsonEventTextFormatter()
            })
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForJson.Keywords.Errors);
                try
                {
                    logger.LogUsingMessage(MockEventSrcForJson.LogMessage);
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            var entries = JsonConvert.DeserializeObject <TestEventEntry[]>("[" + rawOutput + "]");
            var entry   = entries.First();

            Assert.IsFalse(rawOutput.StartsWith("{\r\n")); // No Formatting (Default)
            Assert.AreEqual <Guid>(EventSource.GetGuid(typeof(MockEventSrcForJson)), entry.ProviderId);
            Assert.AreEqual <int>(MockEventSrcForJson.LogUsingMessageEventID, entry.EventId);
            Assert.AreEqual <EventLevel>(EventLevel.Informational, entry.Level);
            Assert.AreEqual <EventKeywords>(EventKeywords.None, entry.EventKeywords);
            Assert.AreEqual <EventOpcode>(EventOpcode.Start, entry.Opcode);
            Assert.AreEqual <byte>(0, entry.Version);
            Assert.AreEqual <EventTask>(EventTask.None, entry.Task);
            Assert.AreEqual(MockEventSrcForJson.LogMessage, entry.Message);
            Assert.AreEqual(1, entry.Payload.Count);
            StringAssert.Contains(entry.Payload.First().ToString(), MockEventSrcForJson.LogMessage);
        }
Ejemplo n.º 20
0
        public void EventWithNoOpCodeNoKeywordsNoVersionNoMsgInJson()
        {
            var logger = MockEventSourceNoTask.Logger;

            string rawOutput = string.Empty;

            using (var listener = new InMemoryEventListener()
            {
                Formatter = new JsonEventTextFormatter()
            })
            {
                listener.EnableEvents(logger, EventLevel.LogAlways);
                try
                {
                    logger.NoTaskNoOpCode1(1, 2, 3);
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                }
            }

            var entries = JsonConvert.DeserializeObject <TestEventEntry[]>("[" + rawOutput + "]");
            var entry   = entries.First();

            Assert.IsFalse(rawOutput.StartsWith("{\r\n")); // No Formatting (Default)
            Assert.AreEqual <EventLevel>(EventLevel.Informational, entry.Level);
            Assert.AreEqual <EventKeywords>(EventKeywords.None, entry.EventKeywords);
            Assert.AreEqual <EventOpcode>(0, entry.Opcode);
            Assert.AreEqual <int>(System.Diagnostics.Process.GetCurrentProcess().Id, entry.ProcessId);
            Assert.AreEqual <int>(ThreadHelper.GetCurrentUnManagedThreadId(), entry.ThreadId);
            Assert.AreEqual <byte>(0, entry.Version);
            Assert.AreEqual(null, entry.Message);
            Assert.AreEqual(3, entry.Payload.Count);
            StringAssert.Contains(entry.Payload.First().ToString(), "[event3Arg0, 1]");
            StringAssert.Contains(entry.Payload.Last().ToString(), "[event3Arg2, 3]");
        }
Ejemplo n.º 21
0
        public void EventWithActivityIdAndRelatedActivityIdInJson()
        {
            var logger = MockEventSrcForJson.Logger;

            var    activityId         = Guid.NewGuid();
            var    relatedActivityId  = Guid.NewGuid();
            var    previousActivityId = Guid.Empty;
            string rawOutput          = string.Empty;

            using (var listener = new InMemoryEventListener()
            {
                Formatter = new JsonEventTextFormatter()
            })
            {
                listener.EnableEvents(logger, EventLevel.LogAlways, MockEventSrcForJson.Keywords.Errors);
                try
                {
                    EventSource.SetCurrentThreadActivityId(activityId, out previousActivityId);
                    logger.LogUsingMessageWithRelatedActivityId(MockEventSrcForJson.LogMessage, relatedActivityId);
                    rawOutput = Encoding.Default.GetString(listener.Stream.ToArray());
                }
                finally
                {
                    listener.DisableEvents(logger);
                    EventSource.SetCurrentThreadActivityId(previousActivityId);
                }
            }

            var entries = JsonConvert.DeserializeObject <TestEventEntry[]>("[" + rawOutput + "]");
            var entry   = entries.First();

            Assert.IsFalse(rawOutput.StartsWith("{\r\n"));
            Assert.AreEqual(MockEventSrcForJson.LogMessage, entry.Message);
            Assert.AreEqual(1, entry.Payload.Count);
            StringAssert.Contains(entry.Payload.First().ToString(), MockEventSrcForJson.LogMessage);
            Assert.AreEqual <Guid>(activityId, entry.ActivityId);
            Assert.AreEqual <Guid>(relatedActivityId, entry.RelatedActivityId);
        }
 protected override void OnCleanup()
 {
     slabListener.DisableEvents(SemanticLoggingEventSource.Log);
     base.OnCleanup();
 }
Ejemplo n.º 23
0
        public void WhenEventsInThreeConsecutiveIntervals()
        {
            this.tableName = "WhenEventsInThreeConsecutiveIntervals";
            var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"];

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

            var bufferingInterval = TimeSpan.FromSeconds(5);
            var insertionInterval = TimeSpan.FromSeconds(1);

            using (var listener = new ObservableEventListener())
                using (var errorsListener = new InMemoryEventListener())
                {
                    try
                    {
                        errorsListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.Verbose);
                        listener.LogToWindowsAzureTable("mytestinstance", connectionString, this.tableName, bufferingInterval: bufferingInterval);
                        listener.EnableEvents(logger, EventLevel.Informational);

                        // 1st interval: Log 10 events
                        for (int i = 0; i < 10; i++)
                        {
                            logger.Informational("Message1");
                        }

                        // 1st interval: Wait for the buffer to flush at end of interval
                        Task.Delay(bufferingInterval).Wait();
                        // 2nd interval: start

                        // 1st interval: Wait for the events to be written and assert
                        Task.Delay(insertionInterval).Wait();
                        Assert.AreEqual(10, AzureTableHelper.GetEventsCount(connectionString, this.tableName));

                        // 2nd interval: Log 10 events
                        for (int i = 0; i < 10; i++)
                        {
                            logger.Informational("Message1");
                        }

                        // 2nd interval: Wait for the buffer to flush at end of interval
                        Task.Delay(bufferingInterval).Wait();
                        // 3rd interval: start

                        // 2nd interval: Wait for the events to be written and assert
                        Task.Delay(insertionInterval).Wait();
                        Assert.AreEqual(20, AzureTableHelper.GetEventsCount(connectionString, this.tableName));

                        // 3rd interval: Log 10 events
                        for (int i = 0; i < 10; i++)
                        {
                            logger.Informational("Message1");
                        }

                        // 3rd interval: Wait for the buffer to flush at end of interval
                        Task.Delay(bufferingInterval).Wait();
                        // 4th interval: start

                        // 3rd interval: Wait for the events to be written and assert
                        Task.Delay(insertionInterval).Wait();
                        Assert.AreEqual(30, AzureTableHelper.GetEventsCount(connectionString, this.tableName));

                        // No errors should have been reported
                        Assert.AreEqual(string.Empty, errorsListener.ToString());
                    }
                    finally
                    {
                        listener.DisableEvents(logger);
                        errorsListener.DisableEvents(SemanticLoggingEventSource.Log);
                    }
                }

            // No more events should have been written during the last flush in the Dispose
            Assert.AreEqual(30, AzureTableHelper.GetEventsCount(connectionString, this.tableName));
        }