netcore2 控制台应用程序在应用程序设置中配置日志级别

netcore2 console app configure loglevel at appsettings

我尝试将记录器添加到我的控制台应用程序。所有配置都正确应用,除了 Logging

Program.cs:

   private static void Main(string[] args)
    {
        var services = new ServiceCollection();
        ConfigureServices(services);

        var serviceProvider = services.BuildServiceProvider();

        serviceProvider.GetService<App>().Run();
        Console.ReadKey();
    }

    private static void ConfigureServices(ServiceCollection services)
    {

        var envName = Environment.GetEnvironmentVariable("MY_ENV") ?? DevelopmentEnvName;

        var configuration = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile("appsettings.json", false)
                            .AddJsonFile($"appsettings.{envName}.json", true, true)
                            .AddEnvironmentVariables()
                            .Build();

        services.AddSingleton(configuration);
        services.AddLogging(builder =>
                            {
                                builder.AddConfiguration(configuration)
                                       .AddConsole()
                                       .AddDebug();
                            });

        ConfigureOptions(services, configuration);

        ConfigureDependencies(services);
    }

App.Run() 我尝试记录调试和信息消息

 public void Run()
 {
    _logger.LogDebug("Debug");
    _logger.LogDebug(_appOptions.Env);   //print nothing

    _logger.LogInformation("Info");
    _logger.LogInformation(_appOptions.Env);  //print Info and debug env lines
 }

appsettings.json:

 {
     "Logging": {
         "IncludeScopes": false,
         "LogLevel": {
              "Default": "Information"
         }
     },
     "AppOptions": {
         "Env": "none"
     }
}

appsettings.Dev.json:

 {
     "Logging": {
         "IncludeScopes": false,
         "LogLevel": {
              "Default": "Debug"
         }
     },
     "AppOptions": {
         "Env": "debug env"
     }
}

我需要更改什么以通过 json 设置控制日志级别?

简短的回答是:您在 AddConfiguration 中错过了 GetSection 调用。

builder.AddConfiguration(configuration.GetSection("Logging"))...

这是我重构你的程序:

ConsoleApp1.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.4" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.2.0" />
  </ItemGroup>

  <ItemGroup>
    <None Update="appsettings.Dev.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

Program.cs

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using System;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var services = new ServiceCollection();
            var envName = Environment.GetEnvironmentVariable("MY_ENV") ?? "Dev";

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile($"appsettings.{envName}.json", false, true)
                                .AddEnvironmentVariables()
                                .Build();

            services.AddSingleton<IConfiguration>(configuration);
            services.AddLogging(builder =>
            {
                builder.ClearProviders();

                builder.AddConfiguration(configuration.GetSection("Logging"))
                       .AddConsole()
                       .AddDebug();
            });

            var provider = services.BuildServiceProvider();
            var config = provider.GetService<IConfiguration>();
            var appOptions = new AppOptions();

            config.GetSection("AppOptions").Bind(appOptions);

            var logger = provider.GetService<ILogger<Program>>();

            logger.LogDebug("Debug");
            logger.LogDebug(appOptions.Env);   //print nothing

            logger.LogInformation("Info");
            logger.LogInformation(appOptions.Env);  //print Info and debug env lines

            Console.ReadLine();
        }
    }

    public class AppOptions
    {
        public string Env { get; set; }
    }
}

appSettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "AppOptions": {
    "Env": "none"
  }
}

appSettings.Dev.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    }
  },
  "AppOptions": {
    "Env": "debug env"
  }
}