Serilog set flush interval

Viewed 6709

I'm using serilog in my ASP Core 2.2 application. Everything works great but I can't set flushToDiskInterval. It means that I want to flush logs to disk every minute for example but logs are flushed just as they're created. My Program.cs file:

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.File("Logs/log-{Date}.txt", buffered: true, flushToDiskInterval: TimeSpan.FromSeconds(60))
        .CreateLogger();

        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseSerilog() // Set serilog as the logging provider.
        .UseStartup<Startup>();
}

So the question is how to set the interval?

==UPDATE==


I can't understand that but now everything works fine... I checked and there is really flush interval set.

3 Answers

To set in the source code,

flushToDiskInterval: TimeSpan.FromSeconds(1)

or following setting in the appsettings.json,

"WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          "restrictedToMinimumLevel": "Verbose",
          ...
          ...
          ...
          "flushToDiskInterval": 1
        }
      }
]

flushToDiskInterval is in seconds.

Reference link.

https://github.com/serilog/serilog-aspnetcore

just answering so that it may be useful to someone like me who is searching for answers!

As suggested by Carl Björknäs, to set this parameter in the settings file use this notation

"flushToDiskInterval": "00:00:01"  //hh:mm:ss

Because, internally when using Serilog Configuration, this method is used to parse the time string:

TimeSpan.Parse(s)

This is Serilog.Settings.Configuration snippet code:

class StringArgumentValue : IConfigurationArgumentValue
{
    readonly string _providedValue; 
    .....

    static readonly Dictionary<Type, Func<string, object>> ExtendedTypeConversions = new Dictionary<Type, Func<string, object>>
            {
                { typeof(Uri), s => new Uri(s) },
                { typeof(TimeSpan), s => TimeSpan.Parse(s) },
                { typeof(Type), s => Type.GetType(s, throwOnError:true) },
            }; 
     ... 
}

This is TimeSpan.Parse Method Doc:

https://docs.microsoft.com/en-us/dotnet/api/system.timespan.parse?view=net-5.0

For .NET 6 add the following to your Program.cs file

var builder = WebApplication.CreateBuilder(args);

// other configuration stuff

builder.Host.UseSerilog((ctx, lc) => lc
    .WriteTo.Console()
    .WriteTo.File("logs/app.log",  
             rollingInterval: RollingInterval.Day, 
             flushToDiskInterval: TimeSpan.FromSeconds(5))
    );

// more configuration stuff

var app = builder.Build();
Related