在.NET控制台应用程序中配置日志记录级别

3

我正在编写一个 .net 控制台应用程序,我有一个设置日志级别的问题。我创建了带有“Logging”部分的 appsettings 文件,但它不起作用 - 我将级别设置为错误,但仍然得到信息级别的错误。

我知道 appsettings 正确加载,因为其余设置已正确绑定。

我的主类:

static async Task Main(string[] args)
{
    await new HostBuilder()
        .ConfigureAppConfiguration((context, config) =>
        {
            config.AddJsonFile("appsettings.json", true);
            config.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true, true);
            config.AddEnvironmentVariables();
            if (args != null)
                config.AddCommandLine(args);
        })
        .ConfigureServices((_, services) =>
            services.AddMagic())
        .RunConsoleAsync();
}

我的appsettings.json文件内容如下:

{
  "Postgres": {
    "Host": "localhost",
    "DatabaseName": "db",
    "Username": "admin",
    "Password": "admin",
    "MinLogLevel": "Error"
  },
  "Redis": {
    "Host": "localhost:6379",
    "Password": null
  },
  "Logging": {
    "LogLevel": {
      "Default": "Error"
    }
  }
}

你的appsettings文件的其余部分是什么样子的?只是为了确认日志部分是否放在正确的位置。 - Code Stranger
我刚刚将整个appsettings文件添加到问题中,而不仅仅是日志部分。 - Kraver
1个回答

7

添加直接登录配置解决了我的问题:

.ConfigureLogging((context, config) =>                    
    config.AddConfiguration(context.Configuration.GetSection("Logging")))

整个主函数:

static async Task Main(string[] args)
{
    await new HostBuilder()
        .ConfigureAppConfiguration((context, config) =>
        {
            config.AddEnvironmentVariables();
            config.AddJsonFile("appsettings.json", true, true);
            config.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true, true);
            if (args != null)
                config.AddCommandLine(args);
        })
        .ConfigureLogging((context, config) =>
            config.AddConfiguration(context.Configuration.GetSection("Logging")))
        .ConfigureServices(services =>
            services.AddMagic())
        .RunConsoleAsync();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接