[英]Proper way to do rolling file sink with Serilog from multiple machines
[英]Is there a way to create a Serilog non rolling File Sink that doesn't include the date stamp in the filename?
我是 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 文件接收器,使其不会将日期插入日志文件名?
文件接收器支持滚动间隔,这也是影响它写入文件的命名约定的因素。 您可以将滚动间隔设置为无限,这将无限期地使用同一个文件,并且似乎不会改变文件名。
要在 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
请注意,文件接收器将文件大小限制为 1 GB,并且将停止写入日志,直到达到下一个滚动周期以防止磁盘使用问题,因此如果您确实达到该限制,您的无限日志可能会停止更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.