netcore2控制台应用程序在appsettings上配置日志级别

时间:2019-04-09 08:11:22

标签: .net-core .net-core-2.0 .net-core-logging .net-core-configuration

我尝试将记录器添加到控制台应用程序。除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设置控制日志级别吗?

1 个答案:

答案 0 :(得分:1)

简短的答案是:您在GetSection中错过了AddConfiguration通话。

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"
  }
}