1

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?

Ed Thomas
  • 13
  • 2

1 Answers1

0

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

https://github.com/serilog/serilog-sinks-file/blob/dev/src/Serilog.Sinks.File/Sinks/File/RollingIntervalExtensions.cs#L26

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.

Adam
  • 3,339
  • 1
  • 10
  • 15
  • No problem! If this solved your issue, you can mark the answer as accepted for future searchers. – Adam May 17 '22 at 21:34