public void WithInstancePrefixWorksAsExpected() { // --- Arrange var configSettings = new AppConfigurationSettings( typeof(AppConfigProvider), null, null, "TestInstancePrefix", "TestInstanceName"); AppConfigurationManager.Configure(configSettings); WindowsEventLogger.LogSourceMapper = new DefaultLogSourceNameMapper(); var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log <WithStringNameAttribute>("Message"); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.ShouldEqual("Message"); lastentry.Source.ShouldEqual("TestInstancePrefix" + SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
public void LogAfterResetWorksAsExpected() { // --- Arrange if (!Directory.Exists(LOG_ROOT)) { Directory.CreateDirectory(LOG_ROOT); } File.Delete(Path.Combine(LOG_ROOT, LOG_FILE)); var tracer = new FileTraceLogger(LOG_FILE, LOG_ROOT, flushAfter: 1); var eventLog = new EventLog(SEEMPLEST_LOG2); WindowsEventLogger.RedirectLogTo(tracer); WindowsEventLogger.Log <WithStringNameAttribute>(); // --- Act WindowsEventLogger.Reset(); WindowsEventLogger.Log <WithStringNameAttribute>(); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.ShouldEqual("Default message"); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
public void LogWithRedirectionWorksAsExpected() { // --- Arrange if (!Directory.Exists(LOG_ROOT)) { Directory.CreateDirectory(LOG_ROOT); } File.Delete(Path.Combine(LOG_ROOT, LOG_FILE)); var tracer = new FileTraceLogger(LOG_FILE, LOG_ROOT, flushAfter: 1); var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.RedirectLogTo(tracer); WindowsEventLogger.Log <WithStringNameAttribute>(); // --- Assert EventLog.Exists(SEEMPLEST_LOG2).ShouldBeFalse(); eventLog.Dispose(); var text = File.ReadAllText(Path.Combine(LOG_ROOT, LOG_FILE)); var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); lines.ShouldHaveCountOf(1); var parts = lines[0].Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); parts[1].ShouldEqual("Informational"); parts[4].ShouldEqual("Windows Event Trace"); parts[5].ShouldEqual("Default message"); parts[6].ShouldEqual("EventId: 3, CategoryId: 5"); }
public void LogRedirectionConvertsTypesAsExpected() { // --- Arrange if (!Directory.Exists(LOG_ROOT)) { Directory.CreateDirectory(LOG_ROOT); } File.Delete(Path.Combine(LOG_ROOT, LOG_FILE)); var tracer = new FileTraceLogger(LOG_FILE, LOG_ROOT, flushAfter: 1); var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.RedirectLogTo(tracer); WindowsEventLogger.Log <SampleError>(); WindowsEventLogger.Log <SampleWarning>(); WindowsEventLogger.Log <SampleInformation>(); WindowsEventLogger.Log <SampleFailureAudit>(); WindowsEventLogger.Log <SampleSuccessAudit>(); // --- Assert EventLog.Exists(SEEMPLEST_LOG2).ShouldBeFalse(); eventLog.Dispose(); var text = File.ReadAllText(Path.Combine(LOG_ROOT, LOG_FILE)); var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); lines.ShouldHaveCountOf(5); var expectedCats = new[] { "Error", "Warning", "Informational", "Error", "Success" }; for (var i = 0; i < 5; i++) { var parts = lines[i].Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); parts[1].ShouldEqual(expectedCats[i]); } }
/// <summary> /// Starts the background task host /// </summary> public void Start() { if (HasStarted) { return; } HasStarted = true; PrepareInstances(); try { foreach (var processor in _processors) { foreach (var instance in processor.Instances) { instance.Name = processor.Name; instance.Start(); } } } catch (Exception ex) { WindowsEventLogger.Log <TaskProcessorHostFailed>( String.Format("Task processor host failed to start instances with the following error: {0}", ex)); } }
public void LogWithRedirectionWorksWithExceptionMessage() { // --- Arrange if (!Directory.Exists(LOG_ROOT)) { Directory.CreateDirectory(LOG_ROOT); } File.Delete(Path.Combine(LOG_ROOT, LOG_FILE)); var tracer = new FileTraceLogger(LOG_FILE, LOG_ROOT, flushAfter: 1); var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.RedirectLogTo(tracer); WindowsEventLogger.Log <SampleError>(new NullReferenceException()); // --- Assert EventLog.Exists(SEEMPLEST_LOG2).ShouldBeFalse(); eventLog.Dispose(); var text = File.ReadAllText(Path.Combine(LOG_ROOT, LOG_FILE)); var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); lines.ShouldHaveCountOf(3); var parts = lines[0].Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries); parts[1].ShouldEqual("Error"); }
public void WorksInParalell() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act Parallel.For(0, 40, num => WindowsEventLogger.Log <WithStringNameAttribute>(String.Format("Message{0}", num))); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(40); var messagelist = new List <string>(); foreach (EventLogEntry lastentry in after) { lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); messagelist.Add(lastentry.Message); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); } for (int i = 0; i < 40; i++) { messagelist.Contains(String.Format("Message{0}", i)).ShouldBeTrue( String.Format("Message{0} was not found", i)); } eventLog.Dispose(); }
public void ExceptionLoggingWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); const string TEST_EX = "This is a test exception"; const string TEST_INNER_EX = "This is an inner test exception"; // --- Act var innerEx = new InvalidOperationException(TEST_EX); var ex = new InvalidOperationException(TEST_INNER_EX, innerEx); WindowsEventLogger.Log <WithExceptionAttributes>("Message:", ex); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(0)"); lastentry.InstanceId.ShouldEqual(0); lastentry.Message.StartsWith("Message:").ShouldBeTrue(); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Error); eventLog.Dispose(); }
/// <summary> /// Starts processing tasks. /// </summary> public virtual void Start() { IsStopRequested = false; EnsurePerformanceCounters(); _executorTask = new Task(RunAsync); _executorTask.Start(); WindowsEventLogger.Log <TaskProcessorStarted>( String.Format("Task processor '{0}' has been started.", GetType())); }
public void EventLogNameBaseWithoutNameAttributeFails() { try { WindowsEventLogger.Log <WrongDefinition4>("message"); } catch (TargetInvocationException exception) { throw exception.InnerException.InnerException; } }
/// <summary> /// Processes tasks that are ready to run. /// </summary> protected override void ProcessTasks() { // --- Create the task, and dispose it when processed using (var newTask = new TTask()) { var success = true; var stopwatch = new Stopwatch(); try { stopwatch.Restart(); // --- Setup with graceful cancellation if (ShouldStopTaskProcessing) { return; } newTask.Setup(Context); // --- Run with graceful cancellation CancellationToken.ThrowIfCancellationRequested(); newTask.Run(); NumTasksPmc.Increment(); NumTasksPerSecondPmc.Increment(); } catch (OperationCanceledException ex) { // --- The message procession canceled, log this failure. WindowsEventLogger.Log <TaskExecutionInterrupted>( "Task execution interrupted while processing a scheduled task.", ex); success = false; } catch (Exception ex) { // --- The message procession failed, log this failure. WindowsEventLogger.Log <TaskExecutionFailed>( "Task execution failed while processing scheduled task.", ex); success = false; } finally { // --- Set up the next time when the task should run _nextTimeToRun = ScheduleInfo.NextTimeToRun(EnvironmentInfo.GetCurrentDateTimeUtc()); } stopwatch.Stop(); if (!success) { NumFailuresPmc.Increment(); NumFailuresPerSecondPmc.Increment(); } LastProcessTimePmc.RawValue = (int)stopwatch.ElapsedMilliseconds; } }
/// <summary> /// Processes tasks that are ready to run. /// </summary> protected override void ProcessTasks() { if (!DoNotPeekWhenCheckingTasks) { // --- We've just peeked the queue, however have not obtained messages. _messagesObtained = _requestQueue .GetMessages(MaxMessagesReadFromQueue, VisibilityTimeoutInSeconds); } // --- Messages are ready to be processed foreach (var message in _messagesObtained) { if (ShouldStopTaskProcessing) { return; } if (MaxDequeuCountBeforeDrop > 0 && message.DequeueCount > MaxDequeuCountBeforeDrop) { // --- Drop this message (probably poisoning message) _requestQueue.DeleteMessage(message); // --- The message procession failed, log this failure. WindowsEventLogger.Log <PoisoningMessageFound>( "Message with id {0} could not be successfully dequed and processed " + "after {1} attempts.\nQueue name: {2}\nMessage: {3}", message.Id, MaxDequeuCountBeforeDrop, _requestQueue.Name, message.MessageText); continue; } try { if (ProcessMessage(message)) { return; } } catch (OperationCanceledException ex) { // --- The message procession canceled, log this failure. WindowsEventLogger.Log <TaskExecutionInterrupted>( "Task execution interrupted while processing message {0}. Queue name: {1}. Abort message {2}", message.Id, _requestQueue.Name, ex.ToString()); } catch (Exception ex) { // --- The message procession failed, log this failure. WindowsEventLogger.Log <TaskExecutionFailed>( "Task execution failed while processing message {0}. Queue name: {1}. Error message {2}", message.Id, _requestQueue.Name, ex.ToString()); } } }
/// <summary> /// Stops the background task host /// </summary> public void Stop() { if (!HasStarted) { return; } HasStarted = false; try { foreach (var instance in _processors.SelectMany(processor => processor.Instances)) { instance.Stop(); } } catch (Exception ex) { WindowsEventLogger.Log <TaskProcessorHostFailed>( String.Format("Task processor host failed to stop instances with the following error: {0}", ex)); } }
public void LogWithExceptionWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log <WithStringNameAttribute>(new NullReferenceException()); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.StartsWith("An unexcepted exception").ShouldBeTrue(); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
public void LogWithDefaultMessageWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log <WithStringNameAttribute>(); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.ShouldEqual("Default message"); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
public void LogWithLongMessageWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log <WithStringNameAttribute>("Haho".PadRight(100000, '.')); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(5)"); lastentry.InstanceId.ShouldEqual(3); lastentry.Message.StartsWith("Haho...").ShouldBeTrue(); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Information); eventLog.Dispose(); }
public void OnlyWithRequiredAttributesWorksAsExpected() { // --- Arrange var eventLog = new EventLog(SEEMPLEST_LOG2); // --- Act WindowsEventLogger.Log <WithOnlyRequiredAttributes>("Message"); // --- Assert var after = eventLog.Entries; var afterCount = after.Count; afterCount.ShouldEqual(1); var lastentry = after[after.Count - 1]; lastentry.Category.ShouldEqual("(0)"); lastentry.InstanceId.ShouldEqual(0); lastentry.Message.ShouldEqual("Message"); lastentry.Source.ShouldEqual(SEEMPLEST_SOURCE); lastentry.EntryType.ShouldEqual(EventLogEntryType.Warning); eventLog.Dispose(); }
/// <summary> /// Stops processing any new task and requests cancelling tasks already /// under progress. /// </summary> public virtual void Stop() { if (_executorTask == null) { return; } IsStopRequested = true; Context.CancellationTokenSource.Cancel(); var stoppedInTime = _executorTask.Wait(StopTimeout); if (!stoppedInTime) { WindowsEventLogger.Log <TaskProcessorStoppedWithTimeout>( String.Format("Task processor '{0}' has been stopped, but did not " + "stop within timeout.", GetType())); } else { WindowsEventLogger.Log <TaskProcessorStopped>( String.Format("Task processor '{0}' has been stopped.", GetType())); _executorTask.Dispose(); _executorTask = null; } }
/// <summary> /// Prepares all task processor instances to run /// </summary> private void PrepareInstances() { _processors.Clear(); try { var instancesCreated = 0; var defaultContext = new DefaultTaskExecutionContext(Configuration.DefaultContext); foreach (var taskProcessor in Configuration.GetTaskProcessors()) { var processorType = GetProcessorType(taskProcessor); var instancesToCreate = taskProcessor.InstanceCount; if (instancesCreated + instancesToCreate > MAX_INSTANCES) { instancesToCreate = MAX_INSTANCES - instancesCreated; if (instancesToCreate < 0) { instancesToCreate = 0; } string message; if (instancesToCreate == 0) { message = String.Format( "No instances has been created for '{0}' task processor, because " + "otherwise the maximum amount of {1}' instances would be exceeded.", taskProcessor.Name, MaxInstances); } else { message = String.Format( "Only {0} instances has been created for '{1}' task processor, because " + "otherwise the maximum amount of {2}' instances would be exceeded.", instancesToCreate, taskProcessor.Name, MaxInstances); } WindowsEventLogger.Log <TaskProcessorHostWarning>(message); } var processorInfo = new TaskProcessorInstances(taskProcessor.Name); _processors.Add(processorInfo); for (var i = 0; i < instancesToCreate; i++) { // --- Create the processor instance and set its properties var instance = (ITaskProcessor)ConfigurationHelper .PrepareInstance(processorType, taskProcessor.Properties); var context = taskProcessor.Context == null ? defaultContext : new DefaultTaskExecutionContext(taskProcessor.Context); instance.SetContext(context); processorInfo.Instances.Add(instance); // --- Set the peek policy var queuedInstance = instance as IQueuedTaskProcessor; if (queuedInstance != null && taskProcessor.PeekPolicyType != null) { queuedInstance.PeekPolicy = Activator.CreateInstance(taskProcessor.PeekPolicyType) as IQueuePeekPolicy; if (queuedInstance.PeekPolicy != null) { queuedInstance.PeekPolicy.SetTaskExecutionContext(context); } } instancesCreated++; } } } catch (Exception ex) { WindowsEventLogger.Log <TaskProcessorHostFailed>( String.Format("Task processor host failed to prepare instances with the following error: {0}", ex)); } }