2
votes

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://docs.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:

  • leave the code as it is in the project template for ASP.NET Core and just change the appsettings.json => no effect
  • explicitly add appsettings.json as config file and configure logging in Program.cs => no logging at all
    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> ();
             });
  • ... configure logging in Startup.ConfigureServices => no effect
    public void ConfigureServices (IServiceCollection services)
    {
      services.AddLogging (config => config.AddConfiguration (Configuration.GetSection("Logging")));
      services.AddControllers ();
    }
1

1 Answers

3
votes

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.