问题
I am trying to use WriteTo.RollingFile with Serilog as the following:
var log = new LoggerConfiguration().WriteTo.RollingFile(
@"F:\logs\log-{Date}.txt",
LogEventLevel.Debug).CreateLogger();
log.Information("this is a log test");
My understanding is that the log file will be created and named based on the date, and also it will write to a new file everyday, however I am getting a new log file for each log entry during the same day! How to configure Serilog to write to a new file every day so ideally I have a single log file per day?
And is there any archiving process to delete files older than 7 days?
回答1:
Try below:
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 the date.
回答2:
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);
回答3:
As a follow up to this make sure you then use the globally scoped "Log" instance.
Example:
Log.Information("Hello world");
回答4:
To use the same file, you have to add shared: true
.WriteTo.RollingFile("log-{Date}.txt", shared: true)
回答5:
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();
回答6:
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" />
来源:https://stackoverflow.com/questions/32108148/serilog-rollingfile