如何从.net Core 2.2中的appsettings.json中读取日志配置

时间:2019-01-23 06:48:49

标签: c# .net .net-core

在.net Core 2.1中,这样做是

var loggingConfig = configuration.GetSection("Logging");
loggerFactory.AddConsole(loggingConfig);

我已将其移至ConfigureServices,现在我得到

  

错误CS1503参数2:无法从“ Microsoft.Extensions.Configuration.IConfigurationSection”转换为“ System.Action Microsoft.Extensions.Logging.Console.ConsoleLoggerOptions”

1 个答案:

答案 0 :(得分:3)

基于this,您可能必须更改配置应用程序的方式:

var webHost = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 
                      optional: true, reloadOnChange: true);
            config.AddEnvironmentVariables();
        })
        .ConfigureLogging((hostingContext, logging) =>
        {
            logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
        })
        .UseStartup<Startup>()
        .Build();

    webHost.Run();

1 Microsoft ASP.NET Core 2.2日志记录文档