我正在尝试限制对asp.net core进行集成测试时打印的日志信息的数量。当前,所有打印到调试级别的信息都会被打印出来,并且模糊了有用的信息。我真的很想将其限制为警告以上。
我正在使用https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#customize-webapplicationfactory处的示例运行集成测试>
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup: class { protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { // Create a new service provider. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Add a database context (ApplicationDbContext) using an in-memory // database for testing. services.AddDbContext<ApplicationDbContext>(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); options.UseInternalServiceProvider(serviceProvider); }); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (ApplicationDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService<ApplicationDbContext>(); var logger = scopedServices .GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>(); // Ensure the database is created. db.Database.EnsureCreated(); try { // Seed the database with test data. Utilities.InitializeDbForTests(db); } catch (Exception ex) { logger.LogError(ex, "An error occurred seeding the database. Error: {Message}", ex.Message); } } }); } }
日志:
dbug: Microsoft.AspNetCore.Hosting.Internal.WebHost[4] Hosting started dbug: Microsoft.AspNetCore.Hosting.Internal.WebHost[0] Loaded hosting startup assembly BackEnd.Api info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1] Request starting HTTP/2.0 GET http://localhost/test dbug: Microsoft.AspNetCore.HostFiltering.HostFilteringMiddleware[0] Wildcard detected, all requests with hosts will be allowed. ...lots more dbug logs...
我在
ConfigureWebHost
中尝试过的事情:
builder.ConfigureLogging(o => { o.SetMinimumLevel(LogLevel.Warning); });
没有效果。我无法提出其他任何有效果的级别和过滤器组合。
builder.ConfigureLogging(o => { o.ClearProviders(); });
停止所有日志记录,但这并不是我真正想要的。
我正在尝试限制对asp.net core进行集成测试时打印的日志信息的数量。当前,所有打印到调试级别的内容都会被打印出来,并且掩盖了有用的内容...
尝试使用AddFilter
之类
我为我的案件解决了这个问题。在我正在测试的asp.net核心应用程序的appsettings.json
中,以下配置: