Skip to content

Commit

Permalink
Merge pull request #107 from nogard111/OnFileRemovingHook
Browse files Browse the repository at this point in the history
Add OnFileRemoving life cycle hook #106
  • Loading branch information
nblumhardt authored Jul 16, 2019
2 parents 9f8bfc3 + f6d1cff commit 9a0257e
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/Serilog.Sinks.File/Sinks/File/FileLifecycleHooks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ namespace Serilog.Sinks.File
{
/// <summary>
/// Enables hooking into log file lifecycle events.
/// Hooks run synchronously and therefore may affect responsiveness of the application if long operations are performed.
/// </summary>
public abstract class FileLifecycleHooks
{
Expand All @@ -35,5 +36,12 @@ public abstract class FileLifecycleHooks
/// <param name="encoding">The encoding to use when reading/writing to the stream.</param>
/// <returns>The <see cref="Stream"/> Serilog should use when writing events to the log file.</returns>
public virtual Stream OnFileOpened(Stream underlyingStream, Encoding encoding) => underlyingStream;

/// <summary>
/// Called before an obsolete (rolling) log file is deleted.
/// This can be used to copy old logs to an archive location or send to a backup server.
/// </summary>
/// <param name="path">The full path to the file being deleted.</param>
public virtual void OnFileDeleting(string path) {}
}
}
3 changes: 2 additions & 1 deletion src/Serilog.Sinks.File/Sinks/File/RollingFileSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -199,11 +199,12 @@ void ApplyRetentionPolicy(string currentFilePath)
var fullPath = Path.Combine(_roller.LogFileDirectory, obsolete);
try
{
_hooks?.OnFileDeleting(fullPath);
System.IO.File.Delete(fullPath);
}
catch (Exception ex)
{
SelfLog.WriteLine("Error {0} while removing obsolete log file {1}", ex, fullPath);
SelfLog.WriteLine("Error {0} while processing obsolete log file {1}", ex, fullPath);
}
}
}
Expand Down
22 changes: 22 additions & 0 deletions test/Serilog.Sinks.File.Tests/RollingFileSinkTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,28 @@ public void WhenRetentionCountIsSetOldFilesAreDeleted()
});
}

[Fact]
public void WhenRetentionCountAndArchivingHookIsSetOldFilesAreCopiedAndOriginalDeleted()
{
const string archiveDirectory = "OldLogs";
LogEvent e1 = Some.InformationEvent(),
e2 = Some.InformationEvent(e1.Timestamp.AddDays(1)),
e3 = Some.InformationEvent(e2.Timestamp.AddDays(5));

TestRollingEventSequence(
(pf, wt) => wt.File(pf, retainedFileCountLimit: 2, rollingInterval: RollingInterval.Day, hooks: new ArchiveOldLogsHook(archiveDirectory)),
new[] {e1, e2, e3},
files =>
{
Assert.Equal(3, files.Count);
Assert.True(!System.IO.File.Exists(files[0]));
Assert.True(System.IO.File.Exists(files[1]));
Assert.True(System.IO.File.Exists(files[2]));
Assert.True(System.IO.File.Exists(ArchiveOldLogsHook.AddTopDirectory(files[0], archiveDirectory)));
});
}

[Fact]
public void WhenSizeLimitIsBreachedNewFilesCreated()
{
Expand Down
35 changes: 35 additions & 0 deletions test/Serilog.Sinks.File.Tests/Support/ArchiveOldLogsHook.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.IO;
using System.Text;

namespace Serilog.Sinks.File.Tests.Support
{
internal class ArchiveOldLogsHook : FileLifecycleHooks
{
private readonly string _relativeArchiveDir;

public ArchiveOldLogsHook(string relativeArchiveDir)
{
_relativeArchiveDir = relativeArchiveDir;
}

public override void OnFileDeleting(string path)
{
base.OnFileDeleting(path);
var newFile = AddTopDirectory(path, _relativeArchiveDir, true);
System.IO.File.Copy(path, newFile, false);
}

public static string AddTopDirectory(string path, string directoryToAdd, bool createOnNonExist = false)
{
string file = Path.GetFileName(path);
string directory = Path.Combine(Path.GetDirectoryName(path) ?? throw new InvalidOperationException(), directoryToAdd);

if (createOnNonExist && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
return Path.Combine(directory, file);
}
}
}

0 comments on commit 9a0257e

Please sign in to comment.