ASP.Net Core LogLevel无法正常工作

Tan*_*ooe 5 c# logging asp.net-core

我无法让记录器按我的意愿工作。我已将日志级别设置为警告,但控制台窗口仍然充满了信息日志。

我在下面提供了一些示例,在Startup.cs或Program.cs中没有配置任何其他内容。

如果需要,我很乐意提供更多信息。

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "ConnectionString"
  },
  "Logging": {
    "IncludeScopes": false, 
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

记录示例:

public class DishRepository : IDishRepository
{
    private readonly ApplicationDbContext _context;
    private readonly ILogger<DishRepository> _logger;

    public DishRepository(ApplicationDbContext context, ILogger<DishRepository> logger)
    {
        _context = context;
        _logger = logger;
    }

    public IEnumerable<Dish> GetAll()
    {
        try
        {
            _logger.LogInformation("GetAll was called");

            return _context.Dishes
                .Include(d => d.Category)
                .Include(d => d.DishIngredients)
                .ThenInclude(di => di.Ingredient)
                .Include(d => d.PizzaType).ToList();
        }
        catch (Exception e)
        {
            _logger.LogError($"Failed to get all dishes: {e}");
            return Enumerable.Empty<Dish>();
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

当我通过VisualStudio运行程序时,得到以下信息:

dotnet控制台

--------这项工作--------

我在https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?tabs=aspnetcore2x上找到了下面的示例,但是它不起作用,但我不明白为什么这样,而不是appsettings.json上面的例子。

appsettings.json

  "Logging": {
"IncludeScopes": false,
"Debug": {
  "LogLevel": {
    "Default": "Warning"
  }
},
"Console": {
  "LogLevel": {
    "PizzeriaAngular": "Warning",
    "Microsoft": "Warning",
    "Microsoft.AspNetCore": "Warning",
    "Microsoft.EntityFrameworkCore": "Information" 
  }
},
"LogLevel": {
  "Default": "Debug"
}
Run Code Online (Sandbox Code Playgroud)

}

Program.cs仍如下所示:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
Run Code Online (Sandbox Code Playgroud)

Nod*_*don 8

有两个配置文件appsettings.json和appsettings.Development.json。并且系统在开发模式下使用它。

  • 当尝试获取“Microsoft.Extensions.Logging.Log4Net.AspNetCore”时,这非常有帮助,我多次检查了他们的示例项目,但它最终被隐藏在 appsettings.Development.json 中,正如这里建议的那样,感谢您的指导。 (3认同)

小智 5

这段代码在方法 ConfigureServices(IServiceCollection services)中的类Startup.cs中对我有用( NetCore 2.x )

services.AddLogging(builder =>
        {
            builder.SetMinimumLevel(LogLevel.Trace);
            builder.AddFilter("Microsoft", LogLevel.Warning);
            builder.AddFilter("System", LogLevel.Error);
            builder.AddFilter("Engine", LogLevel.Warning);
        });
Run Code Online (Sandbox Code Playgroud)