/// <summary> /// Override to specify how the trace entry should be logged. /// </summary> /// <param name="item">Trace entry</param> protected override void DoLog(TraceLogItem item) { using (var db = new SqlDatabase(_sqlConnectionOrName)) { var logRecord = new TraceRecord { // ReSharper disable PossibleInvalidOperationException Timestamp = item.TimestampUtc.Value, // ReSharper restore PossibleInvalidOperationException Type = (int)item.Type, OperationType = item.OperationType, SessionId = item.SessionId, BusinessTransactionId = item.BusinessTransactionId, OperationInstanceId = item.OperationInstanceId, TenantId = item.TenantId, Message = item.Message, DetailedMessage = item.DetailedMessage, ServerName = item.ServerName, // ReSharper disable PossibleInvalidOperationException ThreadId = item.ThreadId.Value // ReSharper restore PossibleInvalidOperationException }; db.Insert(logRecord); } }
public void ExecuteBindingAsync_Traces_And_Invokes_Inner() { // Arrange Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true }; mockParamDescriptor.Setup(d => d.ParameterName).Returns("paramName"); mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string)); Mock<HttpParameterBinding> mockBinding = new Mock<HttpParameterBinding>(mockParamDescriptor.Object) { CallBase = true }; bool innerInvoked = false; mockBinding.Setup( b => b.ExecuteBindingAsync(It.IsAny<ModelMetadataProvider>(), It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())).Returns(TaskHelpers.Completed()).Callback(() => innerInvoked = true); TestTraceWriter traceWriter = new TestTraceWriter(); HttpParameterBindingTracer tracer = new HttpParameterBindingTracer(mockBinding.Object, traceWriter); HttpActionContext actionContext = ContextUtil.CreateActionContext(); ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider(); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteBindingAsync" }, new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ExecuteBindingAsync" } }; // Act Task task = tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None); task.Wait(); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.True(innerInvoked); }
public void ExecuteExceptionFilterAsync_Faults_And_Traces_When_Inner_Faults() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage response = new HttpResponseMessage(); Mock<IExceptionFilter> mockFilter = new Mock<IExceptionFilter>() { CallBase = true }; InvalidOperationException exception = new InvalidOperationException("test"); TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(null); tcs.TrySetException(exception); mockFilter.Setup(a => a.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(), It.IsAny<CancellationToken>())).Returns(tcs.Task); HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response); TestTraceWriter traceWriter = new TestTraceWriter(); ExceptionFilterTracer tracer = new ExceptionFilterTracer(mockFilter.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteExceptionFilterAsync" }, new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ExecuteExceptionFilterAsync" } }; // Act Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None); // Assert Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void ExecuteAsync_Invokes_Inner_And_Traces() { // Arrange HttpResponseMessage response = new HttpResponseMessage(); Mock<ApiController> mockController = new Mock<ApiController>() { CallBase = true }; mockController.Setup(b => b.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<CancellationToken>())).Returns(TaskHelpers.FromResult<HttpResponseMessage>(response)); HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage()); controllerContext.ControllerDescriptor = _controllerDescriptor; controllerContext.Controller = mockController.Object; HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object); TestTraceWriter traceWriter = new TestTraceWriter(); HttpControllerTracer tracer = new HttpControllerTracer(mockController.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.End } }; // Act HttpResponseMessage actualResponse = ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None).Result; // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(response, actualResponse); }
public void ExecuteExceptionFilterAsync_Traces() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage response = new HttpResponseMessage(); Mock<IExceptionFilter> mockFilter = new Mock<IExceptionFilter>() { CallBase = true }; mockFilter.Setup( f => f.ExecuteExceptionFilterAsync(It.IsAny<HttpActionExecutedContext>(), It.IsAny<CancellationToken>())). Returns(TaskHelpers.Completed()); HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response); TestTraceWriter traceWriter = new TestTraceWriter(); ExceptionFilterTracer tracer = new ExceptionFilterTracer(mockFilter.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteExceptionFilterAsync" }, new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ExecuteExceptionFilterAsync" }, }; // Act Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None); task.Wait(); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void SendAsync_Traces_And_Throws_When_Inner_Throws() { // Arrange InvalidOperationException exception = new InvalidOperationException("test"); MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) => { throw exception; }); TestTraceWriter traceWriter = new TestTraceWriter(); MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter); // DelegatingHandlers require an InnerHandler to run. We create a mock one to simulate what // would happen when a DelegatingHandler executing after the tracer throws. MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => { throw exception; }); tracer.InnerHandler = mockInnerHandler; HttpRequestMessage request = new HttpRequestMessage(); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "SendAsync" }, new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "SendAsync" } }; MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); // Act Exception thrown = Assert.Throws<TargetInvocationException>( () => method.Invoke(tracer, new object[] { request, CancellationToken.None })); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown.InnerException); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public void ExecuteBindingAsync_Traces_And_Invokes_Inner_ReadAsync() { // Arrange Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true }; mockParamDescriptor.Setup(d => d.ParameterName).Returns("paramName"); mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof (string)); FormatterParameterBinding binding = new FormatterParameterBinding(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null); TestTraceWriter traceWriter = new TestTraceWriter(); FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(binding, traceWriter); HttpActionContext actionContext = ContextUtil.CreateActionContext(); actionContext.Request.Content = new StringContent("true"); actionContext.Request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider(); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteBindingAsync" }, new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ExecuteBindingAsync" } }; // Act Task task = tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None); task.Wait(); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Equal("True", actionContext.ActionArguments["paramName"]); }
public void ExecuteAsync_Faults_And_Traces_When_Inner_Faults() { // Arrange InvalidOperationException exception = new InvalidOperationException(); TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.TrySetException(exception); Mock<ApiController> mockController = new Mock<ApiController>() { CallBase = true }; mockController.Setup(b => b.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<CancellationToken>())).Returns(tcs.Task); HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage()); controllerContext.ControllerDescriptor = _controllerDescriptor; controllerContext.Controller = mockController.Object; HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object); TestTraceWriter traceWriter = new TestTraceWriter(); HttpControllerTracer tracer = new HttpControllerTracer(mockController.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End } }; // Act Exception thrown = Assert.Throws<InvalidOperationException>(() => ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None).Wait()); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public void OnReadFromStreamAsync_Traces() { // Arrange Mock<MediaTypeFormatter> mockFormatter = new Mock<MediaTypeFormatter>() { CallBase = true }; mockFormatter.Setup( f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContentHeaders>(), It.IsAny<IFormatterLogger>())). Returns(TaskHelpers.FromResult<object>("sampleValue")); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ReadFromStreamAsync" } }; // Act Task<object> task = tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content.Headers, null); string result = task.Result as string; // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Equal("sampleValue", result); }
public void ExecuteBindingAsync_Traces_And_Throws_When_Inner_Throws() { // Arrange Mock<HttpParameterDescriptor> mockParamDescriptor = new Mock<HttpParameterDescriptor>() { CallBase = true }; mockParamDescriptor.Setup(d => d.ParameterName).Returns("paramName"); mockParamDescriptor.Setup(d => d.ParameterType).Returns(typeof(string)); Mock<FormatterParameterBinding> mockBinding = new Mock<FormatterParameterBinding>(mockParamDescriptor.Object, new MediaTypeFormatterCollection(), null) { CallBase = true }; InvalidOperationException exception = new InvalidOperationException("test"); mockBinding.Setup( b => b.ExecuteBindingAsync(It.IsAny<ModelMetadataProvider>(), It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())).Throws(exception); TestTraceWriter traceWriter = new TestTraceWriter(); FormatterParameterBindingTracer tracer = new FormatterParameterBindingTracer(mockBinding.Object, traceWriter); HttpActionContext actionContext = ContextUtil.CreateActionContext(); ModelMetadataProvider metadataProvider = new EmptyModelMetadataProvider(); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteBindingAsync" }, new TraceRecord(actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ExecuteBindingAsync" } }; // Act & Assert Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.ExecuteBindingAsync(metadataProvider, actionContext, CancellationToken.None)); // Assert Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void OnReadFromStreamAsync_Traces_And_Throws_When_Inner_Throws() { // Arrange InvalidOperationException exception = new InvalidOperationException("test"); Mock<MediaTypeFormatter> mockFormatter = new Mock<MediaTypeFormatter>() { CallBase = true }; mockFormatter.Setup( f => f.ReadFromStreamAsync(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContentHeaders>(), It.IsAny<IFormatterLogger>())).Throws(exception); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); MediaTypeFormatterTracer tracer = new MediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStreamAsync" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ReadFromStreamAsync" } }; // Act Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.ReadFromStreamAsync(typeof(string), new MemoryStream(), request.Content.Headers, null)); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public void ExecuteAuthorizationFilterAsync_Faults_And_Traces_When_Inner_Faults() { // Arrange Mock<IAuthorizationFilter> mockAttr = new Mock<IAuthorizationFilter>() { CallBase = true }; HttpResponseMessage response = new HttpResponseMessage(); InvalidOperationException exception = new InvalidOperationException("test"); TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(response); tcs.TrySetException(exception); mockAttr.Setup(a => a.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(tcs.Task); Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0])); HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object); Func<Task<HttpResponseMessage>> continuation = () => TaskHelpers.FromResult<HttpResponseMessage>(response); TestTraceWriter traceWriter = new TestTraceWriter(); AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockAttr.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteAuthorizationFilterAsync" }, new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ExecuteAuthorizationFilterAsync" } }; // Act & Assert Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation); Exception thrown = Assert.Throws<InvalidOperationException>(() => task.Wait()); // Assert Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void ExecuteAuthorizationFilterAsync_Traces() { // Arrange HttpResponseMessage response = new HttpResponseMessage(); Mock<IAuthorizationFilter> mockFilter = new Mock<IAuthorizationFilter>() { CallBase = true }; mockFilter.Setup(f => f.ExecuteAuthorizationFilterAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>(), It.IsAny<Func<Task<HttpResponseMessage>>>())).Returns(TaskHelpers.FromResult(response)); Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0])); HttpActionContext actionContext = ContextUtil.CreateActionContext(actionDescriptor: mockActionDescriptor.Object); Func<Task<HttpResponseMessage>> continuation = () => TaskHelpers.FromResult<HttpResponseMessage>(new HttpResponseMessage()); TestTraceWriter traceWriter = new TestTraceWriter(); AuthorizationFilterTracer tracer = new AuthorizationFilterTracer(mockFilter.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteAuthorizationFilterAsync" }, new TraceRecord(actionContext.Request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ExecuteAuthorizationFilterAsync" }, }; // Act Task task = ((IAuthorizationFilter)tracer).ExecuteAuthorizationFilterAsync(actionContext, CancellationToken.None, continuation); task.Wait(); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void ExecuteExceptionFilterAsync_Traces() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage response = new HttpResponseMessage(); Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true }; Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0])); HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response); TestTraceWriter traceWriter = new TestTraceWriter(); ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" }, new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "OnException" }, }; // Act Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None); task.Wait(); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage response = new HttpResponseMessage(); Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true }; InvalidOperationException exception = new InvalidOperationException("test"); mockAttr.Setup(a => a.OnException(It.IsAny<HttpActionExecutedContext>())).Throws(exception); Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0])); HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response); TestTraceWriter traceWriter = new TestTraceWriter(); ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" }, new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "OnException" } }; // Act Exception thrown = Assert.Throws<InvalidOperationException>( () => ((IExceptionFilter) tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None)); // Assert Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void BindValuesAsync_Invokes_Inner_And_Traces() { // Arrange bool wasInvoked = false; Mock<HttpActionBinding> mockBinder = new Mock<HttpActionBinding>() { CallBase = true }; mockBinder.Setup(b => b.ExecuteBindingAsync( It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>())). Callback(() => wasInvoked = true).Returns(TaskHelpers.Completed()); TestTraceWriter traceWriter = new TestTraceWriter(); HttpActionBindingTracer tracer = new HttpActionBindingTracer(mockBinder.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_actionContext.Request, TraceCategories.ModelBindingCategory, TraceLevel.Info) { Kind = TraceKind.End } }; // Act tracer.ExecuteBindingAsync(_actionContext, CancellationToken.None).Wait(); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.True(wasInvoked); }
public void SendAsync_Traces_And_Invokes_Inner() { // Arrange HttpResponseMessage response = new HttpResponseMessage(); MockDelegatingHandler mockHandler = new MockDelegatingHandler((rqst, cancellation) => TaskHelpers.FromResult<HttpResponseMessage>(response)); TestTraceWriter traceWriter = new TestTraceWriter(); MessageHandlerTracer tracer = new MessageHandlerTracer(mockHandler, traceWriter); MockHttpMessageHandler mockInnerHandler = new MockHttpMessageHandler((rqst, cancellation) => TaskHelpers.FromResult<HttpResponseMessage>(response)); tracer.InnerHandler = mockInnerHandler; HttpRequestMessage request = new HttpRequestMessage(); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "SendAsync" }, new TraceRecord(request, TraceCategories.MessageHandlersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "SendAsync" } }; MethodInfo method = typeof(DelegatingHandler).GetMethod("SendAsync", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); // Act Task<HttpResponseMessage> task = method.Invoke(tracer, new object[] { request, CancellationToken.None }) as Task<HttpResponseMessage>; HttpResponseMessage actualResponse = task.Result; // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(response, actualResponse); }
public void Create_Throws_And_Traces_When_Inner_Throws() { // Arrange Mock<ApiController> mockController = new Mock<ApiController>(); Mock<IHttpControllerActivator> mockActivator = new Mock<IHttpControllerActivator>() { CallBase = true }; InvalidOperationException exception = new InvalidOperationException("test"); mockActivator.Setup(b => b.Create(It.IsAny<HttpRequestMessage>(), It.IsAny<HttpControllerDescriptor>(), It.IsAny<Type>())).Throws(exception); HttpRequestMessage request = new HttpRequestMessage(); TestTraceWriter traceWriter = new TestTraceWriter(); HttpControllerActivatorTracer tracer = new HttpControllerActivatorTracer(mockActivator.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "Create" }, new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "Create" } }; // Act & Assert Exception thrown = Assert.Throws<InvalidOperationException>(() => ((IHttpControllerActivator)tracer).Create(request, controllerDescriptor: null, controllerType: mockController.Object.GetType())); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public void InvokeActionAsync_Traces_Begin_And_End_Info() { // Arrange TestTraceWriter traceWriter = new TestTraceWriter(); HttpActionInvokerTracer tracer = new HttpActionInvokerTracer(new ApiControllerActionInvoker(), traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.End } }; // Act Task task = ((IHttpActionInvoker)tracer).InvokeActionAsync(_actionContext, CancellationToken.None); task.Wait(); // Assert Assert.Equal(2, traceWriter.Traces.Count); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
public void CreateController_Invokes_Inner_And_Traces() { // Arrange Mock<HttpControllerDescriptor> mockControllerDescriptor = CreateMockControllerDescriptor(); mockControllerDescriptor.Setup(b => b.CreateController(It.IsAny<HttpRequestMessage>())).Returns(_controller); TestTraceWriter traceWriter = new TestTraceWriter(); HttpControllerDescriptorTracer tracer = GetHttpControllerDescriptorTracer(mockControllerDescriptor.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "CreateController" }, new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "CreateController" } }; // Act IHttpController controller = tracer.CreateController(_request); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.IsAssignableFrom<HttpControllerTracer>(controller); }
public void SelectAction_Traces_And_Returns_ActionDescriptor_Tracer() { // Arrange TestTraceWriter traceWriter = new TestTraceWriter(); Mock<IHttpActionSelector> mockSelector = new Mock<IHttpActionSelector>(); mockSelector.Setup(s => s.SelectAction(_controllerContext)).Returns(_mockActionDescriptor.Object); HttpActionSelectorTracer tracer = new HttpActionSelectorTracer(mockSelector.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.End } }; // Act HttpActionDescriptor selectedActionDescriptor = ((IHttpActionSelector)tracer).SelectAction(_controllerContext); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.IsAssignableFrom<HttpActionDescriptorTracer>(selectedActionDescriptor); }
public void SelectController_Invokes_Inner_And_Traces() { // Arrange Mock<HttpControllerDescriptor> mockControllerDescriptor = new Mock<HttpControllerDescriptor>(_controllerContext.Configuration, "AnyController", _controller.GetType()); Mock<IHttpControllerSelector> mockSelector = new Mock<IHttpControllerSelector>(); mockSelector.Setup(b => b.SelectController(It.IsAny<HttpRequestMessage>())).Returns(mockControllerDescriptor.Object); TestTraceWriter traceWriter = new TestTraceWriter(); HttpControllerSelectorTracer tracer = new HttpControllerSelectorTracer(mockSelector.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "SelectController" }, new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "SelectController" } }; // Act HttpControllerDescriptor controllerDescriptor = ((IHttpControllerSelector)tracer).SelectController(_request); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.IsAssignableFrom<HttpControllerDescriptorTracer>(controllerDescriptor); }
public void CreateController_Throws_And_Traces_When_Inner_Throws() { // Arrange Mock<HttpControllerDescriptor> mockControllerDescriptor = CreateMockControllerDescriptor(); mockControllerDescriptor.Setup(b => b.CreateController(It.IsAny<HttpRequestMessage>())).Throws(_exception); TestTraceWriter traceWriter = new TestTraceWriter(); HttpControllerDescriptorTracer tracer = GetHttpControllerDescriptorTracer(mockControllerDescriptor.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "CreateController" }, new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "CreateController" } }; // Act Exception thrown = Assert.Throws<InvalidOperationException>(() => tracer.CreateController(_request)); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(_exception, thrown); Assert.Same(_exception, traceWriter.Traces[1].Exception); }
public void SelectAction_Traces_And_Throws_Exception_Thrown_From_Inner() { // Arrange TestTraceWriter traceWriter = new TestTraceWriter(); Mock<IHttpActionSelector> mockSelector = new Mock<IHttpActionSelector>(); InvalidOperationException exception = new InvalidOperationException(); mockSelector.Setup(s => s.SelectAction(_controllerContext)).Throws(exception); HttpActionSelectorTracer tracer = new HttpActionSelectorTracer(mockSelector.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Error) { Kind = TraceKind.End } }; // Act Exception thrown = Assert.Throws<InvalidOperationException>(() => ((IHttpActionSelector)tracer).SelectAction(_controllerContext)); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public void ReadFromStream_Traces() { // Arrange Mock<BufferedMediaTypeFormatter> mockFormatter = new Mock<BufferedMediaTypeFormatter>() { CallBase = true }; mockFormatter.Setup(f => f.ReadFromStream(It.IsAny<Type>(), It.IsAny<Stream>(), It.IsAny<HttpContent>(), It.IsAny<IFormatterLogger>())) .Returns("sampleValue"); TestTraceWriter traceWriter = new TestTraceWriter(); HttpRequestMessage request = new HttpRequestMessage(); request.Content = new StringContent(""); BufferedMediaTypeFormatterTracer tracer = new BufferedMediaTypeFormatterTracer(mockFormatter.Object, traceWriter, request); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ReadFromStream" }, new TraceRecord(request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "ReadFromStream" } }; // Act string valueReturned = tracer.ReadFromStream(typeof(string), new MemoryStream(), request.Content, null) as string; // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Equal("sampleValue", valueReturned); }
public void Create_Invokes_Inner_And_Traces() { // Arrange Mock<ApiController> mockController = new Mock<ApiController>(); Mock<IHttpControllerActivator> mockActivator = new Mock<IHttpControllerActivator>() { CallBase = true }; mockActivator.Setup(b => b.Create(It.IsAny<HttpRequestMessage>(), It.IsAny<HttpControllerDescriptor>(), It.IsAny<Type>())).Returns(mockController.Object); HttpRequestMessage request = new HttpRequestMessage(); TestTraceWriter traceWriter = new TestTraceWriter(); HttpControllerActivatorTracer tracer = new HttpControllerActivatorTracer(mockActivator.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "Create" }, new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "Create" } }; // Act IHttpController createdController = ((IHttpControllerActivator)tracer).Create(request, controllerDescriptor: null, controllerType: mockController.Object.GetType()); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.IsAssignableFrom<HttpControllerTracer>(createdController); }
private void WriteRecord(RecordType type, TraceRecord record) { }
public void ExecuteAsync_Traces() { // Arrange Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); mockActionDescriptor.Setup(a => a.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>(), CancellationToken.None)) .Returns(TaskHelpers.FromResult<object>(null)); HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(); controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(ApiController)); IDictionary<string, object> arguments = new Dictionary<string, object>(); TestTraceWriter traceWriter = new TestTraceWriter(); HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteAsync" }, new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.End } }; // Act var result = tracer.ExecuteAsync(controllerContext, arguments, CancellationToken.None); // Assert result.WaitUntilCompleted(); Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); }
internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception) { if (DiagnosticUtility.ShouldTrace(severity)) { Guid activityId = System.Runtime.Diagnostics.DiagnosticTrace.ActivityId; string msdnTraceCode = System.ServiceModel.Diagnostics.DiagnosticTrace.GenerateMsdnTraceCode("System.IdentityModel", traceCodes[traceCode]); DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, msdnTraceCode, traceDescription, extendedData, exception, activityId, source); } }
/// <summary> /// Logs the trace. /// </summary> /// <param name="record">The trace record.</param> public virtual void LogTrace(TraceRecord record) { var method = record.Request != null ? record.Request.Method.Method : string.Empty; var uri = record.Request != null ? record.Request.RequestUri.AbsoluteUri : string.Empty; var message = string.Format("[{0}] {1}: {2} {3} {4}", record.Category, record.Kind, method, uri, string.IsNullOrEmpty(record.Message) ? string.Empty : " - " + record.Message); switch (record.Level) { case TraceLevel.Info: this._logger.Info(message); break; case TraceLevel.Debug: this._logger.Debug(message); break; case TraceLevel.Warn: this._logger.Warn(message); break; case TraceLevel.Error: this._logger.Error(message); break; case TraceLevel.Fatal: this._logger.Fatal(message); break; } // Add exception message if present if (record.Exception != null) { this._logger.Error(string.Format("{0}: {1}", record.Exception.Message, record.Exception.StackTrace)); if (record.Exception.InnerException != null) { this._logger.Error(string.Format("{0}: {1}", record.Exception.InnerException.Message, record.Exception.InnerException.StackTrace)); } } // Write to system.diagnostics as well System.Diagnostics.Trace.WriteLine(message, record.Category); // Calculate performance if (record.Kind == TraceKind.End) { var begin = this.beginTraces.ToList().FirstOrDefault(r => (record.RequestId == r.RequestId && record.Category == r.Category && record.Operation == r.Operation && record.Operator == r.Operator)); if (begin != null) { // Log performance this._logger.Info(string.Format("[{0}] {1}: {2} {3} - Request processing time: {4} s", record.Category, record.Kind, method, uri, record.Timestamp - begin.Timestamp)); // Remove begintrace this.beginTraces.Remove(begin); } } }
public void Fatal(TraceRecord record) { WriteRecord(RecordType.Fatal, record); }
private void Log(TraceRecord record) { var message = new StringBuilder(); if (!String.IsNullOrWhiteSpace(record.Message)) { message.Append("").Append(record.Message + Environment.NewLine); } if (record.Request != null) { if (record.Request.Method != null) { message.Append("Method: " + record.Request.Method + Environment.NewLine); } if (record.Request.RequestUri != null) { message.Append("").Append("URL:" + record.Request.RequestUri + Environment.NewLine); } if (record.Request.Headers != null && record.Request.Headers.Contains("Token") && record.Request.Headers.GetValues("Token") != null && record.Request.Headers.GetValues("Token").FirstOrDefault() != null) { message.Append("") .Append("Token: " + record.Request.Headers.GetValues("Token").FirstOrDefault() + Environment.NewLine); } if (!string.IsNullOrWhiteSpace(record.Category)) { message.Append("").Append(record.Category); } if (!string.IsNullOrWhiteSpace(record.Operator)) { message.Append(" ").Append(record.Operator).Append(" ").Append(record.Operation); } if (record.Exception != null && !String.IsNullOrWhiteSpace(record.Exception.GetBaseException().Message)) { var exceptionType = record.Exception.GetType(); message.Append(Environment.NewLine); if (exceptionType == typeof(ApiException)) { var exception = record.Exception as ApiException; if (exception != null) { message.Append(" ").Append("Error: " + exception.ErrorDescription + Environment.NewLine); message.Append("").Append("Error Code: " + exception.ErrorCode + Environment.NewLine); } } else if (exceptionType == typeof(ApiBusinessException)) { var exception = record.Exception as ApiBusinessException; if (exception != null) { message.Append(" ").Append("Error: " + exception.ErrorDescription + Environment.NewLine); message.Append("").Append("Error Code: " + exception.ErrorCode + Environment.NewLine); } } else if (exceptionType == typeof(ApiDataException)) { var exception = record.Exception as ApiDataException; if (exception != null) { message.Append(" ").Append("Error: " + exception.ErrorDescription + Environment.NewLine); message.Append("").Append("Error Code: " + exception.ErrorCode + Environment.NewLine); } } else { message.Append("") .Append("Error: " + record.Exception.GetBaseException().Message + Environment.NewLine); } } Logger[record.Level](Convert.ToString(message) + Environment.NewLine); } }
public void Warn(TraceRecord record) { WriteRecord(RecordType.Warn, record); }
/// <summary> /// Gets trace definition like: Wrote to the EventLog. /// Event description ID=57399, Level=critical, Channel=Debug /// </summary> /// <param name="trace">The trace provider</param> /// <param name="traceRecord">Extended data (TraceRecord) for the event</param> internal static void TraceCodeEventLogCritical(EtwDiagnosticTrace trace, TraceRecord traceRecord) { }
public async Task ExecuteExceptionFilterAsync_Faults_And_Traces_When_Inner_Faults() { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage response = new HttpResponseMessage(); Mock <IExceptionFilter> mockFilter = new Mock <IExceptionFilter>() { CallBase = true }; InvalidOperationException exception = new InvalidOperationException("test"); TaskCompletionSource <object> tcs = new TaskCompletionSource <object>(null); tcs.TrySetException(exception); mockFilter .Setup( a => a.ExecuteExceptionFilterAsync( It.IsAny <HttpActionExecutedContext>(), It.IsAny <CancellationToken>() ) ) .Returns(tcs.Task); HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext( request, response ); TestTraceWriter traceWriter = new TestTraceWriter(); ExceptionFilterTracer tracer = new ExceptionFilterTracer( mockFilter.Object, traceWriter ); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "ExecuteExceptionFilterAsync" }, new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "ExecuteExceptionFilterAsync" } }; // Act Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync( actionExecutedContext, CancellationToken.None ); // Assert Exception thrown = await Assert.ThrowsAsync <InvalidOperationException>(() => task); Assert.Same(exception, thrown); Assert.Same(exception, traceWriter.Traces[1].Exception); Assert.Equal <TraceRecord>( expectedTraces, traceWriter.Traces, new TraceRecordComparer() ); }
/// <summary> /// Gets trace definition like: Wrote to the EventLog. /// Event description ID=57400, Level=error, Channel=Debug /// </summary> /// <param name="trace">The trace provider</param> /// <param name="traceRecord">Extended data (TraceRecord) for the event</param> internal static void TraceCodeEventLogError(EtwDiagnosticTrace trace, TraceRecord traceRecord) { }
/// <summary> /// Gets trace definition like: Wrote to the EventLog. /// Event description ID=57402, Level=verbose, Channel=Debug /// </summary> /// <param name="trace">The trace provider</param> /// <param name="traceRecord">Extended data (TraceRecord) for the event</param> internal static void TraceCodeEventLogVerbose(EtwDiagnosticTrace trace, TraceRecord traceRecord) { }
/// <summary> /// Gets trace definition like: Wrote to the EventLog. /// Event description ID=57403, Level=warning, Channel=Debug /// </summary> /// <param name="trace">The trace provider</param> /// <param name="traceRecord">Extended data (TraceRecord) for the event</param> internal static void TraceCodeEventLogWarning(EtwDiagnosticTrace trace, TraceRecord traceRecord) { WcfEventSource.Instance.TraceCodeEventLogWarning(traceRecord.EventId); }
public async Task InvokeActionAsync_Traces_Faulted_Inner_Task() { // Arrange Mock <ApiControllerActionInvoker> mockActionInvoker = new Mock <ApiControllerActionInvoker>() { CallBase = true }; InvalidOperationException expectedException = new InvalidOperationException( "test message" ); TaskCompletionSource <HttpResponseMessage> tcs = new TaskCompletionSource <HttpResponseMessage>(null); tcs.TrySetException(expectedException); mockActionInvoker .Setup( a => a.InvokeActionAsync( It.IsAny <HttpActionContext>(), It.IsAny <CancellationToken>() ) ) .Returns(tcs.Task); TestTraceWriter traceWriter = new TestTraceWriter(); HttpActionInvokerTracer tracer = new HttpActionInvokerTracer( mockActionInvoker.Object, traceWriter ); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord( _actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info ) { Kind = TraceKind.Begin }, new TraceRecord( _actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Error ) { Kind = TraceKind.End } }; // Act var response = ((IHttpActionInvoker)tracer).InvokeActionAsync( _actionContext, CancellationToken.None ); // Assert await Assert.ThrowsAsync <InvalidOperationException>(() => response); Assert.Equal <TraceRecord>( expectedTraces, traceWriter.Traces, new TraceRecordComparer() ); Assert.Equal(expectedException, traceWriter.Traces[1].Exception); }
public void Negotiate_Traces_BeginEnd() { // Arrange MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter(); _mockNegotiator.Setup( n => n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>())).Returns( new ContentNegotiationResult(expectedFormatter, null)); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.End } }; // Act ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0]); // Assert Assert.Equal<TraceRecord>(expectedTraces, _traceWriter.Traces, new TraceRecordComparer()); }
public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action <TraceRecord> traceAction) { var record = new TraceRecord(request, category, level); traceAction(record); }
public void Info(TraceRecord record) { WriteRecord(RecordType.Info, record); }
internal static void TraceEvent(TraceEventType severity, TraceCode traceCode, TraceRecord extendedData, object source, Exception exception, Message message) { Guid empty = Guid.Empty; if (DiagnosticUtility.ShouldTrace(severity)) { DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, TraceUtility.Description(traceCode), extendedData, exception, empty, source); } }
public void Error(TraceRecord record) { WriteRecord(RecordType.Error, record); }
internal void TraceEvent(TraceEventType type, int code, string msdnTraceCode, string description, TraceRecord trace, Exception exception, Guid activityId, object source) { using ((this.ShouldUseActivity && (Guid.Empty != activityId)) ? Activity.CreateActivity(activityId) : null) { this.TraceEvent(type, code, msdnTraceCode, description, trace, exception, source); } }
private void BuildTrace(TraceEventType type, string msdnTraceCode, string description, TraceRecord trace, Exception exception, object source, out TraceXPathNavigator navigator) { PlainXmlWriter xml = new PlainXmlWriter(0xffff); navigator = xml.Navigator; this.BuildTrace(xml, type, msdnTraceCode, description, trace, exception, source); if (!this.TraceSource.ShouldLogPii) { navigator.RemovePii(System.ServiceModel.Diagnostics.DiagnosticStrings.HeadersPaths); } }
public void Negotiate_Traces_BeginEnd_When_Inner_Throws() { // Arrange MediaTypeFormatter expectedFormatter = new XmlMediaTypeFormatter(); InvalidOperationException expectedException = new InvalidOperationException("test"); _mockNegotiator.Setup( n => n.Negotiate(It.IsAny<Type>(), It.IsAny<HttpRequestMessage>(), It.IsAny<IEnumerable<MediaTypeFormatter>>())).Throws(expectedException); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(_request, TraceCategories.FormattingCategory, TraceLevel.Error) { Kind = TraceKind.End } }; // Act & Assert Assert.Throws<InvalidOperationException>(() => ((IContentNegotiator)_tracer).Negotiate(typeof(int), _request, new MediaTypeFormatter[0])); // Assert Assert.Equal<TraceRecord>(expectedTraces, _traceWriter.Traces, new TraceRecordComparer()); Assert.Same(expectedException, _traceWriter.Traces[1].Exception); }
/// <summary> /// 日志写入 /// </summary> /// <param name="record"></param> private void Log(TraceRecord record) { var message = new StringBuilder(); /**************************运行日志****************************/ //if (!string.IsNullOrWhiteSpace(record.Message)) //{ // message.Append("").Append(record.Message + Environment.NewLine); //} if (record.Request != null) { if (record.Request.Method != null) { message.Append("请求类型 : " + record.Request.Method + Environment.NewLine); } if (record.Request.RequestUri != null) { message.Append("").Append("请求地址 : " + record.Request.RequestUri + Environment.NewLine); } if (record.Request.Headers != null && record.Request.Headers.Contains("Token") && record.Request.Headers.GetValues("Token") != null && record.Request.Headers.GetValues("Token").FirstOrDefault() != null) { message.Append("").Append("Token : " + record.Request.Headers.GetValues("Token").FirstOrDefault() + Environment.NewLine); } var ipRecord = GetClientIp(record.Request); if (ipRecord != null) { message.Append("").Append("IP地址 : " + GetClientIp(record.Request) + Environment.NewLine); } } if (!string.IsNullOrWhiteSpace(record.Category) && !record.Category.Contains("exception")) { message.Append("").Append(record.Category); } if (!string.IsNullOrWhiteSpace(record.Operator)) { message.Append(" ").Append(record.Operator).Append(" ").Append(record.Operation); } //***************************异常日志***********************************// if (record.Exception != null && !string.IsNullOrWhiteSpace(record.Exception.GetBaseException().Message)) { var exceptionType = record.Exception.GetType(); message.Append("").Append("异常类型 : " + exceptionType.ToString()); message.Append(Environment.NewLine); System.Exception exception = record.Exception; string errmsg = exception.Message; while (exception.InnerException != null) { errmsg += exception.InnerException.Message; exception = exception.InnerException; } message.Append("").Append("异常信息 : " + errmsg); message.Append(Environment.NewLine); message.Append("").Append("堆栈信息 : " + record.Exception.StackTrace); message.Append(Environment.NewLine); } //日志写入本地文件 Logger[record.Level](Convert.ToString(message) + Environment.NewLine); }
/// <summary> /// Logs info/Error to Log file /// </summary> /// <param name="record"></param> private void log(TraceRecord record, Dictionary <string, string> requestDict, TraceLevel level) { var message = new StringBuilder(); if (!string.IsNullOrWhiteSpace(record.Message)) { message.Append("").Append(record.Message + Environment.NewLine); } if (record.Request != null) { //GET, POST, PUT, DELETE if (record.Request.Method != null) { GlobalContext.Properties["METHOD"] = record.Request.Method; message.Append("Method: " + record.Request.Method + Environment.NewLine); } if (record.Request.RequestUri != null) { GlobalContext.Properties["URL"] = record.Request.RequestUri; message.Append("").Append("URL: " + record.Request.RequestUri + Environment.NewLine); } if (record.Request.Headers != null && record.Request.Headers.Contains("Authorization") && record.Request.Headers.GetValues("Authorization") != null && record.Request.Headers.GetValues("Authorization").FirstOrDefault() != null) { GlobalContext.Properties["AUTH_TOKEN"] = record.Request.Headers.GetValues("Authorization").FirstOrDefault(); message.Append("").Append("Auth Token: " + record.Request.Headers.GetValues("Authorization").FirstOrDefault() + Environment.NewLine); } } if (!string.IsNullOrWhiteSpace(record.Category)) { message.Append("").Append(record.Category); } if (!string.IsNullOrWhiteSpace(record.Operator)) { message.Append(" ").Append(record.Operator).Append(" ").Append(record.Operation); } if (record.Exception != null && !string.IsNullOrWhiteSpace(record.Exception.GetBaseException().Message)) { var exceptionType = record.Exception.GetType(); message.Append(Environment.NewLine); if (exceptionType == typeof(WebException)) { var exception = record.Exception as WebException; if (exception != null) { message.Append("").Append("Hata Kodu: " + exception.HataKodu + Environment.NewLine); message.Append("").Append("Hata: " + exception.HataAciklama + Environment.NewLine); message.Append("").Append("Hata Detayı: " + exception.HataDetayAciklama + Environment.NewLine); message.Append("").Append("Hata Stacktrace: " + exception.StackTrace + Environment.NewLine); message.Append("").Append("HTTP Status Code: " + exception.HttpStatusCode + Environment.NewLine); } } //else if (exceptionType == typeof(ApiBusinessException)) //{ // var exception = record.Exception as ApiBusinessException; // if (exception != null) // { // message.Append("").Append("Error: " + exception.ErrorDescription + Environment.NewLine); // message.Append("").Append("Error Code: " + exception.ErrorCode + Environment.NewLine); // } //} //else if (exceptionType == typeof(ApiDataException)) //{ // var exception = record.Exception as ApiDataException; // if (exception != null) // { // message.Append("").Append("Error: " + exception.ErrorDescription + Environment.NewLine); // message.Append("").Append("Error Code: " + exception.ErrorCode + Environment.NewLine); // } //} else { message.Append("").Append("Hata: " + record.Exception.GetBaseException().Message + Environment.NewLine); message.Append("").Append("Hata Stacktrace: " + record.Exception.StackTrace + Environment.NewLine); } } string logMessage = Convert.ToString(message) + Environment.NewLine; GlobalContext.Properties["IP_ADDRESS"] = requestDict["IP_ADDRESS"]; GlobalContext.Properties["CONTROLLER"] = requestDict["CONTROLLER"]; GlobalContext.Properties["ACTION"] = requestDict["ACTION"]; GlobalContext.Properties["USER_ID"] = requestDict["USER_ID"]; GlobalContext.Properties["ACTION_PARAMETER"] = requestDict["ACTION_PARAMETER"]; log(level, logMessage); }
internal static void DetectErrorOrWarningOnActivity(Activity activity, Dictionary <string, Activity> allActivities, List <TraceRecord> traces, ExecutionInfo execution, bool isChild, bool isDetectSeverityLevel, ref TraceRecordSetSeverityLevel severityLevel, ref TraceRecord firstErrorTrace, int depth) { if (activity != null && depth < MAX_ACTIVITY_TREE_DEPTH) { traces = ((traces == null) ? InternalLoadTraceRecordWarpper(activity, execution, containsActivityBoundary: true) : traces); foreach (TraceRecord trace in traces) { if (execution == null || execution.ExecutionID == trace.Execution.ExecutionID) { if (trace.Level == TraceEventType.Critical || trace.Level == TraceEventType.Error) { if (firstErrorTrace == null) { firstErrorTrace = trace; } if (severityLevel < TraceRecordSetSeverityLevel.Error) { severityLevel = TraceRecordSetSeverityLevel.Error; } return; } if (trace.Level == TraceEventType.Warning) { if (firstErrorTrace == null) { firstErrorTrace = trace; } if (isDetectSeverityLevel) { break; } if (severityLevel < TraceRecordSetSeverityLevel.Warning) { severityLevel = TraceRecordSetSeverityLevel.Warning; } } } } if (isChild) { foreach (Activity childActivity in GetChildActivities(activity.Id, traces, allActivities, execution)) { DetectErrorOrWarningOnActivity(childActivity, allActivities, null, null, isChild, isDetectSeverityLevel, ref severityLevel, ref firstErrorTrace, depth + 1); if (firstErrorTrace != null) { switch (isDetectSeverityLevel) { case false: return; } if (severityLevel == TraceRecordSetSeverityLevel.Error) { break; } } } } } }
// Returns a list of strings describing all of the expected trace records that were not // actually traced. // If you experience test failures from this list, it means someone stopped tracing or // changed the content of what was traced. // Update the ExpectedTraceRecords property to reflect what is expected. private static IList <string> MissingTraces( IList <ExpectedTraceRecord> expectedRecords, IList <TraceRecord> actualRecords ) { List <string> missing = new List <string>(); foreach (ExpectedTraceRecord expectedRecord in expectedRecords) { TraceRecord beginTrace = actualRecords.SingleOrDefault( r => String.Equals( r.Category, expectedRecord.Category, StringComparison.OrdinalIgnoreCase ) && String.Equals( r.Operator, expectedRecord.OperatorName, StringComparison.OrdinalIgnoreCase ) && String.Equals( r.Operation, expectedRecord.OperationName, StringComparison.OrdinalIgnoreCase ) && r.Kind == TraceKind.Begin ); if (beginTrace == null) { missing.Add( string.Format( "Begin category={0}, operator={1}, operation={2}", expectedRecord.Category, expectedRecord.OperatorName, expectedRecord.OperationName ) ); } TraceRecord endTrace = actualRecords.SingleOrDefault( r => String.Equals( r.Category, expectedRecord.Category, StringComparison.OrdinalIgnoreCase ) && String.Equals( r.Operator, expectedRecord.OperatorName, StringComparison.OrdinalIgnoreCase ) && String.Equals( r.Operation, expectedRecord.OperationName, StringComparison.OrdinalIgnoreCase ) && r.Kind == TraceKind.End ); if (endTrace == null) { missing.Add( string.Format( "End category={0}, operator={1}, operation={2}", expectedRecord.Category, expectedRecord.OperatorName, expectedRecord.OperationName ) ); } } return(missing); }
/// <inheritdoc /> public override AnalysisContainer CreateNewAnalysisContainer(TraceRecord traceRecord) { return(new AnalysisContainer(new ReconfigurationAnalysisEvent((ReconfigurationCompletedTraceRecord)traceRecord), AgentIdentifier.ReconfigurationAnalysisAgent)); }
internal void CleanUp() { currentTraceRecord = null; advancedInfoPanel.Controls.Clear(); }
/// <summary> /// Register interest in an Event /// </summary> /// <param name="traceRecord"></param> public InterestFilter RegisterInterestForEvent(TraceRecord traceRecord) { Assert.IsNotNull(traceRecord, "traceRecord"); this.traceRecord = traceRecord; return(this); }
public void ExecuteAsync_Throws_What_Inner_Throws_And_Traces() { // Arrange Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true }; InvalidOperationException exception = new InvalidOperationException("test"); mockActionDescriptor.Setup( a => a.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>(), CancellationToken.None)).Throws(exception); mockActionDescriptor.Setup(a => a.ActionName).Returns("test"); HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(); controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(ApiController)); IDictionary<string, object> arguments = new Dictionary<string, object>(); TestTraceWriter traceWriter = new TestTraceWriter(); HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, traceWriter); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info) { Kind = TraceKind.Begin }, new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Error) { Kind = TraceKind.End } }; // Act & Assert Assert.Throws<InvalidOperationException>(() => tracer.ExecuteAsync(controllerContext, arguments, CancellationToken.None)); // Assert Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); Assert.Same(exception, traceWriter.Traces[1].Exception); }
public void InvokeActionAsync_Traces_Exception_Thrown_From_Inner() { // Arrange InvalidOperationException expectedException = new InvalidOperationException( "test message" ); Mock <ApiControllerActionInvoker> mockActionInvoker = new Mock <ApiControllerActionInvoker>() { CallBase = true }; mockActionInvoker .Setup( a => a.InvokeActionAsync( It.IsAny <HttpActionContext>(), It.IsAny <CancellationToken>() ) ) .Throws(expectedException); TestTraceWriter traceWriter = new TestTraceWriter(); HttpActionInvokerTracer tracer = new HttpActionInvokerTracer( mockActionInvoker.Object, traceWriter ); TraceRecord[] expectedTraces = new TraceRecord[] { new TraceRecord( _actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Info ) { Kind = TraceKind.Begin }, new TraceRecord( _actionContext.Request, TraceCategories.ActionCategory, TraceLevel.Error ) { Kind = TraceKind.End } }; // Act & Assert Assert.Throws <InvalidOperationException>( () => ((IHttpActionInvoker)tracer).InvokeActionAsync( _actionContext, CancellationToken.None ) ); // Assert Assert.Equal <TraceRecord>( expectedTraces, traceWriter.Traces, new TraceRecordComparer() ); Assert.Equal(expectedException, traceWriter.Traces[1].Exception); }
private void BuildTrace(PlainXmlWriter xml, TraceEventType type, string msdnTraceCode, string description, TraceRecord trace, Exception exception, object source) { xml.WriteStartElement("TraceRecord"); xml.WriteAttributeString("xmlns", "http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord"); xml.WriteAttributeString("Severity", LookupSeverity(type)); xml.WriteElementString("TraceIdentifier", msdnTraceCode); xml.WriteElementString("Description", description); xml.WriteElementString("AppDomain", this.AppDomainFriendlyName); if (source != null) { xml.WriteElementString("Source", CreateSourceString(source)); } if (trace != null) { xml.WriteStartElement("ExtendedData"); xml.WriteAttributeString("xmlns", trace.EventId); trace.WriteTo(xml); xml.WriteEndElement(); } if (exception != null) { xml.WriteStartElement("Exception"); this.AddExceptionToTraceString(xml, exception); xml.WriteEndElement(); } xml.WriteEndElement(); }
/// <summary> /// Gets trace definition like: Wrote to the EventLog. /// Event description ID=57403, Level=warning, Channel=Debug /// </summary> /// <param name="trace">The trace provider</param> /// <param name="traceRecord">Extended data (TraceRecord) for the event</param> internal static void TraceCodeEventLogWarning(EtwDiagnosticTrace trace, TraceRecord traceRecord) { }
internal Exception ThrowHelper(Exception exception, TraceEventType eventType, TraceRecord extendedData) { //if ((_diagnosticTrace == null ? 0 : (_diagnosticTrace.ShouldTrace(eventType) ? 1 : 0)) != 0) //{ // using ( // ExceptionUtility.useStaticActivityId // ? Activity.CreateActivity(ExceptionUtility.activityId) // : (Activity)null) // _diagnosticTrace.TraceEvent(eventType, 131075, // LegacyDiagnosticTrace.GenerateMsdnTraceCode("System.ServiceModel.Diagnostics", // "ThrowingException"), TraceSR.Format("ThrowingException"), extendedData, exception, // (object)null); // IDictionary data = exception.Data; // if (data != null && !data.IsReadOnly && !data.IsFixedSize) // { // object obj = // data[(object)"System.ServiceModel.Diagnostics.ExceptionUtility.ExceptionStackAsString"]; // string str1 = obj == null ? "" : obj as string; // if (str1 != null) // { // string stackTrace = exception.StackTrace; // if (!string.IsNullOrEmpty(stackTrace)) // { // string str2 = str1 + (str1.Length == 0 ? "" : Environment.NewLine) + "throw" + // Environment.NewLine + stackTrace + Environment.NewLine + "catch" + // Environment.NewLine; // data[(object)"System.ServiceModel.Diagnostics.ExceptionUtility.ExceptionStackAsString"] // = (object)str2; // } // } // } //} //this.exceptionTrace.TraceEtwException(exception, eventType); return(exception); }
internal void TraceEvent(TraceEventType type, int code, string msdnTraceCode, string description, TraceRecord trace, Exception exception, object source) { TraceXPathNavigator navigator = null; try { if ((this.TraceSource != null) && this.HaveListeners) { try { this.BuildTrace(type, msdnTraceCode, description, trace, exception, source, out navigator); } catch (PlainXmlWriter.MaxSizeExceededException) { StringTraceRecord record = new StringTraceRecord("TruncatedTraceId", msdnTraceCode); this.TraceEvent(type, 0x2000c, GenerateMsdnTraceCode("System.ServiceModel.Diagnostics", "TraceTruncatedQuotaExceeded"), TraceSR.GetString("TraceCodeTraceTruncatedQuotaExceeded"), record, null, null); } this.TraceSource.TraceData(type, code, navigator); if (this.calledShutdown) { this.TraceSource.Flush(); } this.LastFailure = DateTime.MinValue; } } catch (Exception exception2) { if (Fx.IsFatal(exception2)) { throw; } this.LogTraceFailure((navigator == null) ? string.Empty : navigator.ToString(), exception2); } }