gpt4 book ai didi

asp.net-core - 如何控制 ASP.Net 核心集成测试中的日志级别

转载 作者:行者123 更新时间:2023-12-05 03:57:55 26 4
gpt4 key购买 nike

我正在尝试限制在为 asp.net core 运行集成测试时打印的日志信息量。目前,调试级别的所有内容都被打印出来,它掩盖了有用的信息。我真的很想将其限制为警告及以上。

我正在使用 https://learn.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();
});

停止所有日志记录,但这并不是我真正想要的。

最佳答案

尝试像这样使用AddFilter

builder.ConfigureLogging(o=> {
//o.SetMinimumLevel(LogLevel.Warning);
o.AddFilter(logLevel => logLevel >= LogLevel.Warning);
});

关于asp.net-core - 如何控制 ASP.Net 核心集成测试中的日志级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58318683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com