Serilog RollingFile

跟風遠走 提交于 2019-12-22 03:16:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!