Reputation: 930
I am trying to use WriteTo.RollingFile
with Serilog as the following to write one file per day:
var log = new LoggerConfiguration().WriteTo.RollingFile(
@"F:\logs\log-{Date}.txt",
LogEventLevel.Debug).CreateLogger();
log.Information("this is a log test");
But I am getting a new log file for each log entry during the same day!
How does one configure Serilog to write to a new file every day as to have a have a single log file per day?
And is there any archiving process to delete files older than 7 days?
Upvotes: 50
Views: 113260
Reputation: 89
First of all. You need to add these nugets:
<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
Than set your serilog in appsettings.json:
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
"Serilog.Sinks.File"
],
"MinimumLevel": {
"Default": "Information"
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"Path": "../Logs/MyLog-.json",
"RollingInterval": "Day",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
},
{
"Name": "File",
"Args": {
"Path": "../Logs/MyLog-.log",
"RollingInterval": "Day",
"OutputTemplate": "[({Component}|{MachineName}|{ThreadId}) {Timestamp:G} [{Level:u3}]{Message:lj}{NewLine}{Exception} ]"
}
}
]
}
Than you need to add this config in C# code.
var _logger = new LoggerConfiguration()
.ReadFrom
.Configuration(configuration)
.Enrich
.FromLogContext()
.CreateLogger();
services.AddLogging(logBuilder => logBuilder.AddSerilog(_logger));
configuration is an instance of IConfiguration, u will find builder.Configuration
services --> builder.Services
Upvotes: 1
Reputation: 31686
If one is using a text formatter ITextFormatter
, note that the variable positions of the path
has switched to be second place when using File
.
So use this format with a formatter:
var filepath = @"C:\Logs";
ITextFormatter jsonFormatter = new Serilog.Formatting.Json.JsonFormatter(renderMessage: true);
...
Log.Logger = new LoggerConfiguration()
... // Enrichers etc...
.WriteTo.File(formatter: jsonFormatter,
path: filepath,
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
fileSizeLimitBytes: 123456,
shared: true)
.CreateLogger();
Upvotes: 3
Reputation: 16906
Since the posted answer, the method RollingFile
is no longer viable and replaced with File
and options to roll the logs.
Now one must use the standard Serilog.Sinks.File
NuGet package which supports rolling:
.WriteTo.File(path: @"e:\logs\skilliam.log",
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
fileSizeLimitBytes: 123456);
Upvotes: 38
Reputation: 1140
Try below:
var log = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.File(@"f:\log\log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
The log file name will be automatically log-20150819.txt etc. You do not need to specify the date.Old files will be cleaned up as per retainedFileCountLimit - default is 31.
Upvotes: 70
Reputation: 328
This is how I did it:
private readonly Serilog.ILogger _logger; //= Log.ForContext( "Name", "Weather" );
public WeatherForecastController() {
string subPath = Path.Combine( DateTime.Now.ToString( "yyyy" ), DateTime.Now.ToString( "MM" ) ) + $"/{DateTime.Now.ToString("dd")}_Weather";
_logger = Log.ForContext( "Name", subPath );
}
.UseSerilog( ( hostingContext, loggerConfiguration ) => loggerConfiguration
.ReadFrom.Configuration( hostingContext.Configuration )
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.Map(
"Name",
"Request",
( name, wt ) => {
if (name == "Request")
wt.RollingFile( Path.Combine( $"{hostingContext.Configuration["LogPath"]}/{{Date}}-{name}.txt" ) );
else
wt.File( $"{hostingContext.Configuration["LogPath"]}/{name}.txt" );
} )
);
Upvotes: -1
Reputation: 508
To enable multi-process shared log files, set shared to true:
in code
.WriteTo.RollingFile("log-{Date}.txt", shared: true)
or in web.config
<add key="serilog:write-to:RollingFile.shared" value="true" />
Upvotes: 6
Reputation: 2372
To use the same file, you have to add shared: true
.WriteTo.RollingFile("log-{Date}.txt", shared: true)
Upvotes: 5
Reputation: 917
Here is a way to use Serilog with a web.config in an asp.net MVC 4/5 app.
In your web.config add the following:
<add key="serilog:minimum-level" value="Information" />
<add key="serilog:minimum-level:override:Microsoft" value="Information" />
<add key="serilog:minimum-level:override:System" value="Information" />
<add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" />
<add key="serilog:write-to:RollingFile.pathFormat" value="./Logs/log-{Date}.txt" />
<add key="serilog:write-to:RollingFile.outputTemplate" value="{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] [{SourceContext}] {Message}{NewLine}{Exception}" />
<add key="serilog:write-to:RollingFile.retainedFileCountLimit" value="10" />
Then in Application_Start
of global.asax add the following:
// Get application base directory
string basedir = AppDomain.CurrentDomain.BaseDirectory;
// Setup Serilog for logging
Log.Logger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.WriteTo.RollingFile(basedir + "/Logs/log-{Date}.txt")
.CreateLogger();
Upvotes: 6
Reputation: 490
As a follow up to this make sure you then use the globally scoped "Log" instance.
Example:
Log.Information("Hello world");
Upvotes: 2