Serilog RollingFile

醉酒当歌 提交于 2019-12-05 00:55:14

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.

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);

As a follow up to this make sure you then use the globally scoped "Log" instance.

Example:

Log.Information("Hello world");

To use the same file, you have to add shared: true

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

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

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