This project has been developed to extend Serilog buit-in RollingFile, to limit the log files based on size, also purge old files to free up disk space.
https://www.nuget.org/packages/Serilog.Sinks.RollingFile.Extension/
PM> Install-Package Serilog.Sinks.RollingFile.Extension
new LoggerConfiguration()
.WriteTo.SizeRollingFile(@"C:\temp\log.txt",
retainedFileDurationLimit: TimeSpan.FromDays(2),
fileSizeLimitBytes: 1024 * 1024 * 10) // 10MB
.CreateLogger();
<appSettings>
<add key="serilog:using:SizeRollingFile" value="Serilog.Sinks.RollingFile.Extension"/>
<add key="serilog:write-to:SizeRollingFile.pathFormat" value="C:\temp\log.txt"/>
<add key="serilog:write-to:SizeRollingFile.fileSizeLimitBytes" value="10485760"/>
<add key="serilog:write-to:SizeRollingFile.retainedFileDurationLimit" value="2.00:00:00"/>
</appSettings>
To use the file sink with Microsoft.Extensions.Configuration, for example with ASP.NET Core or .NET Core, use the Serilog.Settings.Configuration package. First install that package if you have not already done so:
Install-Package Serilog.Settings.Configuration
Instead of configuring the file directly in code, call ReadFrom.Configuration()
:
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
your appsettings.json
file should look like this :
{
"Serilog": {
"Using": [ "Serilog.Sinks.RollingFile.Extension" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "SizeRollingFile",
"Args": {
"pathFormat": "C:\\temp\\log.txt",
"fileSizeLimitBytes ": 200,
"retainedFileDurationLimit": "00:00:30"
}
}
]
}
}
Adding new variable in path tamplte to suppoert the log's {Level}, can use it same as {Date} variable
<add key="serilog:write-to:SizeRollingFile.pathFormat" value="C:\temp\log-{Date}-{Level}.txt"/>
To enable async, should enable in config file as follow
<add key="serilog:write-to:SizeRollingFile.supportAsync" value="true" />
There are defferent parameter that can update the default value
<add key="serilog:write-to:SizeRollingFile.maxRetries" value="5" /> <!-- Default = 3 -->
<add key="serilog:write-to:SizeRollingFile.bufferSize" value="9999" /> <!-- Default = 10000 -->