gpt4 book ai didi

c# - serilog 异步接收器在关闭时不会将缓冲区刷新到磁盘

转载 作者:行者123 更新时间:2023-11-30 22:52:28 32 4
gpt4 key购买 nike

当使用带有文件接收器的 serilog 异步接收器(和 buffered = true)时,日志条目在关闭时丢失。我猜这是缓冲区没有刷新到磁盘,即使它正在被调用。我不确定为什么会这样,但我很确定这是异步接收器。如果我将其从配置中删除并单独使用文件接收器,日志将按预期刷新到磁盘。

我有一个相当简单的设置。

程序.cs:

 public class Program
{
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();

public static void Main(string[] args)
{

Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(Configuration)
.CreateLogger();

try
{
Log.Information("Starting the web host");

CreateWebHostBuilder(args).Build().Run();

Log.Information("Shutting down the web host");

}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");

}
finally
{
Log.Information("Closing Log");

Log.CloseAndFlush();
}



}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog();

}

应用设置.json

    {
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Information",
"System": "Warning"
}
}
},
...

appsettings.Development.json

{
"Serilog": {
"WriteTo": [
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "logs/log.txt",
"formatter": "Serilog.Formatting.Json.JsonFormatter",
"rollingInterval": "Day",
"retainedFileCountLimit": 7,
"buffered": true
}
}
]
}
}
]
}
}

如果我在 Log.CloseAndFlush() 行上放置一个断点,它会在关闭时命中它,但它实际上不会将缓冲区刷新到磁盘。

有什么想法吗?

最佳答案

您必须按照以下格式组织您的配置。

"WriteTo": [
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}"
}
}
]
}
},
{
"Name": "Async",
"Args": {
"configure": [
{
"Name": "File",
"Args": {
"path": "logs/log.txt",
"formatter": "Serilog.Formatting.Json.JsonFormatter",
"rollingInterval": "Day",
"retainedFileCountLimit": 7,
"buffered": true
}
}
]
}
}
]

关于c# - serilog 异步接收器在关闭时不会将缓冲区刷新到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58014758/

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