public void GetWrongUserReplacesException() { using (var subscription = obsListener.LogToSqlDatabase("test", TracingDatabaseConnectionString, bufferingCount: 1)) { string username = "******"; var roles = new[] { "Employee" }; Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), roles); var repository = new UserRepository(ldapStore, exceptionMgr, container); //assert that the friendly excetpion is thrown to the UI var ex = ExceptionAssertHelper.Throws <NotifyException>(() => repository.GetUser(username)); subscription.Sink.FlushAsync().Wait(); var entries = DatabaseHelper.GetAllLogEntries(TracingDatabaseConnectionString); Assert.AreEqual(2, entries.Count); Assert.IsTrue(entries.Any(e => e.Level == (int)EventLevel.Error)); Assert.IsTrue(entries.Any(e => e.EventId == 1000)); Assert.IsTrue(entries.Any(e => e.Payload.Contains(Resources.UserNotRegisteredMessage))); Assert.IsNotNull(ex, "Exception not thrown"); StringAssert.Contains(ex.Message, Resources.FriendlyMessage); } }
/// <summary> /// Subscribes to the listener using a <see cref="BlueprintSqlDatabaseSink" />. /// </summary> /// <param name="instanceName">The name of the instance originating the entries.</param> /// <param name="connectionString">The connection string.</param> /// <param name="tableName">The name of the table.</param> /// <param name="storedProcedureName">The name of the stored procedure that writes to the table.</param> /// <param name="bufferingInterval">The buffering interval between each batch publishing.</param> /// <param name="bufferingCount">The number of entries that will trigger a batch publishing.</param> /// <param name="listenerDisposeTimeout">Defines a timeout interval for the flush operation when the listener is disposed. /// This means that if the timeout period elapses, some event entries will be dropped and not sent to the store. Calling <see cref="IDisposable.Dispose"/> on /// the <see cref="EventListener"/> will block until all the entries are flushed or the interval elapses. /// If <see langword="null"/> is specified, then the call will block indefinitely until the flush operation finishes.</param> /// <param name="maxBufferSize">The maximum number of entries that can be buffered while it's sending to SQL Database before the sink starts dropping entries. /// This means that if the timeout period elapses, some event entries will be dropped and not sent to the store. Normally, calling <see cref="IDisposable.Dispose" /> on /// the <see cref="System.Diagnostics.Tracing.EventListener" /> will block until all the entries are flushed or the interval elapses. /// If <see langword="null" /> is specified, then the call will block indefinitely until the flush operation finishes.</param> /// <returns>An event listener that uses <see cref="BlueprintSqlDatabaseSink"/> to log events.</returns> public static EventListener CreateListener(string instanceName, string connectionString, string tableName = DefaultTableName, string storedProcedureName = DefaultStoredProcedureName, TimeSpan?bufferingInterval = null, int bufferingCount = Buffering.DefaultBufferingCount, TimeSpan?listenerDisposeTimeout = null, int maxBufferSize = Buffering.DefaultMaxBufferSize) { var listener = new ObservableEventListener(); listener.LogToSqlDatabase(instanceName, connectionString, tableName, storedProcedureName, bufferingInterval, bufferingCount, listenerDisposeTimeout, maxBufferSize); return(listener); }
static void MultipleEventListenersKeywords() { var listener1 = new ObservableEventListener(); var listener2 = new ObservableEventListener(); listener1.EnableEvents(MyCompanyEventSource.Log, EventLevel.LogAlways, MyCompanyEventSource.Keywords.Perf | MyCompanyEventSource.Keywords.Diagnostic); listener2.EnableEvents(MyCompanyEventSource.Log, EventLevel.LogAlways, Keywords.All); // Set up and enable the event listeners - typically done when the application starts listener1.LogToConsole(); // The SinkSubscription is used later to flush the buffer var subscription = listener2.LogToSqlDatabase("Demo Semantic Logging Instance", connectionString); // Log some messages MyCompanyEventSource.Log.PageStart(23, "http://mysite/demopage"); MyCompanyEventSource.Log.Startup(); MyCompanyEventSource.Log.Failure("Couldn't connect to server."); Console.WriteLine("Written three log messages.\nUsing a basic console listener and a SQL listener to capture them."); Console.WriteLine("Only the messages with the Perf or Diagnostic keywords appears in the console, \nall three appear in the SQL Database:\n"); // Disable the event listener - typically done when the application terminates listener1.DisableEvents(MyCompanyEventSource.Log); listener2.DisableEvents(MyCompanyEventSource.Log); // Manually flush the buffer so you can see what's in the database subscription.Sink.FlushAsync().Wait(); ShowContentsOfSqlDatabaseTable(); listener1.Dispose(); listener2.Dispose(); }
public static void InitializeLogger(string instanceName, System.Diagnostics.Tracing.EventLevel logEventLevel, string connectionString, string applicationName = "NA") { var logListener1 = new ObservableEventListener(); logListener1.EnableEvents(AppEventSourceManager.Log, logEventLevel, EventKeywords.None); logListener1.LogToSqlDatabase(instanceName, connectionString, "Traces", Buffering.DefaultBufferingInterval, 1, Timeout.InfiniteTimeSpan, 500); AppEventSourceManager.Log.Info(string.Format("Logger Initialized - Event Source : {0}, Log Level : {1}", instanceName, logEventLevel.ToString()), applicationName); }
public void GetAllExpensesLogsActivity() { using (var subscription = obsListener.LogToSqlDatabase("Activity", TracingDatabaseConnectionString)) { var repository = new ExpenseRepository(TestDatabaseConnectionString, TimeSpan.MinValue); repository.GetAllExpenses(); subscription.Sink.FlushAsync().Wait(); var logEntries = DatabaseHelper.GetAllLogEntries(TracingDatabaseConnectionString); Assert.AreEqual(3, logEntries.Count()); var GetAllExpensesStartedEntry = logEntries.SingleOrDefault(e => e.EventId == 300); Assert.IsNotNull(GetAllExpensesStartedEntry); var GetAllExpensesFinishedEntry = logEntries.SingleOrDefault(e => e.EventId == 301); Assert.IsNotNull(GetAllExpensesFinishedEntry); } }
public void WhenMultipleCustomSinksSubscribing() { string fileName1 = "mockFlatFileMutiple.log"; File.Delete(fileName1); string fileName2 = "flatFileMultiple.log"; File.Delete(fileName2); var validConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["valid"].ConnectionString; DatabaseHelper.CleanLoggingDB(validConnectionString); var logger = MockEventSource.Logger; string message = string.Concat("Message ", Guid.NewGuid()); string message2 = string.Concat("Message2 ", Guid.NewGuid()); IEnumerable <string> entries = null; IEnumerable <string> entries2 = null; using (var eventListener = new ObservableEventListener()) { try { eventListener.LogToMockFlatFile(fileName1, "==-=="); eventListener.LogToFlatFile(fileName2, new EventTextFormatter("--==--")); eventListener.LogToSqlDatabase("testInstance", validConnectionString, "Traces", TimeSpan.Zero, 1); eventListener.LogToCustomSqlDatabase("testCustom", validConnectionString); eventListener.EnableEvents(logger, System.Diagnostics.Tracing.EventLevel.LogAlways, Keywords.All); logger.LogSomeMessage(message); logger.LogSomeMessage(message2); entries = FlatFileHelper.PollUntilTextEventsAreWritten(fileName1, 2, "==-=="); entries2 = FlatFileHelper.PollUntilTextEventsAreWritten(fileName2, 2, "--==--"); } finally { eventListener.DisableEvents(logger); } } Assert.IsTrue(File.Exists(fileName1)); Assert.AreEqual <int>(2, entries.Count()); StringAssert.Contains(entries.First().ToString(), message); StringAssert.Contains(entries.Last().ToString(), message2); Assert.IsTrue(File.Exists(fileName2)); Assert.AreEqual <int>(2, entries.Count()); StringAssert.Contains(entries.First().ToString(), message); StringAssert.Contains(entries.Last().ToString(), message2); var dt = DatabaseHelper.GetLoggedTable(validConnectionString); Assert.AreEqual(4, dt.Rows.Count); }
public static void InitializeLogger(string instanceName, System.Diagnostics.Tracing.EventLevel logEventLevel, string applicationName = "NA") { var logListener1 = new ObservableEventListener(); logListener1.EnableEvents(AppEventSourceManager.Log, logEventLevel, EventKeywords.None); logListener1.LogToSqlDatabase(instanceName, ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString, "Traces", Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Utility.Buffering.DefaultBufferingInterval, 1, Timeout.InfiniteTimeSpan, 500); //var logListener2 = new ObservableEventListener(); //logListener2.EnableEvents(IoTEventSourceManager.Log, logEventLevel, EventKeywords.None); //logListener2.LogToFlatFile("semanticLogs.json", new JsonEventTextFormatter(EventTextFormatting.Indented), true); AppEventSourceManager.Log.Info(string.Format("Logger Initialized - Event Source : {0}, Log Level : {1}", instanceName, logEventLevel.ToString()), applicationName); }
/// <summary> /// Subscribes to the listener using a <see cref="SqlDatabaseSink" />. /// </summary> /// <param name="instanceName">The name of the instance originating the entries.</param> /// <param name="connectionString">The connection string.</param> /// <param name="tableName">The name of the table.</param> /// <param name="bufferingInterval">The buffering interval between each batch publishing.</param> /// <param name="bufferingCount">The number of entries that will trigger a batch publishing.</param> /// <param name="listenerDisposeTimeout">Defines a timeout interval for the flush operation when the listener is disposed. /// This means that if the timeout period elapses, some event entries will be dropped and not sent to the store. Calling <see cref="IDisposable.Dispose"/> on /// the <see cref="EventListener"/> will block until all the entries are flushed or the interval elapses. /// If <see langword="null"/> is specified, then the call will block indefinitely until the flush operation finishes.</param> /// <param name="maxBufferSize">The maximum number of entries that can be buffered while it's sending to Windows Azure Storage before the sink starts dropping entries. /// This means that if the timeout period elapses, some event entries will be dropped and not sent to the store. Normally, calling <see cref="IDisposable.Dispose" /> on /// the <see cref="System.Diagnostics.Tracing.EventListener" /> will block until all the entries are flushed or the interval elapses. /// If <see langword="null" /> is specified, then the call will block indefinitely until the flush operation finishes.</param> /// <returns>An event listener that uses <see cref="SqlDatabaseSink"/> to log events.</returns> public static EventListener CreateListener(string instanceName, string connectionString, string tableName = DefaultTableName, TimeSpan? bufferingInterval = null, int bufferingCount = Buffering.DefaultBufferingCount, TimeSpan? listenerDisposeTimeout = null, int maxBufferSize = Buffering.DefaultMaxBufferSize) { var listener = new ObservableEventListener(); listener.LogToSqlDatabase(instanceName, connectionString, tableName, bufferingInterval, bufferingCount, listenerDisposeTimeout, maxBufferSize); return listener; }