/// <summary> /// Initializes a new instance of the <see cref="DiagnosticTrace"/> class. /// </summary> /// <param name="source">The source.</param> public DiagnosticTrace(DiagnosticSource source) { if (source == null) { ThrowHelper.ThrowArgumentNullException("source"); } this.Source = source; }
public static void AfterOnResourceExecuted( this DiagnosticSource diagnosticSource, ResourceExecutedContext resourceExecutedContext, IResourceFilter filter) { Debug.Assert(diagnosticSource != null); Debug.Assert(resourceExecutedContext != null); Debug.Assert(filter != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.AfterOnResourceExecuted")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.AfterOnResourceExecuted", new { actionDescriptor = resourceExecutedContext.ActionDescriptor, resourceExecutedContext = resourceExecutedContext, filter = filter }); } }
public static void AfterOnException( this DiagnosticSource diagnosticSource, ExceptionContext exceptionContext, IExceptionFilter filter) { Debug.Assert(diagnosticSource != null); Debug.Assert(exceptionContext != null); Debug.Assert(filter != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.AfterOnException")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.AfterOnException", new { actionDescriptor = exceptionContext.ActionDescriptor, exceptionContext = exceptionContext, filter = filter }); } }
public static void AfterOnPageHandlerExecution( this DiagnosticSource diagnosticSource, PageHandlerExecutedContext handlerExecutedContext, IAsyncPageFilter filter) { Debug.Assert(diagnosticSource != null); Debug.Assert(handlerExecutedContext != null); Debug.Assert(filter != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.AfterOnPageHandlerExecution")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.AfterOnPageHandlerExecution", new { actionDescriptor = handlerExecutedContext.ActionDescriptor, handlerExecutedContext = handlerExecutedContext, filter = filter }); } }
public void IntPayload() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; var result = new List <KeyValuePair <string, object> >(); var observer = new ObserverToList <TelemData>(result); using (listener.Subscribe(new ObserverToList <TelemData>(result))) { listener.Write("IntPayload", 5); Assert.Equal(1, result.Count); Assert.Equal("IntPayload", result[0].Key); Assert.Equal(5, result[0].Value); } // unsubscribe // Make sure that after unsubscribing, we don't get more events. source.Write("IntPayload", 5); Assert.Equal(1, result.Count); } }
Activity StartIfEnabled(DiagnosticSource source, string name, object args, SendContext context) { if (!source.IsEnabled(name) || context.TryGetPayload <Activity>(out _)) { return(null); } var activity = new Activity(name) .AddTag(DiagnosticHeaders.MessageId, context.MessageId.ToString()) .AddTag(DiagnosticHeaders.InitiatorId, context.InitiatorId.ToString()) .AddTag(DiagnosticHeaders.SourceAddress, context.SourceAddress.ToString()) .AddTag(DiagnosticHeaders.DestinationAddress, context.DestinationAddress.ToString()) .AddBaggage(DiagnosticHeaders.CorrelationId, context.CorrelationId.ToString()) .AddBaggage(DiagnosticHeaders.CorrelationConversationId, context.ConversationId.ToString()); source.StartActivity(activity, args ?? new { }); Inject(context, activity); return(context.AddOrUpdatePayload(() => activity, a => activity)); }
public static void BeforeOnPageHandlerSelected( this DiagnosticSource diagnosticSource, PageHandlerSelectedContext handlerSelectedContext, IPageFilter filter) { Debug.Assert(diagnosticSource != null); Debug.Assert(handlerSelectedContext != null); Debug.Assert(filter != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.BeforeOnPageHandlerSelected")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.BeforeOnPageHandlerSelected", new { actionDescriptor = handlerSelectedContext.ActionDescriptor, handlerSelectedContext = handlerSelectedContext, filter = filter }); } }
public static void WriteCommandBefore( this DiagnosticSource diagnosticSource, DbCommand command, string executeMethod, Guid instanceId, long startTimestamp, bool async) { if (diagnosticSource.IsEnabled(BeforeExecuteCommand)) { diagnosticSource.Write( BeforeExecuteCommand, new RelationalDiagnosticSourceBeforeMessage { Command = command, ExecuteMethod = executeMethod, InstanceId = instanceId, Timestamp = startTimestamp, IsAsync = async }); } }
public static void BeforeOnAuthorization( this DiagnosticSource diagnosticSource, AuthorizationFilterContext authorizationContext, IAuthorizationFilter filter) { Debug.Assert(diagnosticSource != null); Debug.Assert(authorizationContext != null); Debug.Assert(filter != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.BeforeOnAuthorization")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.BeforeOnAuthorization", new { actionDescriptor = authorizationContext.ActionDescriptor, authorizationContext = authorizationContext, filter = filter }); } }
public static void BeforeOnResultExecuting( this DiagnosticSource diagnosticSource, ResultExecutingContext resultExecutingContext, IResultFilter filter) { Debug.Assert(diagnosticSource != null); Debug.Assert(resultExecutingContext != null); Debug.Assert(filter != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.BeforeOnResultExecuting")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.BeforeOnResultExecuting", new { actionDescriptor = resultExecutingContext.ActionDescriptor, resultExecutingContext = resultExecutingContext, filter = filter }); } }
public static void AfterOnActionExecuting( this DiagnosticSource diagnosticSource, ActionExecutingContext actionExecutingContext, IActionFilter filter) { Debug.Assert(diagnosticSource != null); Debug.Assert(actionExecutingContext != null); Debug.Assert(filter != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.AfterOnActionExecuting")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.AfterOnActionExecuting", new { actionDescriptor = actionExecutingContext.ActionDescriptor, actionExecutingContext = actionExecutingContext, filter = filter }); } }
public ResourceInvoker( DiagnosticSource diagnosticSource, ILogger logger, ActionContext actionContext, IFilterMetadata[] filters, IList <IValueProviderFactory> valueProviderFactories) { if (diagnosticSource == null) { throw new ArgumentNullException(nameof(diagnosticSource)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } if (filters == null) { throw new ArgumentNullException(nameof(filters)); } if (valueProviderFactories == null) { throw new ArgumentNullException(nameof(valueProviderFactories)); } _diagnosticSource = diagnosticSource; _logger = logger; _actionContext = actionContext; _filters = filters; _valueProviderFactories = valueProviderFactories; _cursor = new FilterCursor(filters); }
public void Ping(Node node) { if (PingDisabled(node)) { return; } var pingData = CreatePingRequestData(node); using (var audit = Audit(PingSuccess, node)) using (var d = DiagnosticSource.Diagnose <RequestData, IApiCallDetails>(DiagnosticSources.RequestPipeline.Ping, pingData)) { audit.Path = pingData.PathAndQuery; try { var response = _connection.Request <VoidResponse>(pingData); d.EndState = response; ThrowBadAuthPipelineExceptionWhenNeeded(response); //ping should not silently accept bad but valid http responses if (!response.Success) { throw new PipelineException(pingData.OnFailurePipelineFailure, response.OriginalException) { ApiCall = response } } ; } catch (Exception e) { var response = (e as PipelineException)?.ApiCall; audit.Event = PingFailure; audit.Exception = e; throw new PipelineException(PipelineFailure.PingFailure, e) { ApiCall = response }; } } }
/// <summary> /// Initializes a new instance of the <see cref="ConventionHostBuilder{TSelf}" /> class. /// </summary> /// <param name="scanner">The scanner.</param> /// <param name="assemblyCandidateFinder">The assembly candidate finder.</param> /// <param name="assemblyProvider">The assembly provider.</param> /// <param name="diagnosticSource">The diagnostic source.</param> /// <param name="serviceProperties">The properties.</param> protected ConventionHostBuilder( IConventionScanner scanner, IAssemblyCandidateFinder assemblyCandidateFinder, IAssemblyProvider assemblyProvider, DiagnosticSource diagnosticSource, IServiceProviderDictionary serviceProperties ) { Scanner = scanner; AssemblyCandidateFinder = assemblyCandidateFinder; AssemblyProvider = assemblyProvider; DiagnosticSource = diagnosticSource; ServiceProperties = serviceProperties ?? new ServiceProviderDictionary(); if (!Properties.TryGetValue(typeof(IConventionScanner), out var _)) { Properties[typeof(IConventionScanner)] = scanner; } if (!Properties.TryGetValue(typeof(IAssemblyProvider), out var _)) { Properties[typeof(IAssemblyProvider)] = assemblyProvider; } if (!Properties.TryGetValue(typeof(IAssemblyCandidateFinder), out var _)) { Properties[typeof(IAssemblyCandidateFinder)] = assemblyCandidateFinder; } if (!Properties.TryGetValue(typeof(DiagnosticSource), out var _)) { Properties[typeof(DiagnosticSource)] = diagnosticSource; } if (!Properties.TryGetValue(typeof(ILogger), out var _)) { Properties[typeof(ILogger)] = new DiagnosticLogger(diagnosticSource); } }
public ControllerActionInvokerProvider( IControllerFactory controllerFactory, IEnumerable <IFilterProvider> filterProviders, IControllerActionArgumentBinder argumentBinder, IOptions <MvcOptions> optionsAccessor, IActionBindingContextAccessor actionBindingContextAccessor, ILoggerFactory loggerFactory, DiagnosticSource diagnosticSource) { _controllerFactory = controllerFactory; _filterProviders = filterProviders.OrderBy(item => item.Order).ToArray(); _argumentBinder = argumentBinder; _inputFormatters = optionsAccessor.Value.InputFormatters.ToArray(); _outputFormatters = optionsAccessor.Value.OutputFormatters.ToArray(); _modelBinders = optionsAccessor.Value.ModelBinders.ToArray(); _modelValidatorProviders = optionsAccessor.Value.ModelValidatorProviders.ToArray(); _valueProviderFactories = optionsAccessor.Value.ValueProviderFactories.ToArray(); _actionBindingContextAccessor = actionBindingContextAccessor; _maxModelValidationErrors = optionsAccessor.Value.MaxModelValidationErrors; _logger = loggerFactory.CreateLogger <ControllerActionInvoker>(); _diagnosticSource = diagnosticSource; }
/// <summary> /// Initializes a new instance of the <see cref="DeveloperExceptionPageMiddleware"/> class /// </summary> /// <param name="next">The <see cref="RequestDelegate"/> representing the next middleware in the pipeline.</param> /// <param name="options">The options for configuring the middleware.</param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> used for logging.</param> /// <param name="hostingEnvironment"></param> /// <param name="diagnosticSource">The <see cref="DiagnosticSource"/> used for writing diagnostic messages.</param> /// <param name="filters">The list of registered <see cref="IDeveloperPageExceptionFilter"/>.</param> /// <param name="problemDetailsService">The <see cref="IProblemDetailsService"/> used for writing <see cref="ProblemDetails"/> messages.</param> public DeveloperExceptionPageMiddlewareImpl( RequestDelegate next, IOptions <DeveloperExceptionPageOptions> options, ILoggerFactory loggerFactory, IWebHostEnvironment hostingEnvironment, DiagnosticSource diagnosticSource, IEnumerable <IDeveloperPageExceptionFilter> filters, IProblemDetailsService?problemDetailsService = null) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (filters == null) { throw new ArgumentNullException(nameof(filters)); } _next = next; _options = options.Value; _logger = loggerFactory.CreateLogger <DeveloperExceptionPageMiddleware>(); _fileProvider = _options.FileProvider ?? hostingEnvironment.ContentRootFileProvider; _diagnosticSource = diagnosticSource; _exceptionDetailsProvider = new ExceptionDetailsProvider(_fileProvider, _logger, _options.SourceCodeLineCount); _exceptionHandler = DisplayException; _problemDetailsService = problemDetailsService; foreach (var filter in filters.Reverse()) { var nextFilter = _exceptionHandler; _exceptionHandler = errorContext => filter.HandleExceptionAsync(errorContext, nextFilter); } }
public static void ViewNotFound( this DiagnosticSource diagnosticSource, ActionContext actionContext, bool isMainPage, PartialViewResult viewResult, string viewName, IEnumerable <string> searchedLocations) { if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.ViewNotFound")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.ViewNotFound", new { actionContext = actionContext, isMainPage = isMainPage, result = viewResult, viewName = viewName, searchedLocations = searchedLocations, }); } }
public static void ViewFound( this DiagnosticSource diagnosticSource, ActionContext actionContext, bool isMainPage, PartialViewResult viewResult, string viewName, IView view) { if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.ViewFound")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.ViewFound", new { actionContext = actionContext, isMainPage = isMainPage, result = viewResult, viewName = viewName, view = view, }); } }
/// <summary> /// Creates a new <see cref="ViewExecutor"/>. /// </summary> /// <param name="viewOptions">The <see cref="IOptions{MvcViewOptions}"/>.</param> /// <param name="writerFactory">The <see cref="IHttpResponseStreamWriterFactory"/>.</param> /// <param name="viewEngine">The <see cref="ICompositeViewEngine"/>.</param> /// <param name="tempDataFactory">The <see cref="ITempDataDictionaryFactory"/>.</param> /// <param name="diagnosticSource">The <see cref="DiagnosticSource"/>.</param> public ViewExecutor( IOptions <MvcViewOptions> viewOptions, IHttpResponseStreamWriterFactory writerFactory, ICompositeViewEngine viewEngine, ITempDataDictionaryFactory tempDataFactory, DiagnosticSource diagnosticSource) { if (viewOptions == null) { throw new ArgumentNullException(nameof(viewOptions)); } if (writerFactory == null) { throw new ArgumentNullException(nameof(writerFactory)); } if (viewEngine == null) { throw new ArgumentNullException(nameof(viewEngine)); } if (tempDataFactory == null) { throw new ArgumentNullException(nameof(tempDataFactory)); } if (diagnosticSource == null) { throw new ArgumentNullException(nameof(diagnosticSource)); } ViewOptions = viewOptions.Value; WriterFactory = writerFactory; ViewEngine = viewEngine; TempDataFactory = tempDataFactory; DiagnosticSource = diagnosticSource; }
public PageActionInvokerProvider( IPageLoader loader, IPageFactoryProvider pageFactoryProvider, IPageModelFactoryProvider modelFactoryProvider, IRazorPageFactoryProvider razorPageFactoryProvider, IActionDescriptorCollectionProvider collectionProvider, IEnumerable <IFilterProvider> filterProviders, ParameterBinder parameterBinder, IModelMetadataProvider modelMetadataProvider, IModelBinderFactory modelBinderFactory, ITempDataDictionaryFactory tempDataFactory, IOptions <MvcOptions> mvcOptions, IOptions <HtmlHelperOptions> htmlHelperOptions, IPageHandlerMethodSelector selector, RazorProjectFileSystem razorFileSystem, DiagnosticSource diagnosticSource, ILoggerFactory loggerFactory, IActionResultTypeMapper mapper) { _loader = loader; _pageFactoryProvider = pageFactoryProvider; _modelFactoryProvider = modelFactoryProvider; _modelBinderFactory = modelBinderFactory; _razorPageFactoryProvider = razorPageFactoryProvider; _collectionProvider = collectionProvider; _filterProviders = filterProviders.ToArray(); _valueProviderFactories = mvcOptions.Value.ValueProviderFactories.ToArray(); _parameterBinder = parameterBinder; _modelMetadataProvider = modelMetadataProvider; _tempDataFactory = tempDataFactory; _mvcOptions = mvcOptions.Value; _htmlHelperOptions = htmlHelperOptions.Value; _selector = selector; _razorFileSystem = razorFileSystem; _diagnosticSource = diagnosticSource; _logger = loggerFactory.CreateLogger <PageActionInvoker>(); _mapper = mapper; }
public static void WriteDataReaderDisposing( this DiagnosticSource diagnosticSource, DbConnection connection, Guid connectionId, DbDataReader dataReader, int recordsAffected, long startTimestamp, long currentTimestamp) { if (diagnosticSource.IsEnabled(DataReaderDisposing)) { diagnosticSource.Write(DataReaderDisposing, new { Connection = connection, ConnectionId = connectionId, DataReader = dataReader, RecordsAffected = recordsAffected, Timestamp = currentTimestamp, Duration = currentTimestamp - startTimestamp }); } }
/// <summary> /// Fors the application domain. /// </summary> /// <param name="appDomain">The application domain.</param> /// <param name="diagnosticSource">The diagnostic source.</param> /// <returns>Func<IHostBuilder, IRocketHostBuilder>.</returns> public static Func <IHostBuilder, IRocketHostBuilder> ForAppDomain( AppDomain appDomain, DiagnosticSource diagnosticSource = null) { return(builder => { var b = RocketHostExtensions.GetOrCreateBuilder(builder); if (diagnosticSource != null) { b = b.With(diagnosticSource); } var logger = new DiagnosticLogger(b.DiagnosticSource); var assemblyCandidateFinder = new AppDomainAssemblyCandidateFinder(appDomain, logger); var assemblyProvider = new AppDomainAssemblyProvider(appDomain, logger); var scanner = new SimpleConventionScanner(assemblyCandidateFinder, b.ServiceProperties, logger); return RocketHostExtensions.Swap(b, b .With(assemblyCandidateFinder) .With(assemblyProvider) .With(scanner) ); }); }
private void EnsureServices(HttpContext context) { if (_servicesRetrieved) { return; } var services = context.RequestServices; // The IActionContextAccessor is optional. We want to avoid the overhead of using CallContext // if possible. _actionContextAccessor = services.GetService <IActionContextAccessor>(); _actionInvokerFactory = services.GetRequiredService <IActionInvokerFactory>(); _actionSelector = services.GetRequiredService <IActionSelector>(); _diagnosticSource = services.GetRequiredService <DiagnosticSource>(); var factory = services.GetRequiredService <ILoggerFactory>(); _logger = factory.CreateLogger <MvcRouteHandler>(); _servicesRetrieved = true; }
public static void WriteConnectionClosed( this DiagnosticSource diagnosticSource, DbConnection connection, Guid connectionId, Guid instanceId, long startTimestamp, long currentTimestamp, bool async) { if (diagnosticSource.IsEnabled(ConnectionClosed)) { diagnosticSource.Write(ConnectionClosed, new { Connection = connection, ConnectionId = connectionId, InstanceId = instanceId, Timestamp = currentTimestamp, Duration = currentTimestamp - startTimestamp, IsAsync = async }); } }
/// <summary> /// Initializes a new instance of the <see cref="DeveloperExceptionPageMiddleware"/> class /// </summary> /// <param name="next"></param> /// <param name="options"></param> /// <param name="loggerFactory"></param> /// <param name="hostingEnvironment"></param> /// <param name="diagnosticSource"></param> public DeveloperExceptionPageMiddleware( RequestDelegate next, IOptions <DeveloperExceptionPageOptions> options, ILoggerFactory loggerFactory, IHostingEnvironment hostingEnvironment, DiagnosticSource diagnosticSource) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } _next = next; _options = options.Value; _logger = loggerFactory.CreateLogger <DeveloperExceptionPageMiddleware>(); _fileProvider = _options.FileProvider ?? hostingEnvironment.ContentRootFileProvider; _diagnosticSource = diagnosticSource; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, DiagnosticSource diagnosticSource) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
/// <summary> /// Initializes a new instance of the <see cref="DeveloperExceptionPageMiddleware"/> class /// </summary> /// <param name="next"></param> /// <param name="options"></param> public DeveloperExceptionPageMiddleware( RequestDelegate next, ErrorPageOptions options, ILoggerFactory loggerFactory, IApplicationEnvironment appEnvironment, DiagnosticSource diagnosticSource) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } _next = next; _options = options; _logger = loggerFactory.CreateLogger <DeveloperExceptionPageMiddleware>(); _fileProvider = options.FileProvider ?? new PhysicalFileProvider(appEnvironment.ApplicationBasePath); _diagnosticSource = diagnosticSource; }
public static void BeforeActionMethod( this DiagnosticSource diagnosticSource, ActionContext actionContext, IDictionary <string, object> actionArguments, object controller) { Debug.Assert(diagnosticSource != null); Debug.Assert(actionContext != null); Debug.Assert(actionArguments != null); Debug.Assert(controller != null); if (diagnosticSource.IsEnabled("Microsoft.AspNetCore.Mvc.BeforeActionMethod")) { diagnosticSource.Write( "Microsoft.AspNetCore.Mvc.BeforeActionMethod", new { actionContext = actionContext, arguments = actionArguments, controller = controller }); } }
public ExceptionHandlerMiddleware( RequestDelegate next, ILoggerFactory loggerFactory, IOptions <ExceptionHandlerOptions> options, DiagnosticSource diagnosticSource) { _next = next; _options = options.Value; _logger = loggerFactory.CreateLogger <ExceptionHandlerMiddleware>(); _clearCacheHeadersDelegate = ClearCacheHeaders; _diagnosticSource = diagnosticSource; if (_options.ExceptionHandler == null) { if (_options.ExceptionHandlingPath == null) { throw new InvalidOperationException(Resources.FormatExceptionHandlerOptions_NotConfiguredCorrectly()); } else { _options.ExceptionHandler = _next; } } }
/// <summary> /// Fors the dependency context. /// </summary> /// <param name="dependencyContext">The dependency context.</param> /// <param name="diagnosticSource">The diagnostic source.</param> /// <returns>Func<IWebJobsBuilder, System.Object, IRocketFunctionHostBuilder>.</returns> public static Func <IWebJobsBuilder, object, IRocketFunctionHostBuilder> ForDependencyContext( DependencyContext dependencyContext, DiagnosticSource diagnosticSource = null) { return((builder, startupInstance) => { var b = RocketHostExtensions.GetOrCreateBuilder(builder, startupInstance, null); if (diagnosticSource != null) { b = b.With(diagnosticSource); } var logger = new DiagnosticLogger(b.DiagnosticSource); var assemblyCandidateFinder = new DependencyContextAssemblyCandidateFinder(dependencyContext, logger); var assemblyProvider = new DependencyContextAssemblyProvider(dependencyContext, logger); var scanner = new SimpleConventionScanner(assemblyCandidateFinder, b.ServiceProperties, logger); return RocketHostExtensions.Swap(b, b .With(assemblyCandidateFinder) .With(assemblyProvider) .With(scanner) ); }); }
public void DiagnosticSourceStartStop() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; var observer = new TestObserver(); using (listener.Subscribe(observer)) { var arguments = new { args = "arguments" }; var activity = new Activity("activity"); // Test Activity.Stop source.StartActivity(activity, arguments); Assert.Equal(activity.OperationName + ".Start", observer.EventName); Assert.Equal(arguments, observer.EventObject); Assert.NotNull(observer.Activity); Assert.True(DateTime.UtcNow - new TimeSpan(0, 1, 0) <= observer.Activity.StartTimeUtc); Assert.True(observer.Activity.StartTimeUtc <= DateTime.UtcNow); Assert.True(observer.Activity.Duration == TimeSpan.Zero); observer.Reset(); // Test Activity.Stop source.StopActivity(activity, arguments); Assert.Equal(activity.OperationName + ".Stop", observer.EventName); Assert.Equal(arguments, observer.EventObject); // Confirm that duration is set. Assert.NotNull(observer.Activity); Assert.True(TimeSpan.Zero < observer.Activity.Duration); Assert.True(observer.Activity.StartTimeUtc + observer.Activity.Duration < DateTime.UtcNow); } } }