'Is there a way to create a Serilog non rolling File Sink that doesn't include the date stamp in the filename?
I'm a newbie to C#... We're using Serilog to record ILogger log records. For my test cases, I'd like to pass a log filename to Serilog File sink and have it not insert YYYYMMDD into the filename. So far, I have not found a way to get Serilog to not insert the date into the log filename. Below are abbreviated code snippets to demonstrate the point:
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.");
}
The output filename will be: ./test20220517.log
How do I setup Serilog File sink so it doesn't insert the date into the log filename?
Solution 1:[1]
The File sink supports a rolling interval, which is also what impacts the naming convention of the file it writes to. You can set a rolling interval of infinite, which will use the same file indefinitely and doesn't appear to alter the file name.
To configure the sink in C# code, call WriteTo.File() during logger configuration:
var log = new LoggerConfiguration() .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); This will append the time period to the filename, creating a file set like:
log20180631.txt
log20180701.txt
log20180702.txt
https://github.com/serilog/serilog-sinks-file#rolling-policies
Please be aware that the file sink limits the file size to 1 GB and will stop writing to the log until the next rolling period is reached to prevent disk usage issues, so if you do reach that limit, your infinite log may cease to update.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adam |
