Remove http client logging handler in ASP.NET Core - c#

When using the HttpClientFactory of .NET Core, is it possible to somehow remove the default LoggingHttpMessageHandler?
I expect something like the below but it doesn't seem to exists
services.AddHttpClient("minos")
.RemoveHttpMessageHandler<LoggingHttpMessageHandler>();

You can configure it in appsettings.json by setting HttpClient's log level to none:
However, this will also enable informational messages from all other
components in the System root namespace. Therefore it may be better to
configure the logging by limiting the configuration to
“System.Net.Http.HttpClient” so that you only add in the messages from
the HTTP requests through clients created via the HttpClientFactory:
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"System.Net.Http.HttpClient": "Information"
}
}
}
https://www.stevejgordon.co.uk/httpclientfactory-asp-net-core-logging

Just for anyone needing this, I had opened an issue on the GitHub repo, and one of the contributors had replied with the following
services.RemoveAll<IHttpMessageHandlerBuilderFilter>();
Just Add this line AFTER the adding of the HttpClient
Make sure to use Microsoft.Extensions.DependencyInjection.Extensions namespace
https://github.com/aspnet/HttpClientFactory/issues/196#issuecomment-432755765

Related

How do I disable Application Insights logging in Microsoft.ApplicationInsights.AspNetCore" Version="2.20.0" and upper?

I have an Asp.Net Core 6 Web Api.
I added Application Insights to it and I have stored the Connection string in a local Secrets.json file as is recommended.
I don't want to send telemetry when in debug while I am still developing the app.
I want to be able to switch it on and off while I develop.
What is the best way to do it?
The first thing that comes to my mind is to adjust the log level in appsettings.Development.json:
"ApplicationInsights": {
"LogLevel": {
"Default": "None"
}
}
I see this question here, but all the answers seem outdated because in the documentation it is recommended to make the configurations in appsettings.json, NOT in the code.
Is there a better alternative for Asp.net Core 6 and Microsoft.ApplicationInsights.AspNetCore" Version="2.20.0" than putting the LogLevel to none?
Edit: I use Secrets.json file as recommended here to store the connection string locally.
You could just not set the instrumentation key in debug/development mode so the telemetry is not send to azure but still visible in the Visual Studio tool

Durable Function Doesn't Correlate Telemetry

According to this developer blog post
Durable functions can be configured (and according the the host.json schema are configured by default) to automatically create and correlate trace telemetry with the W3C tracing protocol.
Currently, my host.json looks like this, and includes the properties shown in the blog.
{
"version": "2.0",
"logging": {
"applicationInsights": {
"httpAutoCollectionOptions": {
"enableW3CDistributedTracing": true
},
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": true
}
},
"logLevel": {
"default": "Information",
"blueprints_webcp_gateway": "Debug"
}
},
"functionTimeout": "00:10:00",
"extensions": {
"queues": {
"visibilityTimeout": "00:00:10",
"batchSize": 4
},
"durableTask": {
"tracing": {
"DistributedTracingProtocol": "W3CTraceContext"
}
}
}
}
Yet, when I go to the Activity Log page in Azure Portal, each orchestrator and activity shows up as its own operation, which is definitely not what I'm expecting to see. Is any additional configuration needed? As far as I can tell, telemetry logged by the durable function host should be correlated by default.
I face same issue and have exactly same results(durable functions traces have different OperationId). Have not found the solution in bigger project I am working on. We have created smaller project to try full end-to-end functionality in more clear environment. I found out that some packages may break the correlation of DF traces f.e. (System.DiagnosticTool >= 4.7.0, MS.Azure.ServiceBus - this SDK is whole deprecated, ...) But there is a light in the end of the tunnel. When I have upgraded each package, target framework and version of Azure functions everything was working correctly in our smaller project. To update everything and make it work in bigger project will be another challenge.

Change logging verbosity level for health check endpoint in ASP.NET Core application

