Search code examples
c#serilog

Explicit Log Level instead of MinimumLevel for Serilog


Is there any way I can configure exactly ONE log level per file in serilog?

I know I can configure one file per "MinimumLevel", but that is not what I need.


Solution

  • I had a similar requirement. After some research, I added the following in the Startup class of my .net core 2.2 web api:

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
        .WriteTo.Logger(lc => lc
            .Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Error)
            .WriteTo.RollingFile("C:\\Temp\\erros-logs.txt"))
        .WriteTo.Logger(lc => lc
            .Filter.ByIncludingOnly(evt => evt.Level == LogEventLevel.Information)
            .WriteTo.RollingFile("C:\\Temp\\info-logs.txt"))
        .CreateLogger();
    

    If you are reading the settings from appsettings.json file and you want to use the above, you should transfer your logic from the file.

    My answer is heavily inspired from the following post: Restrict to level