public void WhenConfiguringProgrammatically() { this.tableName = "testoutofprocazuretables"; var connectionString = System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"]; AzureTableHelper.DeleteTable(connectionString, this.tableName); var logger = MockEventSourceOutProc.Logger; EventTextFormatter formatter = new EventTextFormatter(); IEnumerable<WindowsAzureTableEventEntry> events = null; EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways); var subject = new EventEntrySubject(); subject.LogToWindowsAzureTable("AzureInstance", connectionString, tableName, TimeSpan.FromSeconds(1)); SinkSettings sinkSettings = new SinkSettings("azureSink", subject, new List<EventSourceSettings>() { { settings } }); List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } }; TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks); TestScenario.WithConfiguration( svcConfiguration, () => { for (int i = 0; i < 10; i++) { logger.Critical("Critical message"); } events = AzureTableHelper.PollForEvents(connectionString, this.tableName, 10); }); Assert.AreEqual<int>(10, events.Count()); Assert.AreEqual<int>(2, events.First().EventId); }
public void WhenMultipleEventsAreRaised() { var fileName = "multipleMessages.log"; File.Delete(fileName); var formatter = new EventTextFormatter("------======------"); var logger = MockEventSource.Logger; TestScenario.With1Listener( logger, listener => { listener.LogToFlatFile(fileName, formatter); listener.EnableEvents(logger, EventLevel.LogAlways); for (int n = 0; n < 300; n++) { logger.Informational("some message to flat file " + n.ToString()); } }); Assert.IsTrue(File.Exists(fileName)); var entries = Regex.Split(ReadFileWithoutLock(fileName), formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)); Assert.AreEqual<int>(300, entries.Count()); StringAssert.Contains(entries.First(), "some message to flat file 0"); StringAssert.Contains(entries.Last(), "some message to flat file 299"); }
public void SetUp() { AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory); this.fileName = Path.ChangeExtension(Guid.NewGuid().ToString("N"), ".log"); this.eventTextFormatter = new EventTextFormatter(EventTextFormatter.DashSeparator); this.listener = new ObservableEventListener(); }
public void WhenFileIsDeletedBetweenSessions() { var fileName = "newflatfile.log"; File.Delete(fileName); var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator); var logger = MockEventSource.Logger; TestScenario.With1Listener( logger, listener => { listener.LogToFlatFile(fileName, formatter); listener.EnableEvents(logger, EventLevel.LogAlways); logger.Informational("Message 1"); }); Assert.IsTrue(File.Exists(fileName)); var entries = Regex.Split(ReadFileWithoutLock(fileName), formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)); Assert.AreEqual<int>(1, entries.Count()); File.Delete(fileName); TestScenario.With1Listener( logger, listener => { listener.LogToFlatFile(fileName, formatter); listener.EnableEvents(logger, EventLevel.LogAlways); logger.Informational("Message 1"); }); Assert.IsTrue(File.Exists(fileName)); }
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 void WhenConcurrentEventsRaised() { var logger = MockEventSourceOutProc.Logger; EventTextFormatter formatter = new EventTextFormatter(); EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways); InMemorySink sink = new InMemorySink(formatter); SinkSettings sinkSettings = new SinkSettings("memorySink", sink, new List<EventSourceSettings>() { { settings } }); List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } }; TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks); TestScenario.WithConfiguration( svcConfiguration, () => { sink.WaitSignalCondition = () => sink.EventWrittenCount == 100; for (int n = 0; n < 100; n++) { logger.LogSomeMessage("some message" + n.ToString()); } sink.WaitOnAsyncEvents.WaitOne(TimeSpan.FromSeconds(10)); }); StringAssert.Contains(sink.ToString(), "some message99"); }
public void WhenEnumsInPayload() { var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString; DatabaseHelper.CleanLoggingDB(validConnectionString); var logger = MockEventSourceOutProcEnum.Logger; EventTextFormatter formatter = new EventTextFormatter(); System.Data.DataTable eventsDataTable = null; var subject = new EventEntrySubject(); subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", bufferingCount: 1); EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProcEnum", null, EventLevel.LogAlways); SinkSettings sinkSettings = new SinkSettings("sqlDBsink", subject, new List<EventSourceSettings>() { { settings } }); List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } }; TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks); TestScenario.WithConfiguration( svcConfiguration, () => { logger.SendEnumsEvent16(MockEventSourceOutProcEnum.MyColor.Blue, MockEventSourceOutProcEnum.MyFlags.Flag3); eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 1); }); Assert.AreEqual(1, eventsDataTable.Rows.Count); StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), @"""a"": 1"); StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), @"""b"": 4"); }
public void WhenUsingSinkProgrammatically() { var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString; DatabaseHelper.CleanLoggingDB(validConnectionString); var logger = MockEventSourceOutProc.Logger; EventTextFormatter formatter = new EventTextFormatter(); EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways); var subject = new EventEntrySubject(); subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(1), 1); System.Data.DataTable eventsDataTable = null; SinkSettings sinkSettings = new SinkSettings("sqlDBsink", subject, new List<EventSourceSettings>() { { settings } }); List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } }; TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks); TestScenario.WithConfiguration( svcConfiguration, () => { for (int n = 0; n < 10; n++) { logger.LogSomeMessage("some message" + n.ToString()); } eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 10); }); Assert.AreEqual(10, eventsDataTable.Rows.Count); StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message"); }
public void WhenUsingRollingSinkProgrammatic() { var logger = MockEventSourceOutProc.Logger; EventTextFormatter formatter = new EventTextFormatter(EventTextFormatter.DashSeparator); var fileName = "newRollingFlatfileSerial.log"; File.Delete(fileName); EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways); var subject = new EventEntrySubject(); subject.LogToRollingFlatFile(fileName, 100, "d", RollFileExistsBehavior.Overwrite, RollInterval.Day, formatter); SinkSettings sinkSettings = new SinkSettings("rollingFlatFileSink", subject, new List<EventSourceSettings>() { { settings } }); List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } }; TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks); IEnumerable<string> entries = null; TestScenario.WithConfiguration( svcConfiguration, () => { for (int n = 0; n < 200; n++) { logger.LogSomeMessage("some message" + n.ToString()); } entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 200, EventTextFormatter.DashSeparator); }); Assert.AreEqual(200, entries.Count()); StringAssert.Contains(entries.First(), "some message0"); StringAssert.Contains(entries.Last(), "some message199"); }
protected override void Given() { ColorMapper = new MockDefaultConsoleColorMapper(); MockConsole = new MockConsoleOutput(); Formatter = new EventTextFormatter(EventTextFormatter.DashSeparator) { VerbosityThreshold = EventLevel.Informational }; Listener = new ObservableEventListener(); Listener.LogToConsole(Formatter, ColorMapper); Listener.EnableEvents(TestEventSource.Log, EventLevel.LogAlways); }
static void Main(string[] args) { if (args.Length < 5) { Console.WriteLine("Mamemaki.Slab.BigQuery.PlayGround.exe <projectId> <datasetId> <tableId> <serviceAccountEmail> <privateKeyFile>"); return; } var projectId = args[0]; var datasetId = args[1]; var tableId = args[2]; var serviceAccountEmail = args[3]; var privateKeyFile = args[4]; var tableSchemaFile = args[5]; using (var listenerConsole = new ObservableEventListener()) using (var listener = new ObservableEventListener()) { var formatterConsole = new EventTextFormatter( "+=========================================+"); // Setup listener for debug listenerConsole.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways); listenerConsole.EnableEvents(BigQuerySinkEventSource.Log, EventLevel.LogAlways); listenerConsole.LogToConsole(formatterConsole); // Setup listener for playgrond listener.EnableEvents(PlayGroundEventSource.Log, EventLevel.LogAlways); listener.LogToConsole(formatterConsole); listener.LogToBigQuery( projectId: projectId, datasetId: datasetId, tableId: tableId, authMethod: "private_key", serviceAccountEmail: serviceAccountEmail, privateKeyFile: privateKeyFile, privateKeyPassphrase: "notasecret", autoCreateTable: true, tableSchemaFile: tableSchemaFile, insertIdFieldName: "%uuid%", bufferingInterval: TimeSpan.FromSeconds(1), bufferingCount: 3, bufferingFlushAllTimeout: Constants.DefaultBufferingFlushAllTimeout, maxBufferSize: 30000); PlayGroundEventSource.Log.Trace("start"); InsertRows(3); Thread.Sleep(1); InsertRows(3); PlayGroundEventSource.Log.Trace("end"); } Console.WriteLine("Press any key to exit"); Console.ReadLine(); }
public void WhenUsingTwoCollectorsForSameEventSourceWithDifferentSinkTypes() { var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString; DatabaseHelper.CleanLoggingDB(validConnectionString); string fileName = "TwoCollectorsSameEventSourceDifferentSinkTypes.log"; File.Delete(fileName); string header = "==========="; var logger = MockEventSourceOutProc.Logger; EventTextFormatter formatter = new EventTextFormatter(header); EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways); var subject = new EventEntrySubject(); subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(1), 1); SinkSettings sinkSettings = new SinkSettings("dbSink", subject, new List<EventSourceSettings>() { { settings } }); var subject2 = new EventEntrySubject(); subject2.LogToFlatFile(fileName, formatter); SinkSettings sinkSettings2 = new SinkSettings("ffSink", subject2, new List<EventSourceSettings>() { { settings } }); System.Data.DataTable eventsDataTable = null; List<SinkSettings> sinks = new List<SinkSettings>() { sinkSettings, sinkSettings2 }; TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks); IEnumerable<string> entries = null; using (TraceEventService collector = new TraceEventService(svcConfiguration)) using (TraceEventService collector2 = new TraceEventService(svcConfiguration)) { collector.Start(); collector2.Start(); try { for (int n = 0; n < 10; n++) { logger.LogSomeMessage("some message" + n.ToString()); } eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 10); entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 10, header); } finally { collector.Stop(); collector2.Stop(); } } Assert.AreEqual(10, eventsDataTable.Rows.Count); StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message"); Assert.AreEqual(10, entries.Count()); StringAssert.Contains(entries.First(), "some message0"); StringAssert.Contains(entries.Last(), "some message9"); }
public void IncludesTaskName() { var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator, verbosityThreshold: EventLevel.LogAlways); using (var listener = new InMemoryEventListener(formatter)) { listener.EnableEvents(Logger, EventLevel.LogAlways, Keywords.All); Logger.DBQueryStart("select * from table"); Logger.DBQueryStop(); var entries = Regex.Split(listener.ToString(), formatter.Header + "\r\n").Where(c => !string.IsNullOrWhiteSpace(c)).ToList(); StringAssert.Matches(entries[0], new Regex("EventName : .*DBQuery")); StringAssert.Matches(entries[1], new Regex("Task : .*" + MyCompanyEventSource.Tasks.DBQuery.ToString())); } }
public void WritesEventData() { var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator) { VerbosityThreshold = EventLevel.Critical }; using (var listener = new InMemoryEventListener(formatter)) { listener.EnableEvents(Logger, EventLevel.LogAlways, Keywords.All); Logger.Failure("Failure message"); formatter.VerbosityThreshold = EventLevel.Informational; Logger.DBQueryStart("select * from table"); Logger.DBQueryStop(); Logger.LogColor(MyColor.Red); var entries = Regex.Split(listener.ToString(), formatter.Header + "\r\n").Where(c => !string.IsNullOrWhiteSpace(c)).ToList(); StringAssert.Contains(entries[0], "EventId : 1"); StringAssert.Contains(entries[0], "Level : Error"); StringAssert.Contains(entries[0], "Payload : [message : Failure message]"); StringAssert.Contains(entries[1], @"EventId : 5 Keywords : 2 Level : Informational Message : Opcode : Start Task : 2 Version : 0 Payload : [sqlQuery : select * from table]"); StringAssert.Contains(entries[2], @"EventId : 6 Keywords : 2 Level : Informational Message : Opcode : Stop Task : 2 Version : 0 Payload :"); StringAssert.Contains(entries[3], @"EventId : 8 Keywords : None Level : Informational Message : Opcode : Info Task : 65526 Version : 0 Payload : [color : 0]"); } }
public void ShouldWriteTimestampWithDefaultDateTimeFormat() { var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator); using (var listener = new InMemoryEventListener(formatter)) { listener.EnableEvents(Logger, EventLevel.LogAlways, Keywords.All); Logger.Failure("error"); var logged = listener.ToString(); var lookup = "Timestamp : "; var lookupIndex = logged.IndexOf(lookup); var dateLength = logged.IndexOf("\r\n", lookupIndex) - lookupIndex - lookup.Length; var ts = logged.Substring(lookupIndex + lookup.Length, dateLength); DateTime dt; Assert.IsTrue(DateTime.TryParseExact(ts, formatter.DateTimeFormat ?? EventEntry.DefaultDateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)); } }
public void WhenUsingTwoCollectorsForSameEventSource() { var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString; DatabaseHelper.CleanLoggingDB(validConnectionString); var logger = MockEventSourceOutProc.Logger; EventTextFormatter formatter = new EventTextFormatter(); EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.LogAlways); var subject = new EventEntrySubject(); subject.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(1), 1); SinkSettings sinkSettings = new SinkSettings("dbSink", subject, new List<EventSourceSettings>() { { settings } }); var subject2 = new EventEntrySubject(); subject2.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.FromSeconds(1), 1); SinkSettings sinkSettings2 = new SinkSettings("dbSink2", subject2, new List<EventSourceSettings>() { { settings } }); System.Data.DataTable eventsDataTable = null; List<SinkSettings> sinks = new List<SinkSettings>() { sinkSettings, sinkSettings2 }; TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks); using (TraceEventService collector = new TraceEventService(svcConfiguration)) using (TraceEventService collector2 = new TraceEventService(svcConfiguration)) { collector.Start(); collector2.Start(); try { for (int n = 0; n < 10; n++) { logger.LogSomeMessage("some message" + n.ToString()); } eventsDataTable = DatabaseHelper.PollUntilEventsAreWritten(validConnectionString, 20); } finally { collector.Stop(); collector2.Stop(); } } Assert.AreEqual(20, eventsDataTable.Rows.Count); StringAssert.Contains(eventsDataTable.Rows[0]["payload"].ToString(), "some message"); }
public void WhenDefaultColorMappingForCritical() { var consoleOutputInterceptor = new MockConsoleOutputInterceptor(); var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator); var logger = MockConsoleListenerEventSource.Logger; TestScenario.With1Listener( logger, listener => { listener.LogToConsole(); listener.EnableEvents(logger, EventLevel.LogAlways); logger.Critical("This is to log critical in Console"); }); var entry = Regex.Split(consoleOutputInterceptor.Ouput, formatter.Header).Where(c => !string.IsNullOrWhiteSpace(c)).SingleOrDefault(); Assert.IsNotNull(entry); StringAssert.Contains(entry, "200"); Assert.AreEqual(DefaultConsoleColorMapper.Critical, consoleOutputInterceptor.OutputForegroundColor); }
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 void WhenTaskNameIsSpecifiedForEvent() { var fileNameWithoutExtension = "RollingFlatFileEL_For_TaskName"; var fileName = fileNameWithoutExtension + ".log"; FlatFileHelper.DeleteCreatedLogFiles(fileNameWithoutExtension); var logger = MockEventSource.Logger; var eventTextFormatter = new EventTextFormatter(EventTextFormatter.DashSeparator); eventTextFormatter.VerbosityThreshold = EventLevel.LogAlways; TestScenario.With1Listener( logger, listener => { listener.LogToRollingFlatFile(fileName, 1, "yyyy", RollFileExistsBehavior.Increment, RollInterval.Day, eventTextFormatter); listener.EnableEvents(logger, EventLevel.LogAlways, Keywords.All); logger.CriticalWithTaskName("CriticalWithTaskName"); logger.InfoWithKeywordDiagnostic("InfoWithKeywordDiagnostic"); Assert.IsTrue(File.Exists(fileNameWithoutExtension + ".log")); }); StringAssert.Contains(File.ReadAllText(fileNameWithoutExtension + ".log"), "Task : 1\r\nVersion : 0\r\nPayload : [message : CriticalWithTaskName] \r\nEventName : PageSuspend"); StringAssert.Contains(File.ReadAllText(fileNameWithoutExtension + ".log"), "Task : 64512\r\nVersion : 0\r\nPayload : [message : InfoWithKeywordDiagnostic] \r\nEventName : InfoWithKeywordDiagnosticInfo"); }
public void WritingToANullWriterThrows() { var formatter = new EventTextFormatter(); formatter.WriteEvent(new EventEntry(Guid.NewGuid(), 0, string.Empty, new System.Collections.ObjectModel.ReadOnlyCollection<object>(new object[0]), DateTimeOffset.MaxValue, new EventSourceSchemaReader().GetSchema(Logger).Values.First()), null); }
public void WritingNullEntryThrows() { var formatter = new EventTextFormatter(); using (var writer = new StringWriter()) { formatter.WriteEvent(null, writer); } }
public void WritesProcessIdAndThreadIdOnSummary() { var formatter = new EventTextFormatter(verbosityThreshold: EventLevel.Critical); using (var writer = new StringWriter()) { var processId = 200; var threadId = 300; formatter.WriteEvent( new EventEntry( Guid.NewGuid(), 0, string.Empty, new System.Collections.ObjectModel.ReadOnlyCollection<object>(new object[0]), DateTimeOffset.MaxValue, processId, threadId, Guid.Empty, Guid.Empty, new EventSourceSchemaReader().GetSchema(Logger).Values.First()), writer); var message = writer.ToString(); var processIdMatch = Regex.Match(message, "\\bProcessId : (?<id>\\d+)\\w?").Groups["id"].Value; var threadIdMatch = Regex.Match(message, "\\bThreadId : (?<id>\\d+)\\w?").Groups["id"].Value; Assert.AreEqual(processId.ToString(), processIdMatch); Assert.AreEqual(threadId.ToString(), threadIdMatch); } }
public void WritesNonEmptyRelatedActivityIdOnSummary() { var formatter = new EventTextFormatter(verbosityThreshold: EventLevel.Critical); using (var writer = new StringWriter()) { var relatedActivityId = Guid.NewGuid(); formatter.WriteEvent( new EventEntry( Guid.NewGuid(), 0, string.Empty, new System.Collections.ObjectModel.ReadOnlyCollection<object>(new object[0]), DateTimeOffset.MaxValue, Guid.Empty, relatedActivityId, new EventSourceSchemaReader().GetSchema(Logger).Values.First()), writer); var message = writer.ToString(); var activityIdMatch = Regex.Match(message, "\\bActivityId : (?<id>[-A-Fa-f0-9]+)\\w?").Groups["id"].Value; var relatedActivityIdMatch = Regex.Match(message, "\\bRelatedActivityId : (?<id>[-A-Fa-f0-9]+)\\w?").Groups["id"].Value; Assert.AreEqual(string.Empty, activityIdMatch); Assert.AreEqual(relatedActivityId.ToString(), relatedActivityIdMatch); } }
public void WritesDetailedOnEventLevel() { var formatter = new EventTextFormatter(EventTextFormatter.DashSeparator) { VerbosityThreshold = EventLevel.Critical }; using (var listener = new InMemoryEventListener(formatter)) { listener.EnableEvents(Logger, EventLevel.LogAlways, Keywords.All); Logger.Failure("Summary"); formatter.VerbosityThreshold = EventLevel.Error; Logger.Failure("Detailed"); var entries = Regex.Split(listener.ToString(), formatter.Header + "\r\n").Where(c => !string.IsNullOrWhiteSpace(c)).ToList(); StringAssert.Contains(entries[0], "EventId : 1"); StringAssert.Contains(entries[0], "Level : Error"); StringAssert.Contains(entries[0], "Payload : [message : Summary]"); StringAssert.Contains(entries[1], @"ProviderId : 659518be-d338-564b-2759-c63c10ef82e2 EventId : 1 Keywords : 4 Level : Error Message : Application Failure: Detailed Opcode : Info Task : 65533 Version : 0 Payload : [message : Detailed] EventName : FailureInfo"); } }
public void WritesCustomHeaderAndFooter() { var formatter = new EventTextFormatter("---header---", "___footer___"); using (var listener = new InMemoryEventListener(formatter)) { listener.EnableEvents(Logger, EventLevel.LogAlways, Keywords.All); Logger.Startup(); var contents = listener.ToString(); Assert.IsTrue(contents.Contains(formatter.Header)); Assert.IsTrue(contents.Contains(formatter.Footer)); } }
public void WritesCustomHeader() { var formatter = new EventTextFormatter("*** header ***"); using (var listener = new InMemoryEventListener(formatter)) { listener.EnableEvents(Logger, EventLevel.LogAlways, Keywords.All); Logger.DBQueryStart("select * from table"); Assert.IsTrue(listener.ToString().Contains(formatter.Header)); } }
public void WritesCustomFooter() { var formatter = new EventTextFormatter(null, "___footer___"); using (var listener = new InMemoryEventListener(formatter)) { listener.EnableEvents(Logger, EventLevel.LogAlways, Keywords.All); Logger.Startup(); Assert.IsTrue(listener.ToString().Contains(formatter.Footer)); } }
public void WhenInfoAndMoreVerboseLevelsAreFiltered() { var logger = MockEventSourceOutProc.Logger; EventTextFormatter formatter = new EventTextFormatter(EventTextFormatter.DashSeparator); var fileName = "FlatFileAllFiltered.log"; File.Delete(fileName); EventSourceSettings settings = new EventSourceSettings("MockEventSourceOutProc", null, EventLevel.Error); var subject = new EventEntrySubject(); subject.LogToFlatFile(fileName, formatter); SinkSettings sinkSettings = new SinkSettings("flatFileSink", subject, new List<EventSourceSettings>() { { settings } }); List<SinkSettings> sinks = new List<SinkSettings>() { { sinkSettings } }; TraceEventServiceConfiguration svcConfiguration = new TraceEventServiceConfiguration(sinks); IEnumerable<string> entries = null; TestScenario.WithConfiguration( svcConfiguration, () => { for (int n = 0; n < 200; n++) { logger.LogSomeMessage("some message " + n.ToString()); logger.Critical("some error " + n.ToString()); } entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 200, EventTextFormatter.DashSeparator); }); Assert.AreEqual(200, entries.Count()); StringAssert.Contains(entries.First(), "some error 0"); StringAssert.Contains(entries.Last(), "some error 199"); }
public void WhenMultipleEventsAreLogged() { var fileNameWithoutExtension = "CanLogMultipleMessages"; var fileName = fileNameWithoutExtension + ".log"; FlatFileHelper.DeleteCreatedLogFiles(fileNameWithoutExtension); var logger = MockEventSource.Logger; EventTextFormatter formatter = new EventTextFormatter("------======------"); TestScenario.With1Listener( logger, listener => { listener.LogToRollingFlatFile(fileName, 300000, "d", RollFileExistsBehavior.Increment, RollInterval.Year, formatter); listener.EnableEvents(logger, EventLevel.LogAlways); for (int n = 0; n < 300; n++) { logger.Informational("some message to flat file " + n.ToString()); } }); Assert.IsTrue(File.Exists(fileName)); var entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName, 300, formatter.Header); Assert.AreEqual<int>(300, entries.Count()); StringAssert.Contains(entries.First(), "some message to flat file 0"); StringAssert.Contains(entries.Last(), "some message to flat file 299"); }
public void WhenAllKeywordsAreEnabled() { var fileNameWithoutExtension = "RollingFlatFileEL_For_Keywords_All"; var fileName = fileNameWithoutExtension + ".log"; FlatFileHelper.DeleteCreatedLogFiles(fileNameWithoutExtension); var logger = MockEventSource.Logger; TestScenario.With1Listener( logger, listener => { var formatter = new EventTextFormatter("====", "=====", EventLevel.LogAlways); listener.LogToRollingFlatFile(fileName, 1, "yyyy", RollFileExistsBehavior.Increment, RollInterval.Day, formatter); listener.EnableEvents(logger, EventLevel.LogAlways, Keywords.All); logger.VerboseWithKeywordPage("VerboseWithKeywordPage"); logger.InfoWithKeywordDiagnostic("InfoWithKeywordDiagnostic"); Assert.IsTrue(File.Exists(fileNameWithoutExtension + ".log")); }); StringAssert.Contains(File.ReadAllText(fileNameWithoutExtension + ".log"), "Keywords : 1"); StringAssert.Contains(File.ReadAllText(fileNameWithoutExtension + ".log"), "Keywords : 4"); }