Thanh Nguyen
Thanh Nguyen

Reputation: 61

How to writing logs to STDERR base on log level using Serilog

I'm using Serilog for my .netcore application and write logs to console. And all logs come to STDOUT streams, but the requirement is Error and Fatal level should come to STDERR streams. I already added "standardErrorFromLevel": "Error" to arg of Writeto Console setting in appsetting.json but not working and my STDERR still empty. How do I redirect the logs for error and fatal level to STDERR? Please help!!!

Upvotes: 6

Views: 1831

Answers (1)

R. Schreurs
R. Schreurs

Reputation: 9085

I tried to achieve the same thing as you and I got it to work with VS.Net 2020 and Serilog.

My appSettings.json looks like this:

{
  "Serilog": {
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "standardErrorFromLevel": "Error"
        }
      }
    ],
  }
}

I tried this with setting command line arguments in my web projects properties, Debug, General, Launch Profiles to: >c:\temp\stdout.log 2>c:\temp\stderr.log. And the logging gets nicely separated into these two files.

My .Net6 program.cs contains this for SeriLog:

builder.Host.UseSerilog((context, configuration) => configuration
    .Enrich.FromLogContext()
    .ReadFrom.Configuration(context.Configuration)
    })
);

To make SeriLog the default ILogger<T> for dependency injection in controllers, I have added:

builder.Services.AddLogging(x =>
{
    x.ClearProviders();
    x.AddSerilog(dispose: true);
});

Might it be you are using DI and not actually be using SeriLog at all?

If you want to try and set the propeties in code, just add

    .WriteTo.Async(x =>
    {
         x.Console(standardErrorFromLevel: LogEventLevel.Error);
    }

inside UseSerilog().

I have to following SeriLog packages installed:

  • Serilog.AspNetCore 4.1.0
  • Serilog.Extensions.Logging 3.1.0
  • SeriLog.Settings.Configuration 3.3.0
  • SeriLog.Extensions.Logging.File 2.0.0

The latter should not be relevant there.

Upvotes: 2

Related Questions