.net-coreserilogserilog-exceptions

Serilog different levels for different sinks


I have the following piece of c# code for writing logs with multiple sinks (console and file), how do i restrict the console to log only (info, warn and error) and file to log everything.

var outputTemplate = "[{Level:u3}] {Message:lj}{NewLine}{Exception}";

// Logger  

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Console(outputTemplate: outputTemplate, theme:SystemConsoleTheme.Literate)
    .WriteTo.File($"logs/log-{DateTime.Now:yyyy-MM-dd_HH:mm:ss.fff}.log")              
    .CreateLogger();

Solution

  • You can set a value for restrictedToMinimumLevel for each sink, to raise the minimum level that it should log.

    It's explained in the documentation with examples:

    https://github.com/serilog/serilog/wiki/Configuration-Basics#overriding-per-sink

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .WriteTo.File("log.txt")
        .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
        .CreateLogger();