我想在Serilog文件名中使用UTC DateTime。我在appseting.json文件中将以下配置用于serilog。
"Serilog": {
"Using": [],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithProcessId",
"WithThreadId"
],
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "Logs\\log-.json",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact",
"rollingInterval": "Hour",
"shared": true
}
}
]
}
和下面是我用于serilog的program.cs文件代码。
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json").Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception e)
{
Log.Fatal(e, "The Application failed to start correctly");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).UseSerilog()
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
当前,serilog生成的日志文件名为log-2020091323.json,它不是UTC DateTime。 我正在使用asp.net core 3.1。
答案 0 :(得分:1)
您可以使用Install-Package Serilog.Sinks.Map
nuget软件包并在Serilog设置中对其进行配置,以将其存档,如下面的代码示例所示
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
// Ex: UtcDateTime value '202009201010'
.WriteTo.Map("UtcDateTime", DateTime.UtcNow.ToString("yyyyMMddHHmm")
, (UtcDateTime, wt) => wt.File($"logs/log-{UtcDateTime}.txt"))
.CreateLogger();
Log.Information("Hello, Serilog!");
Log.CloseAndFlush(); // Ex: log file name 'log-202009201010.txt'
如果您需要每小时对其进行配置,则此代码每分钟将日志保存到新文件,请使用DateTime.UtcNow.ToString("yyyyMMddHH")
或DateTime.UtcNow.ToString("yyyyMMdd")
天。