Skip to content

File name with creation timestamp (a part of the isssue #243) #352

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<appSettings>` 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:
Expand Down
47 changes: 38 additions & 9 deletions src/Serilog.Sinks.File/FileLoggerConfigurationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;
using Serilog.Configuration;
using Serilog.Core;
using Serilog.Debugging;
Expand All @@ -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("^(?<date>(?:y{4}[_-]?M{2}[_-]?d{2})|(?:d{2}[_-]?M{2}[_-]?y{4}))[_-]?(?<time>H{2}[_-]?m{2}[_-]?s{2})$", RegexOptions.Compiled);

/// <summary>
/// Write log events to the specified file.
Expand Down Expand Up @@ -164,7 +166,7 @@ public static LoggerConfiguration File(
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="formatter">A formatter, such as <see cref="JsonFormatter"/>, to convert the log events into
/// text for the file. If control of regular text formatting is required, use the other
/// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?, RollingInterval, bool, int?, Encoding, FileLifecycleHooks, TimeSpan?)"/>
/// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?, RollingInterval, bool, int?, Encoding, FileLifecycleHooks, TimeSpan?, string?)"/>
/// and specify the outputTemplate parameter instead.
/// </param>
/// <param name="path">Path to the file.</param>
Expand Down Expand Up @@ -236,6 +238,12 @@ public static LoggerConfiguration File(
/// Must be greater than or equal to <see cref="TimeSpan.Zero"/>.
/// Ignored if <paramref see="rollingInterval"/> is <see cref="RollingInterval.Infinite"/>.
/// The default is to retain files indefinitely.</param>
/// <param name="dateTimeFormatFileName">This parameter ensures that a timestamp with date and time is set at the end of the file name.<br/> It only works in conjunction with a set file size limit. A rolling interval must not be set.<br/>
/// Examples of valid formats:<br/>
/// yyyy-MM-dd_HH-mm-ss<br/>
/// yyyyMMddHHmmss<br/>
/// dd_MM_yyyy-HH_mm_ss<br/>
/// ... </param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="sinkConfiguration"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="path"/> is <code>null</code></exception>
Expand All @@ -262,7 +270,8 @@ public static LoggerConfiguration File(
int? retainedFileCountLimit = DefaultRetainedFileCountLimit,
Encoding? encoding = null,
FileLifecycleHooks? hooks = null,
TimeSpan? retainedFileTimeLimit = null)
TimeSpan? retainedFileTimeLimit = null,
string? dateTimeFormatFileName = null)
{
if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration));
if (path == null) throw new ArgumentNullException(nameof(path));
Expand All @@ -271,7 +280,7 @@ public static LoggerConfiguration File(
var formatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
return File(sinkConfiguration, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes,
levelSwitch, buffered, shared, flushToDiskInterval,
rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding, hooks, retainedFileTimeLimit);
rollingInterval, rollOnFileSizeLimit, retainedFileCountLimit, encoding, hooks, retainedFileTimeLimit, dateTimeFormatFileName);
}

/// <summary>
Expand All @@ -280,7 +289,7 @@ public static LoggerConfiguration File(
/// <param name="sinkConfiguration">Logger sink configuration.</param>
/// <param name="formatter">A formatter, such as <see cref="JsonFormatter"/>, to convert the log events into
/// text for the file. If control of regular text formatting is required, use the other
/// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?, RollingInterval, bool, int?, Encoding, FileLifecycleHooks, TimeSpan?)"/>
/// overload of <see cref="File(LoggerSinkConfiguration, string, LogEventLevel, string, IFormatProvider, long?, LoggingLevelSwitch, bool, bool, TimeSpan?, RollingInterval, bool, int?, Encoding, FileLifecycleHooks, TimeSpan?, string?)"/>
/// and specify the outputTemplate parameter instead.
/// </param>
/// <param name="path">Path to the file.</param>
Expand All @@ -306,6 +315,12 @@ public static LoggerConfiguration File(
/// Must be greater than or equal to <see cref="TimeSpan.Zero"/>.
/// Ignored if <paramref see="rollingInterval"/> is <see cref="RollingInterval.Infinite"/>.
/// The default is to retain files indefinitely.</param>
/// <param name="dateTimeFormatFileName">This parameter ensures that a timestamp with date and time is set at the end of the file name.<br/> It only works in conjunction with a set file size limit. A rolling interval must not be set.<br/>
/// Examples of valid formats:<br/>
/// yyyy-MM-dd_HH-mm-ss<br/>
/// yyyyMMddHHmmss<br/>
/// dd_MM_yyyy-HH_mm_ss<br/>
/// ... </param>
/// <returns>Configuration object allowing method chaining.</returns>
/// <exception cref="ArgumentNullException">When <paramref name="sinkConfiguration"/> is <code>null</code></exception>
/// <exception cref="ArgumentNullException">When <paramref name="formatter"/> is <code>null</code></exception>
Expand All @@ -331,15 +346,16 @@ public static LoggerConfiguration File(
int? retainedFileCountLimit = DefaultRetainedFileCountLimit,
Encoding? encoding = null,
FileLifecycleHooks? hooks = null,
TimeSpan? retainedFileTimeLimit = null)
TimeSpan? retainedFileTimeLimit = null,
string? dateTimeFormatFileName = null)
{
if (sinkConfiguration == null) throw new ArgumentNullException(nameof(sinkConfiguration));
if (formatter == null) throw new ArgumentNullException(nameof(formatter));
if (path == null) throw new ArgumentNullException(nameof(path));

return ConfigureFile(sinkConfiguration.Sink, formatter, path, restrictedToMinimumLevel, fileSizeLimitBytes, levelSwitch,
buffered, false, shared, flushToDiskInterval, encoding, rollingInterval, rollOnFileSizeLimit,
retainedFileCountLimit, hooks, retainedFileTimeLimit);
retainedFileCountLimit, hooks, retainedFileTimeLimit, dateTimeFormatFileName);
}

/// <summary>
Expand Down Expand Up @@ -494,7 +510,7 @@ public static LoggerConfiguration File(
if (path == null) throw new ArgumentNullException(nameof(path));

return ConfigureFile(sinkConfiguration.Sink, formatter, path, restrictedToMinimumLevel, null, levelSwitch, false, true,
false, null, encoding, RollingInterval.Infinite, false, null, hooks, null);
false, null, encoding, RollingInterval.Infinite, false, null, hooks, null, null);
}

static LoggerConfiguration ConfigureFile(
Expand All @@ -513,7 +529,8 @@ static LoggerConfiguration ConfigureFile(
bool rollOnFileSizeLimit,
int? retainedFileCountLimit,
FileLifecycleHooks? hooks,
TimeSpan? retainedFileTimeLimit)
TimeSpan? retainedFileTimeLimit,
string? dateTimeFormatFileName)
{
if (addSink == null) throw new ArgumentNullException(nameof(addSink));
if (formatter == null) throw new ArgumentNullException(nameof(formatter));
Expand All @@ -523,14 +540,26 @@ static LoggerConfiguration ConfigureFile(
if (retainedFileTimeLimit.HasValue && retainedFileTimeLimit < TimeSpan.Zero) throw new ArgumentException("Negative value provided; retained file time limit must be non-negative.", nameof(retainedFileTimeLimit));
if (shared && buffered) throw new ArgumentException("Buffered writes are not available when file sharing is enabled.", nameof(buffered));
if (shared && hooks != null) throw new ArgumentException("File lifecycle hooks are not currently supported for shared log files.", nameof(hooks));
if (dateTimeFormatFileName != null)
{
if(rollingInterval != RollingInterval.Infinite)
throw new ArgumentException($"Argument '{nameof(dateTimeFormatFileName)}' are not supported for rolling interval.");

if(fileSizeLimitBytes == null)
throw new ArgumentException($"Argument '{nameof(dateTimeFormatFileName)}' is not supported, if the argument '{nameof(fileSizeLimitBytes)}' is null.");

Match match = ValidateDateTimeFormatFileName.Match(dateTimeFormatFileName);
if(!match.Success || String.IsNullOrEmpty(match.Groups["date"].Value) || String.IsNullOrEmpty(match.Groups["time"].Value))
throw new ArgumentException($"Argument '{nameof(dateTimeFormatFileName)}' does not have the expected format.");
}

ILogEventSink sink;

try
{
if (rollOnFileSizeLimit || rollingInterval != RollingInterval.Infinite)
{
sink = new RollingFileSink(path, formatter, fileSizeLimitBytes, retainedFileCountLimit, encoding, buffered, shared, rollingInterval, rollOnFileSizeLimit, hooks, retainedFileTimeLimit);
sink = new RollingFileSink(path, formatter, fileSizeLimitBytes, retainedFileCountLimit, encoding, buffered, shared, rollingInterval, rollOnFileSizeLimit, hooks, retainedFileTimeLimit, dateTimeFormatFileName);
}
else
{
Expand Down
69 changes: 51 additions & 18 deletions src/Serilog.Sinks.File/Sinks/File/PathRoller.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2013-2016 Serilog Contributors
// Copyright 2013-2016 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -21,16 +21,19 @@ sealed class PathRoller
{
const string PeriodMatchGroup = "period";
const string SequenceNumberMatchGroup = "sequence";
const string DateTimeMatchGroup = "datetime";

readonly string _directory;
readonly string _filenamePrefix;
readonly string _filenameSuffix;
readonly Regex _filenameMatcher;
readonly Regex _filenameMatcher = null!;

readonly RollingInterval _interval;
readonly string _periodFormat;
string _dateTimeFormat = String.Empty;
public bool UseDateTimeFormat => !String.IsNullOrEmpty(_dateTimeFormat);

public PathRoller(string path, RollingInterval interval)
public PathRoller(string path, RollingInterval interval, string? dateTimeFormatFileName = null)
{
if (path == null) throw new ArgumentNullException(nameof(path));
_interval = interval;
Expand All @@ -43,14 +46,29 @@ public PathRoller(string path, RollingInterval interval)
_directory = Path.GetFullPath(pathDirectory);
_filenamePrefix = Path.GetFileNameWithoutExtension(path);
_filenameSuffix = Path.GetExtension(path);
_filenameMatcher = new Regex(
"^" +
Regex.Escape(_filenamePrefix) +
"(?<" + PeriodMatchGroup + ">\\d{" + _periodFormat.Length + "})" +
"(?<" + SequenceNumberMatchGroup + ">_[0-9]{3,}){0,1}" +
Regex.Escape(_filenameSuffix) +
"$",
RegexOptions.Compiled);

if (dateTimeFormatFileName != null)
{
Regex dateTimeFormatCheck = new Regex(@"^([_\-a-zA-Z]{14,19})$");
Match match = dateTimeFormatCheck.Match(dateTimeFormatFileName);
if (match.Groups.Count == 2)
{
_dateTimeFormat = match.Groups[1].Value;
_filenameMatcher = new Regex($@"^{Regex.Escape(_filenamePrefix)}(?<{DateTimeMatchGroup}>[\-_0-9]{{14,19}})(?<{SequenceNumberMatchGroup}>_[0-9]{{3,}})?{Regex.Escape(_filenameSuffix)}$", RegexOptions.Compiled);
}
}

if (!UseDateTimeFormat)
{
_filenameMatcher = new Regex(
"^" +
Regex.Escape(_filenamePrefix) +
"(?<" + PeriodMatchGroup + ">\\d{" + _periodFormat.Length + "})" +
"(?<" + SequenceNumberMatchGroup + ">_[0-9]{3,}){0,1}" +
Regex.Escape(_filenameSuffix) +
"$",
RegexOptions.Compiled);
}

DirectorySearchPattern = $"{_filenamePrefix}*{_filenameSuffix}";
}
Expand All @@ -61,6 +79,16 @@ public PathRoller(string path, RollingInterval interval)

public void GetLogFilePath(DateTime date, int? sequenceNumber, out string path)
{
if (UseDateTimeFormat)
{
string seqNo = sequenceNumber != null
? $"_{sequenceNumber.Value.ToString("000", CultureInfo.InvariantCulture)}"
: String.Empty;

path = Path.Combine(_directory, $"{_filenamePrefix}{date.ToString(_dateTimeFormat)}{seqNo}{_filenameSuffix}");
return;
}

var currentCheckpoint = GetCurrentCheckpoint(date);

var tok = currentCheckpoint?.ToString(_periodFormat, CultureInfo.InvariantCulture) ?? "";
Expand Down Expand Up @@ -88,16 +116,21 @@ public IEnumerable<RollingLogFile> SelectMatches(IEnumerable<string> filenames)
}

DateTime? period = null;
var periodGroup = match.Groups[PeriodMatchGroup];
if (periodGroup.Captures.Count != 0)
Group? periodGroup = null;
if (UseDateTimeFormat)
periodGroup = match.Groups[DateTimeMatchGroup];
else
periodGroup = match.Groups[PeriodMatchGroup];

if (periodGroup != null && periodGroup.Captures.Count != 0)
{
var dateTimePart = periodGroup.Captures[0].Value;
if (DateTime.TryParseExact(
dateTimePart,
_periodFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var dateTime))
dateTimePart,
_periodFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out var dateTime))
{
period = dateTime;
}
Expand Down
Loading