Skip to content
This repository has been archived by the owner on Jul 8, 2024. It is now read-only.

Commit

Permalink
added a overloaded RollingFileAlternate to pass in a prefix for log f…
Browse files Browse the repository at this point in the history
…ile names. (#33)
  • Loading branch information
pradeepneo authored and Andy Wardle committed Apr 27, 2017
1 parent d60d18c commit 942bd96
Show file tree
Hide file tree
Showing 10 changed files with 71 additions and 25 deletions.
6 changes: 6 additions & 0 deletions examples/ExampleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,18 @@ public static void Main(string[] args)
.WriteTo.ColoredConsole()
.CreateLogger();

var loggerWithPrefix = new LoggerConfiguration().MinimumLevel.Verbose()
.WriteTo.RollingFileAlternate(@"C:\logs\serilogtest\", fileSizeLimitBytes: 4096, logFilePrefix:"sample")
.WriteTo.ColoredConsole()
.CreateLogger();

int messageCount = 0;
while (true)
{
for (int i = 0; i < 100; i++)
{
logger.Information("Message: {messageCount}", messageCount);
loggerWithPrefix.Information("Message: {messageCount}", messageCount);
messageCount++;
}
Console.WriteLine("Enter to log 100 logs...");
Expand Down
2 changes: 1 addition & 1 deletion examples/ExampleApp/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
},
"Serilog": "2.0.0",
"Serilog.Sinks.ColoredConsole": "2.0.0",
"Serilog.Sinks.RollingFileAlternate": "2.0"
"Serilog.Sinks.RollingFileAlternate": "2.0.7"
},

"frameworks": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,40 @@ public static LoggerConfiguration RollingFileAlternate(
var sink = new AlternateRollingFileSink(logDirectory, templateFormatter, fileSizeLimitBytes ?? TwoMegabytes, retainedFileCountLimit);
return configuration.Sink(sink, minimumLevel);
}


/// <summary>
/// Creates an alternative implementation of the rolling file sink
/// that rolls files based on their size with an overload to pass log file name prefix
/// </summary>
/// <param name="configuration"><see cref="LoggerSinkConfiguration"/></param>
/// <param name="logDirectory">The names of the directory to be logged</param>
/// <param name="logFilePrefix">The prefix for the log file name.</param>
/// <param name="minimumLevel">Minimum <see cref="LogLevel"/></param>
/// <param name="outputTemplate">The template for substituting logged parameters</param>
/// <param name="formatProvider">A culture specific format provider</param>
/// <param name="fileSizeLimitBytes">The size files should grow up to (default 2MB)</param>
/// <param name="retainedFileCountLimit">The maximum number of log files that will be retained,
/// including the current log file. The default is null which is unlimited.</param>
/// <returns></returns>
public static LoggerConfiguration RollingFileAlternate(
this LoggerSinkConfiguration configuration,
string logDirectory, string logFilePrefix,
LogEventLevel minimumLevel = LevelAlias.Minimum,
string outputTemplate = DefaultOutputTemplate,
IFormatProvider formatProvider = null,
long? fileSizeLimitBytes = null,
int? retainedFileCountLimit = null)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}

var templateFormatter = new MessageTemplateTextFormatter(outputTemplate, formatProvider);
var sink = new AlternateRollingFileSink(logDirectory, templateFormatter, fileSizeLimitBytes ?? TwoMegabytes, retainedFileCountLimit, logFilePrefix: logFilePrefix);
return configuration.Sink(sink, minimumLevel);
}

/// <summary>
/// Creates an alternative implementation of the rolling file sink with
/// an overload to pass an ITextFormatter.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class AlternateRollingFileSink : ILogEventSink, IDisposable
private readonly object syncRoot = new object();
private bool disposed;
private readonly string logDirectory;
private readonly string logFilePrefix;

