我是 C# 的新手......我們正在使用 Serilog 來記錄 ILogger 日志記錄。對于我的測驗用例,我想將日志檔案名傳遞給 Serilog 檔案接收器,并讓它不將 YYYYMMDD 插入檔案名。到目前為止,我還沒有找到讓 Serilog 不將日期插入日志檔案名的方法。以下是用于說明這一點的簡短代碼片段:
public static class Log
{
private static readonly ConcurrentDictionary<string, Lazy<ILogger>> fileLogs = new ConcurrentDictionary<string, Lazy<ILogger>>();
public static ILogger File(string path)
{
var filePath = string.IsNullOrEmpty(path)
? $"{Assembly.GetEntryAssembly().GetName().Name}_{UnixEpoch.MillisecondsNow}.log"
: path;
var fileInfo = new FileInfo(filePath);
return fileLogs.GetOrAdd(fileInfo.FullName, name => new Lazy<ILogger>(() =>
{
fileInfo.Directory.Create();
return LoggerFactory
.Create(builder => builder.AddFile(filePath))
.CreateLogger("File");
})).Value;
}
}
public void CreateFileLog()
{
var log = Log.File("./test.log");
log.LogInformation("Sample log record.");
}
輸出檔案名將是:./test20220517.log
如何設定 Serilog 檔案接收器,使其不會將日期插入日志檔案名?
uj5u.com熱心網友回復:
檔案接收器支持滾動間隔,這也是影響它寫入檔案的命名約定的因素。您可以將滾動間隔設定為無限,這將無限期地使用同一個檔案,并且似乎不會改變檔案名。
要在 C# 代碼中配置接收器,請在記錄器配置期間呼叫 WriteTo.File():
var log = new LoggerConfiguration() .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); 這會將時間段附加到檔案名,創建一個檔案集,如:
log20180631.txt
log20180701.txt
log20180702.txt
https://github.com/serilog/serilog-sinks-file#rolling-policies
https://github.com/serilog/serilog-sinks-file/blob/dev/src/Serilog.Sinks.File/Sinks/File/RollingIntervalExtensions.cs#L26
請注意,檔案接收器將檔案大小限制為 1 GB,并且將停止寫入日志,直到達到下一個滾動周期以防止磁盤使用問題,因此如果您達到該限制,您的無限日志可能會停止更新。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476746.html