I have an ASP.NET Core application (.NET 5 actually) and it has health check endpoints implemented in a standard way with
services.AddHealthChecks()...
Health checks are working fine. The problem is they are being invoked quite often and hence they generate a lot of logs in our storage.
Service has standard .NET logging mechanisms and defaults in appsettings.json like
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Debug",
"Microsoft.Hosting.Lifetime": "Debug"
}
},
The question is how can I change verbosity level (to Information, for example) for this very heath check (and its implementation inside also, like EF.Core stuff or anything else) while keeping it as Debug in all other places?
Are there any parameters or settings to help with this?
The goal here is to reduce logging storage consumption.
In the settings file:
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Debug",
"Microsoft.Hosting.Lifetime": "Debug"
}
},
You can configure the LogLevel on the namespace level by specifiying "namespace":"LogLevel" inside the LogLevel configuration object.
For instance:
You're seeing lots of dbug: Microsoft.EntityFrameworkCore.Database.Connection[20000] Opening connection to database 'some_db' on server 'tcp://localhost:5432' messages.
As you can tell by the line itself, they're coming from Microsoft.EntityFrameworkCore.Database.Connection object, inside Microsoft.EntityFrameworkCore.Database namespace.
So you could modify the LogLevel for Microsoft, or Microsoft.EntityFrameworkCore or even Microsoft.EntityFrameworkCore.Database namespace to be Information for instance:
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft": "Debug",
"Microsoft.Hosting.Lifetime": "Debug",
"Microsoft.EntityFrameworkCore.Database": "Information"
}
},
Now the line dbug: Microsoft.EntityFrameworkCore.Database.Connection[20000] Opening connection to database 'some_db' on server 'tcp://localhost:5432' won't get logged because its level is Debug and the minimum threshold is configured to be Information.
EDIT
It looks like you're trying to filter based on the context of the request instead of using just the namespace.
AFAIK, aspnetcore logging package is not capable of doing that.
On the other hand, Serilog with a little aid from Serilog.Expressions can filter out the log messages when they originated from specific requests.
From Serilog.Expressions readme file:
Filtering example
Serilog.Expressions adds ByExcluding() and ByIncludingOnly() overloads to the Filter configuration object that accept filter expressions:
Log.Logger = new LoggerConfiguration()
.Filter.ByExcluding("RequestPath like '/health%'")
.CreateLogger();

Turn off HttpClient Logging in .net core 3.1 [duplicate]

When using the HttpClientFactory of .NET Core, is it possible to somehow remove the default LoggingHttpMessageHandler?
I expect something like the below but it doesn't seem to exists
services.AddHttpClient("minos")
.RemoveHttpMessageHandler<LoggingHttpMessageHandler>();
You can configure it in appsettings.json by setting HttpClient's log level to none:
However, this will also enable informational messages from all other
components in the System root namespace. Therefore it may be better to
configure the logging by limiting the configuration to
“System.Net.Http.HttpClient” so that you only add in the messages from
the HTTP requests through clients created via the HttpClientFactory:
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"System.Net.Http.HttpClient": "Information"
}
}
}
https://www.stevejgordon.co.uk/httpclientfactory-asp-net-core-logging
Just for anyone needing this, I had opened an issue on the GitHub repo, and one of the contributors had replied with the following
services.RemoveAll<IHttpMessageHandlerBuilderFilter>();
Just Add this line AFTER the adding of the HttpClient
Make sure to use Microsoft.Extensions.DependencyInjection.Extensions namespace
https://github.com/aspnet/HttpClientFactory/issues/196#issuecomment-432755765

How to set Sentry log level in runtime in .NET Core?

I'm using Sentry with .NET Core which is currently configured as
"SentryOptions": {
"Dsn": "https://...",
"LogLevel": "Error",
"UseRequestFactory": false,
"IsDisabled": false
},
which is loaded in ConfigureServices
serviceCollection.AddTransient<ISentryProvider, SentryProvider>();
serviceCollection.AddOptions().Configure<SentryOptions>(section);
Is there a way to change LogLevel in runtime? I don't want to have to change the appsettings.json and re-deploy just to toggle a config.
Is this a ASP.NET Core app or just .NET Core using generic Host? Are you using the Sentry.AspNetCore integration? That integration does load the Sentry key from appsettings.json automatically so you don't need to touch the DI container for any Sentry configuration. It has docs here.
Sentry.AspNetCore depends on Sentry.Extension.Logging (docs here) so it brings the support to capturing all LogErrors and higher as errors and LogInformation and lower as breadcrumbs (default settings). That means you can use DI to take IHub or ISentryClient anywhere in your app.
Your answer is likely: The specific settings MinimumBreadcrumbLevel and MinimumEventLevel are not reloaded if you change their value in the appsettings.json. For example, you could disable Sentry altogether:
{
"Logging": {
"LogLevel": {
"Sentry": "None", // Disables Sentry
}
}
More details on the ASP.NET docs.
Since this is an integration built on top of the Microsoft.Extensions.Logging package, you can configure the general app's log level and it should affect Sentry's loggers. They don't have auto reload of configuration at a higher level. It's the job of each logging provider to reload the configuration.
A way around this if you'd like to try (undocumented/unsupported): You could resole the IOptions<SentryOptions> from the container (don't register it yourself, the SDK already does that) and change the LogLevels at runtime. The logger instance holds a reference to the options and checks the level at runtime:
https://github.com/getsentry/sentry-dotnet/blob/f5f57545a1f17820d8beda3238ad76fc7ceac7ef/src/Sentry.Extensions.Logging/SentryLogger.cs#L40-L41
Finally, note that if you use Serilog, it changes the logging backend a things are different in that case. Sentry offers a Sentry.Serilog package too.

Categories