Serilog RollingFile

I am trying to use WriteTo.RollingFile with Serilog as follows:

var log = new LoggerConfiguration().WriteTo.RollingFile( @"F:\logs\log-{Date}.txt", LogEventLevel.Debug).CreateLogger(); log.Information("this is a log test"); 

I understand that a log file will be created and named based on the date, and it will be written to a new file every day, however I get a new log file for each log entry on the same day! How do I configure Serilog to write to a new file every day, so ideally I have one log file per day?

And is there an archiving process to delete files older than 7 days?

+7
source share
6 answers

Try the following:

  var log = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.RollingFile(@"f:\log\log.txt", retainedFileCountLimit:7) .CreateLogger(); 

The log file name will be automatically log-20150819.txt, etc. You do not need to specify a date.

+14
source

Accordingly, make sure that you then use the "Log" instance with global reach.

Example:

 Log.Information("Hello world"); 
+2
source

Now in 2018, the standard Serilog.Sinks.File NuGet package supports rolling:

 .WriteTo.File(@"e:\logs\skilliam.log", rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: true, fileSizeLimitBytes: 123456); 
+1
source

Here is a way to use Serilog with web.config in asp.net MVC 4/5.

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 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(); 
0
source

To use the same file, you must add shared: true

.WriteTo.RollingFile ("log- {Date} .txt", shared: true)

0
source

To enable multiprocessor shared log files, set the shared parameter to true:

in code

 .WriteTo.RollingFile("log-{Date}.txt", shared: true) 

or in web.config

 <add key="serilog:write-to:RollingFile.shared" value="true" /> 
0
source

All Articles