public async Task SendAsync_Success()
        {
            var traceContextFixture = _fixture.Create <SpanContext>();

            _mockSpanContextAccessor.Setup(t => t.HasContext()).Returns(true);
            _mockSpanContextAccessor.Setup(t => t.GetContext()).Returns(traceContextFixture);

            _mockSampler.Setup(
                s => s.IsSampled(It.Is <SpanContext>(t => t.TraceId == traceContextFixture.TraceId)))
            .Returns(true);

            _mockDispatcher.Setup(
                d => d.Dispatch(
                    It.IsAny <Span>()));

            var tracingHandler = new TracingHandler(
                new DummyHandler(AssertPropagationHeadersAddedToRequest),
                _mockSpanContextAccessor.Object,
                _mockDispatcher.Object,
                _mockSampler.Object,
                "test");

            var httpClient  = new HttpClient(tracingHandler);
            var httpRequest = new HttpRequestMessage(HttpMethod.Get, new Uri("http://test.com"));
            var response    = await httpClient.SendAsync(httpRequest);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            _mockSpanContextAccessor.VerifyAll();
            _mockSampler.VerifyAll();
            _mockDispatcher.VerifyAll();
        }
Beispiel #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Configuration
            services.AddOptions();
            services.Configure <ApplicationOptions>(Configuration);
            services.AddSingleton(Configuration);

            var config = ConfigurationHelper.Configuration.Get <ApplicationOptions>();

            // Swagger
            services.AddCustomSwagger(Configuration);

            // AppMetrics
            services.AddMetrics();
            services.AddMetricsTrackingMiddleware();

            //Zipkin
            services.AddHttpClient("Tracer").AddHttpMessageHandler(provider =>
                                                                   TracingHandler.WithoutInnerHandler(provider.GetService <IConfiguration>()["applicationName"]));

            // Health Checks
            services.AddHealthChecks();

            //Services
            services.AddScoped <ITokenProvider>(_ => new TokenProvider(config.OpenIdConnectConfiguration));
            services.AddScoped <IFlickrSearchService>(_ => new FlickrSearchService(config.FlickrConfiguration.ApiKey, config.FlickrConfiguration.Secret));
            services.AddScoped <IFlickrDownloadService, FlickrDownloadService>();

            services.AddCustomHttpServices(Configuration);

            services.AddMvc();
        }
Beispiel #3
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllers();
     services.AddHttpClient(ServiceName.ProductService, client =>
     {
         client.BaseAddress = new Uri($"http://localhost:5002");
     })
     //.AddHttpMessageHandler<NacosDiscoveryDelegatingHandler>()
     .AddHttpMessageHandler(provider => TracingHandler.WithoutInnerHandler(ServiceName.OrderService));
 }
Beispiel #4
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     services.AddHttpClient <IExpenseClient, ExpenseClient>(client =>
     {
         client.BaseAddress = new Uri(Configuration.GetConnectionString("Expenses"));
     }).AddHttpMessageHandler(provider => TracingHandler.WithoutInnerHandler("report"));
     services.AddTransient <IToggleClient>(s => new ToggleClient(Configuration.GetConnectionString("Consul"), new ConsulClient(), Configuration.GetConnectionString("ConsulTemplateFile")));
     services.AddLogging(opt =>
     {
         opt.AddConsole();
     });
 }
        public async Task <IHttpActionResult> GetStatus()
        {
            var tracingHandler = new TracingHandler(
                new HttpClientHandler(),
                _spanContextAccessor,
                _dispatcher,
                _sampler,
                "Ping.API-OWIN");

            var httpClient = new HttpClient(tracingHandler);
            var result     = await httpClient.GetAsync(new Uri("http://localhost:5005/api/ping"));

            return(Ok(await result.Content.ReadAsStringAsync()));
        }
Beispiel #6
0
        public async Task ShouldLogTagAnnotations()
        {
            // Arrange
            dispatcher
            .Setup(h => h.Dispatch(It.IsAny <Record>()))
            .Returns(true);

            var returnStatusCode = HttpStatusCode.BadRequest;
            var tracingHandler   = new TracingHandler("abc", null, null, logHttpHost: true)
            {
                InnerHandler = new TestHandler(returnStatusCode)
            };

            httpClient = new HttpClient(tracingHandler);

            // Act
            Trace.Current = Trace.Create();
            var uri    = new Uri("https://abc.com/");
            var method = HttpMethod.Get;
            await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));

            // Assert
            dispatcher
            .Verify(h =>
                    h.Dispatch(It.Is <Record>(m =>
                                              m.Annotation is TagAnnotation &&
                                              ((TagAnnotation)m.Annotation).Key == zipkinCoreConstants.HTTP_HOST &&
                                              ((TagAnnotation)m.Annotation).Value.ToString() == uri.Host)));

            dispatcher
            .Verify(h =>
                    h.Dispatch(It.Is <Record>(m =>
                                              m.Annotation is TagAnnotation &&
                                              ((TagAnnotation)m.Annotation).Key == zipkinCoreConstants.HTTP_PATH &&
                                              ((TagAnnotation)m.Annotation).Value.ToString() == uri.LocalPath)));

            dispatcher
            .Verify(h =>
                    h.Dispatch(It.Is <Record>(m =>
                                              m.Annotation is TagAnnotation &&
                                              ((TagAnnotation)m.Annotation).Key == zipkinCoreConstants.HTTP_METHOD &&
                                              ((TagAnnotation)m.Annotation).Value.ToString() == method.Method)));

            dispatcher
            .Verify(h =>
                    h.Dispatch(It.Is <Record>(m =>
                                              m.Annotation is TagAnnotation &&
                                              ((TagAnnotation)m.Annotation).Key == zipkinCoreConstants.HTTP_STATUS_CODE &&
                                              ((TagAnnotation)m.Annotation).Value.ToString() == ((int)returnStatusCode).ToString())));
        }
