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

Viewed 1317

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.

1 Answers

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.

Related