gpt4 book ai didi

.net - ASP.net : How to log from within CreateHostBuilder()?

转载 作者:行者123 更新时间:2023-12-05 01:10:22 34 4
gpt4 key购买 nike

我有一个 ASP.net Core 3.1 Web 应用程序。在 Program.cs 类中,我实现了类似这样的 CreateHostBuilder() 静态方法:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host
.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
try
{
// do some configuration work that might fail
}
catch (Exception ex)
{
// how can I write to a log from here?
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}

如果在配置应用程序时抛出异常,当我捕获它时如何使用 ILogger 记录它?

最佳答案

微软的“Logging in .NET Core and ASP.NET Core”文档文章说:

Logging during host construction isn't directly supported. However, a separate logger can be used.

他们继续使用 Serilog 给出这个例子:

public static IHostBuilder CreateHostBuilder(string[] args)
{
var builtConfig = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddCommandLine(args)
.Build();

Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File(builtConfig["Logging:FilePath"])
.CreateLogger();

try
{
return Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
services.AddRazorPages();
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddConfiguration(builtConfig);
})
.ConfigureLogging(logging =>
{
logging.AddSerilog();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
catch (Exception ex)
{
Log.Fatal(ex, "Host builder error");

throw;
}
finally
{
Log.CloseAndFlush();
}
}

关于.net - ASP.net : How to log from within CreateHostBuilder()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64152220/

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