Beispiel #7
0
        /// <summary>
        /// 注册分布式追踪埋点配置 zipkin
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddZipkin(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddOptions();
            services.Configure <ZipkinOptions>(configuration);

            //var zipkinOptions = new ZipkinOptions();
            var zipkinOptions = services.BuildServiceProvider().GetRequiredService <IOptions <ZipkinOptions> >().Value;

            services.AddHttpClient(zipkinOptions.HttpClientServiceName)
            .AddHttpMessageHandler(sp => TracingHandler.WithoutInnerHandler(zipkinOptions.ApplicationName));

            services.AddResilienceHttpClient(zipkinOptions.HttpClientServiceName);

            return(services);
        }
        public async Task SendAsync_InnerHandlerException()
        {
            var traceContextFixture = _fixture.Create <SpanContext>();
            var exceptionFixture    = new Exception(_fixture.Create <string>());

            _mockSpanContextAccessor.Setup(t => t.HasContext()).Returns(true);
            _mockSpanContextAccessor.Setup(t => t.GetContext()).Returns(traceContextFixture);

            _mockSampler.Setup(
                s => s.IsSampled(It.Is <SpanContext>(t => t.TraceId == traceContextFixture.TraceId)))
            .Returns(true);

            _mockDispatcher.Setup(
                d => d.Dispatch(
                    It.Is <Span>(s => s.Tags.ContainsKey("error") && s.Tags["error"] == exceptionFixture.Message)));

            var tracingHandler = new TracingHandler(
                new ExceptionDummyHandler(AssertPropagationHeadersAddedToRequest, exceptionFixture),
                _mockSpanContextAccessor.Object,
                _mockDispatcher.Object,
                _mockSampler.Object,
                "test");

            var httpClient  = new HttpClient(tracingHandler);
            var httpRequest = new HttpRequestMessage(HttpMethod.Get, new Uri("http://test.com"));

            try
            {
                await httpClient.SendAsync(httpRequest);
            }
            catch (Exception)
            {
                // ignored
            }

            _mockSpanContextAccessor.VerifyAll();
            _mockSampler.VerifyAll();
            _mockDispatcher.VerifyAll();
        }
Beispiel #9
0
        public async Task ShouldNotLogHttpHost()
        {
            // Arrange
            var returnStatusCode = HttpStatusCode.BadRequest;
            var tracingHandler   = new TracingHandler("abc", null, null, logHttpHost: false)
            {
                InnerHandler = new TestHandler(returnStatusCode)
            };

            httpClient = new HttpClient(tracingHandler);

            dispatcher
            .Setup(h => h.Dispatch(It.Is <Record>(m =>
                                                  m.Annotation is TagAnnotation &&
                                                  ((TagAnnotation)m.Annotation).Key == zipkinCoreConstants.HTTP_HOST)))
            .Throws(new Exception("HTTP_HOST Shouldn't be logged."));

            // Act
            Trace.Current = Trace.Create();
            var uri    = new Uri("https://abc.com/");
            var method = HttpMethod.Get;
            await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
        }
Beispiel #10
0
        public async Task ShouldNotLogStatusCodeOnHttpCodeSuccess()
        {
            // Arrange
            var tracingHandler = new TracingHandler("abc")
            {
                InnerHandler = new TestHandler(HttpStatusCode.OK)
            };

            httpClient = new HttpClient(tracingHandler);


            dispatcher
            .Setup(h => h.Dispatch(It.Is <Record>(m =>
                                                  m.Annotation is TagAnnotation &&
                                                  ((TagAnnotation)m.Annotation).Key == zipkinCoreConstants.HTTP_STATUS_CODE)))
            .Throws(new Exception("HTTP_STATUS_CODE Shouldn't be logged."));

            // Act and assert
            Trace.Current = Trace.Create();
            var uri    = new Uri("https://abc.com/");
            var method = HttpMethod.Get;
            await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, uri));
        }
Beispiel #11
0
 public override void ConfigureServices(IServiceCollection services)
 {
     services.AddHttpClient("Tracer").AddHttpMessageHandler(provider =>
                                                            TracingHandler.WithoutInnerHandler(provider.GetService <IConfiguration>()["applicationName"]));
 }
Beispiel #12
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddHttpClient("Tracer").AddHttpMessageHandler(provider => TracingHandler.WithoutInnerHandler(provider.GetService <IConfiguration>()["AppName"]));
     services.AddControllersWithViews();
 }
Beispiel #13
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddHttpClient("Tracer").AddHttpMessageHandler(provider => TracingHandler.WithoutInnerHandler("Client-App"));
 }