官網(wǎng)的文檔有誤乌庶,所以做一下記錄,避免入坑。
https://github.com/serilog/serilog/wiki/Enrichment#the-logcontext
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
// .Enrich.WithProperty("MyVersion", "1.0.2")
.Enrich.FromLogContext()
.CreateLogger();
try
{
Log.Information("No contextual properties");
using (LogContext.PushProperty("A", "A_Value"))
{
Log.Information("Carries property {A} = 1");
using (LogContext.PushProperty("A", "A_Value2"))
using (LogContext.PushProperty("B", "B_Value"))
{
Log.Information("Carries {A} = 2 and {B} = 1");
}
Log.Information("Carries property {A} = 1, again");
}
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
Log.CloseAndFlush(); // 釋放資源
}
}
運(yùn)行結(jié)果: