Skip to content

Commit 57d96c2

Browse files
Marcin_OsadaMarcin_Osada
Marcin_Osada
authored and
Marcin_Osada
committed
Add OnFileRemoving life cycle hook #106
1 parent 9f8bfc3 commit 57d96c2

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/Serilog.Sinks.File/Sinks/File/FileLifecycleHooks.cs

+14
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,19 @@ public abstract class FileLifecycleHooks
3535
/// <param name="encoding">The encoding to use when reading/writing to the stream.</param>
3636
/// <returns>The <see cref="Stream"/> Serilog should use when writing events to the log file.</returns>
3737
public virtual Stream OnFileOpened(Stream underlyingStream, Encoding encoding) => underlyingStream;
38+
39+
/// <summary>
40+
/// Method called on log files that were marked as obsolete (old) and by default would be deleted.
41+
/// This can be used to move old logs to archive location or send to backup server
42+
/// </summary>
43+
/// <remarks>
44+
/// Executing long synchronous operation may affect responsiveness of application
45+
/// </remarks>
46+
/// <param name="fullPath">Log file full path</param>
47+
/// <returns>
48+
/// Return if Serilog should delete file.
49+
/// Warning: returning false and keeping file in same place will result in calling this method again in next scan for obsolete files
50+
/// </returns>
51+
public virtual bool OnFileRemoving(string fullPath) => true;
3852
}
3953
}

src/Serilog.Sinks.File/Sinks/File/RollingFileSink.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -199,11 +199,12 @@ void ApplyRetentionPolicy(string currentFilePath)
199199
var fullPath = Path.Combine(_roller.LogFileDirectory, obsolete);
200200
try
201201
{
202-
System.IO.File.Delete(fullPath);
202+
if (_hooks == null || _hooks.OnFileRemoving(fullPath))
203+
System.IO.File.Delete(fullPath);
203204
}
204205
catch (Exception ex)
205206
{
206-
SelfLog.WriteLine("Error {0} while removing obsolete log file {1}", ex, fullPath);
207+
SelfLog.WriteLine("Error {0} while processing obsolete log file {1}", ex, fullPath);
207208
}
208209
}
209210
}

0 commit comments

Comments
 (0)