Thomas Lielacher
Thomas Lielacher

Reputation: 1067

Configure logging via config file in .NET Core

We are trying to configure logging for our ASP.NET Core application via a configuration file (the default appsettings.json). The docu says it should be possible (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1), but we can't get it working like expected.

What we have tried so far:

    public static IHostBuilder CreateHostBuilder (string[] args) =>
        Host.CreateDefaultBuilder (args)
            .ConfigureAppConfiguration ((hostingContext, config) =>
            {
              config.Sources.Clear ();

              var env = hostingContext.HostingEnvironment;

              config.AddJsonFile ("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile ($"appsettings.{env.EnvironmentName}.json",
                        optional: true, reloadOnChange: true);

              config.AddEnvironmentVariables ();
            })
            .ConfigureLogging ((hostingContext, logging) =>
            {
              logging.ClearProviders ();

              logging.AddConfiguration (hostingContext.Configuration.GetSection ("Logging"));
            })
            .ConfigureWebHostDefaults (webBuilder =>
             {
               webBuilder.UseStartup<Startup> ();
             });
    public void ConfigureServices (IServiceCollection services)
    {
      services.AddLogging (config => config.AddConfiguration (Configuration.GetSection("Logging")));
      services.AddControllers ();
    }

Upvotes: 6

Views: 10926

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239440

You misunderstood. You can configure logging, i.e. log levels for each provider, filtering out messages, etc., but the actual providers must be assigned in code. In other words, you can configure what messages go to the console via config, but you must still call logging.AddConsole() within ConfigureLogging to add that provider.

The code you have clears all the default providers and adds nothing, so there's no providers at all and hence no logs are generated. You cannot actually add the providers via config, just configure providers that have been added.

Upvotes: 9

Related Questions