question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Provide a way to differentiate HttpClient configuration

See original GitHub issue

The newly added IHttpClientFactory integration only exposes HTTP request host and method as labels. While a good start, this is not enough to really identify which (out of several possible) HttpClient configurations/types the metric applies to.

Ideally, we could track the “foo” in services.AddHttpClient("foo", ...) but I did not find any way to get access to this information in our middleware.

Ref: https://github.com/dotnet/aspnetcore/discussions/27018 Ref #248, #229 Ref https://github.com/dotnet/aspnetcore/issues/28455

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:12

github_iconTop GitHub Comments

1reaction
ricardopaivacommented, Jan 28, 2021

The solution I’ve implemented was to create a delegate handler, create the Counter inside it and register that handler in the http client. That way, the counter will be automatically called whenever the http client is used and there’s no need to repeat this code all over the solution.

Here’s my DelegateHandler:

using Microsoft.AspNetCore.Http;
using Prometheus;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace <namespace>
{
    public class HttpClientMetricsHandler : DelegatingHandler
    {
        private readonly IHttpContextAccessor _accessor;

        private static readonly Counter HttpRequestsCount = Metrics
            .CreateCounter("integrationapi_http_requests_to_external_api_total", "Number of http requests to external API.",
                new CounterConfiguration
                {
                    LabelNames = new[] { "method", "endpoint" }
                });

        public HttpClientMetricsHandler(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var context = _accessor.HttpContext;
            HttpRequestsCount.WithLabels(context.Request.Method, context.Request.Path).Inc();
            var response = await base.SendAsync(request, cancellationToken);
            return response;
        }
    }
}

And in my Service I’m register this handler like this:

services.AddTransient<HttpClientMetricsHandler>();

services.AddHttpClient("<my http client name>", client =>
{
    client.BaseAddress = new Uri(configuration["ApiConfig:BaseUrl"]);
    client.DefaultRequestHeaders.Add("Accept", "application/json");
})
    .AddHttpMessageHandler<HttpClientMetricsHandler>()
    .UseHttpClientMetrics();
0reactions
ricardopaivacommented, Jan 29, 2021

It’s working perfectly fine without the IHttpContextAccessor for me. Microsoft uses AddTransient in their example, so I’ll stick with that.

Sorry, I misread your post. I thought you’re still having problems. In my case I only want to know how many calls are being made by the HttpClient. At least for now, I don’t need to know the endpoint so I can exclude that so that I don’t have that problem with high label cardinality.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Advanced Apache HttpClient Configuration
HttpClient configurations for advanced use cases. ... Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies ...
Read more >
Are You Using HttpClient in The Right Way?
The simplest way is to inject the IHttpClient Factory and create a new HttpClient instance from it.
Read more >
Are there differences to consider? http and https with
Hello,. Are there differences to consider? http and https with - HttpClient. c-only-http-and-https-schemes-are-allowed-httpclie.html.
Read more >
HttpClient vs IHttpClientFactory - Henrique Siebert Domareski
HttpClient and IHttpClientFactory can be used in .NET to make HTTP requests and handle HTTP responses from web resources.
Read more >
What is the difference between CloseableHttpClient and ...
CloseableHttpClient is an abstract class which is the base implementation of HttpClient that also implements java.io.Closeable. Here is an ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found