Serilog - multiple log files

Anton Kiprianov picture Anton Kiprianov · Feb 3, 2015 · Viewed 15.8k times · Source

I am using Serilog for logging and cant' figure out how to separate log events to different files. For example, I want to log errors to error_log-ddmmyyyy.txt and warnings to warn_log-ddmmyyyy.txt.

Here goes my logger configuration:

Log.Logger = new LoggerConfiguration()
            .WriteTo.Logger(lc =>
                lc.Filter.ByIncludingOnly(Matching.WithProperty("Level", "Warning"))
                    .WriteTo.RollingFile(
                        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Logs\warn_log-{Date}.txt"),
                        outputTemplate: OutputTemplate))
            .WriteTo.Logger(lc =>
                lc.Filter.ByIncludingOnly(Matching.WithProperty("Level", "Error"))
                    .WriteTo.RollingFile(
                        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Logs\error_log-{Date}.txt"),
                        outputTemplate: OutputTemplate))
            .CreateLogger();

It only works when I specify {Level} property exatcly in log message.

I was trying to use:

Matching.WithProperty<LogEventLevel>("Level", l => l == LogEventLevel.Warning)

but it didn't work too.

Answer

Ben Pretorius picture Ben Pretorius · Oct 7, 2016

I use the following configuration and it works for me:

            Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Debug()
                    .WriteTo.LiterateConsole()
                    .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information).WriteTo.RollingFile(@"Logs\Info-{Date}.log"))
                    .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug      ).WriteTo.RollingFile(@"Logs\Debug-{Date}.log"))
                    .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Warning    ).WriteTo.RollingFile(@"Logs\Warning-{Date}.log"))
                    .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error      ).WriteTo.RollingFile(@"Logs\Error-{Date}.log"))
                    .WriteTo.Logger(l => l.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Fatal      ).WriteTo.RollingFile(@"Logs\Fatal-{Date}.log"))
                    .WriteTo.RollingFile(@"Logs\Verbose-{Date}.log")
                    .CreateLogger();