【问题标题】:How do I configure Microsoft.Extensions.Logging.ILogger levels per namespace?如何为每个命名空间配置 Microsoft.Extensions.Logging.ILogger 级别?
【发布时间】:2019-09-26 20:06:14
【问题描述】:

我希望能够独立于 Microsoft.* 来配置像 Microsoft.AspNetCore.Mvc/DataProtection 这样的嵌套级别,这可能吗,如果可以,我该怎么做? 日志记录有效,我看到目前在调试中看到所有内容,但没有排除任何内容。

我将设置等注入到像这样在 Program.cs 中配置的类中

var builder = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory);

builder.AddJsonFile("appsettings.json", true, true);

var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.IsNullOrWhiteSpace(envName))
    builder.AddJsonFile($"appsettings.${envName}.json", true);

builder.AddEnvironmentVariables();
builder.AddCommandLine(args);

var configurationRoot = builder.Build();

new WebHostBuilder()
    .UseKestrel(options =>
        { options.Limits.MaxRequestBodySize = null; })
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseConfiguration(configurationRoot)
    .ConfigureLogging(lb =>
     {
         lb.AddConsole();
         lb.AddDebug();
         lb.SetMinimumLevel(LogLevel.Trace);
     })
    .UseStartup<Startup>()
    .UseIISIntegration()
    .Build()
    .Run();

使用 Startup.cs 注入记录器和配置

public Startup(ILogger<Startup> iLogger, IConfiguration iConfiguration)
{
    _configuration = iConfiguration;
    _logger = iLogger;
    _logger.LogDebug("Configured logger, config and builder.");
}

在 appsettings.json 中配置日志记录

"Logging": {
  "IncludeScopes": true,
  "LogLevel": {
    "Microsoft.AspNetCore.Mvc": "Warning",
    "Microsoft.AspNetCore.DataProtection": "Warning",
    "Default": "Debug"
  }
}

来自 log4j 我会尝试类似上面的方法,但它不起作用,我哪里出错了?

【问题讨论】:

  • 更改您的 appsettings.json 以包含完整的命名空间,例如"Microsoft.AspNetCore.Mvc": "Warning".
  • 我已经尝试过 "LogLevel": { "Microsoft.AspNetCore.Mvc": "Warning", "Microsoft.AspNetCore.DataProtection": "Warning", "Default": "Debug" }"Microsoft.AspNetCore.Mvc.*" 都没有成功。
  • 我认为您不需要builder startup.cs 中的代码,因为配置等由WebHostBuilder.Build() 加载。如果删除它会发生什么?
  • 是的,我意识到它可能属于 Program.cs,因此它可以解析 args 等。我将更新上面的代码。
  • 我建议你看看setup a host 页面,了解program.cs 需要做什么。

标签: c# logging configuration scope .net-core-2.2


【解决方案1】:

您需要阅读how to setup a host 页面以了解需要进入program.cs 代码的内容。这在 .Net Core 2.x 中发生了变化,并且减少了我们需要加载设置和设置日志记录的代码量。

【讨论】:

猜你喜欢
  • 2019-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多