在 ASP.NET Core 6.0 中使用 Serilog


本文基于Serilog.AspNetCore 4.1.0 版本。 对于之后的版本,Serilog.AspNetCore可能会有针对.NET6更新更加方便读者调用,请读者悉知

疑问

Serilog 在 ASP.NET Core 5 中用的好好的,原项目升级到6也没有问题,可是为什么新建ASP.NET Core 6.0项目,使用不了"UseSerilog()"呢?

解释

因为6使用了"new minimal hosting model",5上面"UseSerilog()"是扩展在"IHostBuilder"上面的,而6上使用的是"WebApplicationBuilder",所以"UseSerilog()"自然就无法使用了,但是"builder.Host"上是"IHostBuilder"类型,可以把"UseSerilog()"用在"builder.Host"上,不建议使用"builder.WebHost"哦。

正确示例

.csproj 文件

	<ItemGroup> <PackageReference Include="Serilog" Version="2.10.0" /> <PackageReference Include="Serilog.AspNetCore" Version="4.1.0" /> <PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" /> <PackageReference Include="Serilog.Sinks.Console" Version="4.0.0" /> <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" /> </ItemGroup> 

Program.cs

using Serilog; const string OUTPUT_TEMPLATE = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} <{ThreadId}> [{Level:u3}] {Message:lj}{NewLine}{Exception}"; Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.WithThreadId() .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: OUTPUT_TEMPLATE) .WriteTo.File("logs/app.txt" , rollingInterval: RollingInterval.Day , outputTemplate: OUTPUT_TEMPLATE) .CreateLogger(); try { Log.Information("Starting web host"); var builder = WebApplication .CreateBuilder(args); builder.Host.UseSerilog(Log.Logger, dispose: true); // Add services to the container. builder.Services.AddControllers(); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseAuthorization(); app.UseSerilogRequestLogging(); app.MapControllers(); app.Run(); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); } finally { Log.CloseAndFlush(); } 

参考

Migrate from ASP.NET Core 5.0 to 6.0
Setting up Serilog in .NET 6

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM