首页 > 解决方案 > 控制台应用程序中的 .NET Core 日志记录 - 详细信息级别

问题描述

我正在.NET Core 5.0(VS 2019)中创建一个控制台应用程序。我无法使用各种日志记录配置来实现我的 appsettings.json。它根本行不通。

我在Main()配置appsettings.json的方法开始时有这个:

var dir = Directory.GetCurrentDirectory();

var configurationRoot = new ConfigurationBuilder()
        .SetBasePath(dir) // Microsoft.Extensions.Configuration.Json
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
        .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: false)
        .AddEnvironmentVariables()
        .AddCommandLine(args)
        .Build();

我还做了 ServiceCollection 扩展来配置 ServiceCollection 中的日志记录:

public static IServiceCollection ConfigureApplicationLogging(this IServiceCollection @this, string appName, IConfigurationRoot configurationRoot)
{
    @this.AddLogging(loggingBuilder =>
    {
        loggingBuilder.ClearProviders();
        loggingBuilder.AddConfiguration(configurationRoot);
        loggingBuilder.AddConsole();
        loggingBuilder.AddEventLog(settings =>
        {
            settings.LogName = "Application";
            settings.SourceName = appName;
        });
    });

    return @this;
}

这就是我创建 ServiceCollection 和构建服务的方式:

var serviceCollection = new ServiceCollection();
serviceCollection.ConfigureApplicationLogging("MyApp", configurationRoot)
// ... add other services
var services = serviceCollection.BuildServiceProvider();

以下是我的 appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "Console": {
      "IncludeScopes": true,
      "LogLevel": {
        "Default": "Error",
        "Microsoft": "Error"
      }
    },
    "EventLog": {
      "LogLevel": {
        "Default": "Error",
        "Microsoft": "Error"
      }
    }
  }
}

如您所见,Console 的默认级别设置为错误。我通过ServiceCollection获取记录器:

_logger = services.GetService<ILogger<MyService>>();

现在,如果我执行此代码:

_logger.LogInformation("info");
_logger.LogError("error");

两条消息都打印到控制台,似乎它没有从 appsettings.json 中获取设置。

我在互联网上搜索了很多,但找不到解决方案。

标签: c#.net.net-coreconsole-application

解决方案


通过调用 AddConsole(),您将覆盖来自 AddConfiguration() 调用的设置(使用默认值,因为您没有在 AddConsole 调用中提供任何设置)。


推荐阅读