在 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

聲明

本文采用知識共享署名-非商業性使用-相同方式共享 2.5 中國大陸許可協議進行許可,發表在CSDN博客園,歡迎讀者轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接!請讀者/爬蟲們尊重版權


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM