在.NET 6中使用默认的WebAPI框架VS2022。我想使用ILogger记录信息,但在调用“var app = builder.Build();
".
是否可以检索“新配置的记录器”buider.Host.ConfigureLogging(logging =>
”来自“WebApplication”对象、WebApplicationBuilder 对象、builder.Host 对象或任何其他对象?
这是program.cs的代码
var builder = WebApplication.CreateBuilder(args);
string insightConnectionString = Environment.GetEnvironmentVariable("APPLICATIONINSIGHTS_CONNECTION_STRING");
builder.Host.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddApplicationInsights(insightConnectionString);
logging.AddConsole();
});
// -----> I want to log information here, before the call of "var app = builder.Build();" <-----
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// -----> And I want to log information here, before the call of "var app = builder.Build();" <-----
var app = builder.Build();
app.Logger.LogInformation("Log some information #1");
//...
app.Logger.LogInformation("Log some information #2");
app.Run();
您可以手动创建LoggerFactory
and Logger
:
using var loggerFactory = LoggerFactory.Create(loggingBuilder => loggingBuilder
.SetMinimumLevel(LogLevel.Trace)
.AddConsole());
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation("Example log message");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)