从 Program.cs 中的 appsettings 获取 Serilog 设置
我正在使用 .Net Core 6 Worker 项目创建 Windows 服务。
我已经添加了正在运行的 Setilog,并且我在 appsettings.json 中有设置。但是,我想在启动和停止服务时写入日志文件。我在 program.cs 中有以下代码,它似乎可以工作,但这并没有使用 appsettings.json 中的设置。是否可以从 appsettings.json 获取设置,而不是将它们添加到此初始 Serilog 设置中?
using Serilog;
using Serilog.Events;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.File("./logs/log-.txt", rollingInterval:RollingInterval.Day)
.CreateBootstrapLogger();
try
{
Log.Information("Starting the Service");
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSerilog()
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
})
.Build();
await host.RunAsync();
return;
}
catch (Exception ex)
{
Log.Fatal(ex, "There was a problem starting the service");
return;
}
finally
{
Log.Information("Service successfully stopped");
Log.CloseAndFlush();
}
I am creating a Windows Service using a .Net Core 6 Worker project.
I have added Setilog which is working, and I have settings in appsettings.json. However, I would like to write to the log file when starting and stopping the service. I have the following code in program.cs, which seems to work, but this does not make use of the settings in appsettings.json. Is it possible to get the settings from appsettings.json instead of adding them to this initial Serilog setup?
using Serilog;
using Serilog.Events;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.File("./logs/log-.txt", rollingInterval:RollingInterval.Day)
.CreateBootstrapLogger();
try
{
Log.Information("Starting the Service");
IHost host = Host.CreateDefaultBuilder(args)
.UseWindowsService()
.UseSerilog()
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
})
.Build();
await host.RunAsync();
return;
}
catch (Exception ex)
{
Log.Fatal(ex, "There was a problem starting the service");
return;
}
finally
{
Log.Information("Service successfully stopped");
Log.CloseAndFlush();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这看起来像是用于两阶段初始化的代码的一部分。
CreateBootstrapLogger()
用于创建一个记录器,该记录器只能在 .NET Core 的日志记录基础结构配置完毕并正常运行之前使用。两阶段初始化文档展示了如何使用
ReadFrom.Configuration
:This looks like part of the code used for two-stage initialization.
CreateBootstrapLogger()
is used to create a logger that can be used only until .NET Core's logging infrastructure is configured and functional.The Two-stage initialization docs show how to read settings using
ReadFrom.Configuration
in the main logger configuration :