/// <summary>
/// Construct a <see cref="AlternateRollingFileSink"/>
Expand All @@ -35,18 +36,21 @@ public class AlternateRollingFileSink : ILogEventSink, IDisposable
/// <param name="fileSizeLimitBytes">
/// The size in bytes at which a new file should be created</param>
/// <param name="encoding"></param>
/// <param name="logFilePrefix">The prefix for the log file name.</param>
public AlternateRollingFileSink(
string logDirectory,
ITextFormatter formatter,
long fileSizeLimitBytes,
int? retainedFileCountLimit = null,
Encoding encoding = null)
Encoding encoding = null,
string logFilePrefix = "")
{
this.formatter = formatter;
this.fileSizeLimitBytes = fileSizeLimitBytes;
this.retainedFileCountLimit = retainedFileCountLimit;
this.encoding = encoding;
this.logDirectory = logDirectory;
this.logFilePrefix = string.IsNullOrEmpty(logFilePrefix) ? logFilePrefix : $"{logFilePrefix}-";
this.currentSink = GetLatestSink();
}

Expand Down Expand Up @@ -89,12 +93,12 @@ private SizeLimitedFileSink GetLatestSink()
{
EnsureDirectoryCreated(this.logDirectory);

SizeLimitedLogFileInfo logFileInfo = SizeLimitedLogFileInfo.GetLatestOrNew(DateTime.UtcNow, this.logDirectory);
SizeLimitedLogFileInfo logFileInfo = SizeLimitedLogFileInfo.GetLatestOrNew(DateTime.UtcNow, this.logDirectory, this.logFilePrefix);

return new SizeLimitedFileSink(
this.formatter,
this.logDirectory,
new SizeLimitedLogFileDescription(logFileInfo, this.fileSizeLimitBytes),
new SizeLimitedLogFileDescription(logFileInfo, this.fileSizeLimitBytes, this.logFilePrefix),
this.encoding);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@ internal class SizeLimitedLogFileDescription
{
public readonly long SizeLimitBytes;
public readonly SizeLimitedLogFileInfo LogFileInfo;
public readonly string LogFilePrefix;

public SizeLimitedLogFileDescription(SizeLimitedLogFileInfo logFileInfo, long sizeLimitBytes)
public SizeLimitedLogFileDescription(SizeLimitedLogFileInfo logFileInfo, long sizeLimitBytes, string logFilePrefix)
{
LogFileInfo = logFileInfo;
SizeLimitBytes = sizeLimitBytes;
LogFilePrefix = logFilePrefix;
}

public string FileName { get { return LogFileInfo.FileName; } }

internal SizeLimitedLogFileDescription Next()
{
return new SizeLimitedLogFileDescription(this.LogFileInfo.Next(), this.SizeLimitBytes);
return new SizeLimitedLogFileDescription(this.LogFileInfo.Next(LogFilePrefix), this.SizeLimitBytes, LogFilePrefix);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,29 @@ internal class SizeLimitedLogFileInfo
internal string FileName { get; private set; }
internal DateTime Date { get; private set; }

public SizeLimitedLogFileInfo(DateTime date, uint sequence)
public SizeLimitedLogFileInfo(DateTime date, uint sequence, string logFilePrefix)
{
this.Date = date;
this.Sequence = sequence;
this.FileName = String.Format("{0}-{1}.log", date.ToString(DateFormat), sequence.ToString(NumberFormat));
this.FileName = $"{logFilePrefix}{date.ToString(DateFormat)}-{sequence.ToString(NumberFormat)}.log";
}

public SizeLimitedLogFileInfo Next()
public SizeLimitedLogFileInfo Next(string logFilePrefix)
{
DateTime now = DateTime.UtcNow;
if (this.Date.Date != now.Date)
{
return new SizeLimitedLogFileInfo(now, 1);
return new SizeLimitedLogFileInfo(now, 1, logFilePrefix);
}

return new SizeLimitedLogFileInfo(now, this.Sequence + 1);
return new SizeLimitedLogFileInfo(now, this.Sequence + 1, logFilePrefix);
}

internal static SizeLimitedLogFileInfo GetLatestOrNew(DateTime date, string logDirectory)
internal static SizeLimitedLogFileInfo GetLatestOrNew(DateTime date, string logDirectory, string logFilePrefix)
{
string pattern = date.ToString(DateFormat) + @"-(\d{5}).log";
string pattern = $"{logFilePrefix}{date.ToString(DateFormat)}" + @"-(\d{5}).log";

var logFileInfo = new SizeLimitedLogFileInfo(date, 1);
var logFileInfo = new SizeLimitedLogFileInfo(date, 1, logFilePrefix);

foreach (var filePath in Directory.GetFiles(logDirectory))
{
Expand All @@ -46,7 +46,7 @@ internal static SizeLimitedLogFileInfo GetLatestOrNew(DateTime date, string logD

if (sequence > logFileInfo.Sequence)
{
logFileInfo = new SizeLimitedLogFileInfo(date, sequence);
logFileInfo = new SizeLimitedLogFileInfo(date, sequence, logFilePrefix);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class LogFileInfoTests
[Fact]
public void RendersCorrectlyWithDateAndSequenceNumber()
{
var sut = new SizeLimitedLogFileInfo(new DateTime(2015, 01, 15), 77);
var sut = new SizeLimitedLogFileInfo(new DateTime(2015, 01, 15), 77, string.Empty);
Assert.Equal(sut.FileName, "20150115-00077.log");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>

<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>060cf269-c2bf-4529-8395-bde3c92fd151</ProjectGuid>
Expand All @@ -13,9 +12,11 @@
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
</PropertyGroup>

<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ public class SizeLimitReachedTests
public void ReachedWhenAmountOfCharactersWritten()
{
var formatter = new RawFormatter();
var components = new SizeLimitedLogFileInfo(new DateTime(2015, 01, 15), 0);
var logFile = new SizeLimitedLogFileDescription(components, 1);
var components = new SizeLimitedLogFileInfo(new DateTime(2015, 01, 15), 0, string.Empty);
var logFile = new SizeLimitedLogFileDescription(components, 1, string.Empty);
using (var str = new MemoryStream())
using (var wr = new StreamWriter(str, Encoding.UTF8))
using (var sink = new SizeLimitedFileSink(formatter, logFile, wr))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public void SequenceIsOneWhenNoPreviousFile()
{
using (var dir = new TestDirectory())
{
var latest = SizeLimitedLogFileInfo.GetLatestOrNew(new DateTime(2015, 01, 15), dir.LogDirectory);
var latest = SizeLimitedLogFileInfo.GetLatestOrNew(new DateTime(2015, 01, 15), dir.LogDirectory, string.Empty);
Assert.Equal<uint>(latest.Sequence, 1);
}
}
Expand All @@ -31,7 +31,7 @@ public void SequenceIsEqualToTheHighestFileWritten()
dir.CreateLogFile(date, 1);
dir.CreateLogFile(date, 2);
dir.CreateLogFile(date, 3);
var latest = SizeLimitedLogFileInfo.GetLatestOrNew(new DateTime(2015, 01, 15), dir.LogDirectory);
var latest = SizeLimitedLogFileInfo.GetLatestOrNew(new DateTime(2015, 01, 15), dir.LogDirectory, string.Empty);
Assert.Equal<uint>(latest.Sequence, 3);
}
}
Expand Down Expand Up @@ -74,7 +74,7 @@ public void CreateLogFile(DateTime date, uint sequence)
{
lock (_lock)
{
string fileName = Path.Combine(this.folder, new SizeLimitedLogFileInfo(date, sequence).FileName);
string fileName = Path.Combine(this.folder, new SizeLimitedLogFileInfo(date, sequence, string.Empty).FileName);
File.Create(fileName).Dispose(); // touch
}
}
Expand Down

0 comments on commit 942bd96

Please sign in to comment.