diff --git a/README.md b/README.md index 1feed22..81bcc4e 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,28 @@ Specifying both `rollingInterval` and `rollOnFileSizeLimit` will cause both poli Old files will be cleaned up as per `retainedFileCountLimit` - the default is 31. +### File name with creation timestamp + +For the `fileSizeLimitBytes` parameter, the `dateTimeFormatFileName` parameter can also be set to obtain the creation timestamp in the file name. +Example of possible formats: +- yyyy-MM-dd_HH-mm-ss +- yyyyMMddHHmmss +- dd_MM_yyyy-HH_mm_ss +- ... + +```csharp + .WriteTo.File("log-.txt", fileSizeLimitBytes: 1024, dateTimeFormatFileName: "yyyy-MM-dd_HH-mm-ss") +``` + +If the file limit occurs in the same second as the last file was created, a counter is appended. +This will create a file set like: + +``` +log-2025-06-20_17-16-35.txt +log-2025-06-20_20-43-16.txt +log-2025-06-20_20-43-16_001.txt +``` + ### XML `` configuration To use the file sink with the [Serilog.Settings.AppSettings](https://github.com/serilog/serilog-settings-appsettings) package, first install that package if you haven't already done so: diff --git a/src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs b/src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs index e3e8bcf..1258d17 100644 --- a/src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs +++ b/src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs @@ -14,6 +14,7 @@ using System.ComponentModel; using System.Text; +using System.Text.RegularExpressions; using Serilog.Configuration; using Serilog.Core; using Serilog.Debugging; @@ -33,6 +34,7 @@ public static class FileLoggerConfigurationExtensions const int DefaultRetainedFileCountLimit = 31; // A long month of logs const long DefaultFileSizeLimitBytes = 1L * 1024 * 1024 * 1024; // 1GB const string DefaultOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"; + private static readonly Regex ValidateDateTimeFormatFileName = new Regex("^(?(?:y{4}[_-]?M{2}[_-]?d{2})|(?:d{2}[_-]?M{2}[_-]?y{4}))[_-]?(?