Ejemplo n.º 1
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 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 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());
        }
Ejemplo n.º 4
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);
                        }
                    }
                });
        }
        public void EventWithActivityIdAndRelatedActivityIdInXml()
        {
            var formatter = new XmlEventTextFormatter();
            var logger = MockEventSrcForXml.Logger;

            var activityId = Guid.NewGuid();
            var relatedActivityId = 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.LogUsingMessageWithRelatedActivityId(MockEventSrcForXml.LogMessage, relatedActivityId);
                    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.AreEqual<Guid>(relatedActivityId, Guid.Parse(XmlFormattedEntry.Correlation.Attribute("RelatedActivityID").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)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, 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);
        }
        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);
        }
        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);
        }
        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<int>(System.Diagnostics.Process.GetCurrentProcess().Id, entry.ProcessId);
            Assert.AreEqual<int>(ThreadHelper.GetCurrentUnManagedThreadId(), entry.ThreadId);
            Assert.AreEqual("**test**", entry.Message);
            Assert.AreEqual<byte>(0, entry.Version);
            Assert.AreEqual(1, entry.Payload.Count);
            StringAssert.Contains(entry.Payload.First().ToString(), "test");
        }
        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.º 11
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.º 12
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);
                        }
                    }
                });
        }