Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard ASP.NET logger LogError to stderr

Is it possible to configure the ASP.NET Core default logger to log error level logs to stderr?

This is my configuration:

builder.Logging.AddJsonConsole(options =>
{
    options.IncludeScopes = false;
    options.TimestampFormat = "HH:mm:ss ";
    options.JsonWriterOptions = new JsonWriterOptions
    {
        Indented = true
    };
});

And usage:

_logger.LogError("Test error log");

e

Message is nicely formatted, LogLevel is set to Error but it is in std out not err

like image 306
beseus Avatar asked Dec 29 '25 21:12

beseus


1 Answers

You can use ConsoleLoggerOptions.LogToStandardErrorThreshold, by configuring it either by explicitly calling AddConsole (which is internally called by AddJsonConsole):

builder.Logging.AddConsole(o => o.LogToStandardErrorThreshold = LogLevel.Error);
builder.Logging.AddJsonConsole(...);

Or by explicit configure call:

builder.Logging.AddJsonConsole(...);
builder.Services.Configure<ConsoleLoggerOptions>(
    o => o.LogToStandardErrorThreshold = LogLevel.Warning);

Also it should be manageable from the config:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    },
    "Console": {
      "LogToStandardErrorThreshold": "Error",
      "FormatterName": "json",
      "FormatterOptions": {
        "JsonWriterOptions": {
          "Indented": true
        },
        "IncludeScopes": false,
        "TimestampFormat": "HH:mm:ss "
      }
    }
  }
}

Also you can look into Serilog which also supports redirecting errors to stderr via standardErrorFromLevel setting - see for example this github issue.

Small demo (for console app):

var services = new ServiceCollection();

services.AddLogging(lb => lb.AddJsonConsole());
services.Configure<ConsoleLoggerOptions>(
    o => o.LogToStandardErrorThreshold = LogLevel.Error);

StringWriter stdErrCapture = new();
Console.SetError(stdErrCapture);

var sp = services.BuildServiceProvider();
var requiredService = sp.GetRequiredService<ILogger<Program>>();
requiredService.LogError("Test");
sp.Dispose(); // dispose to wait for async write from the log queue

var capturedStdErr = stdErrCapture.ToString();
Console.WriteLine(capturedStdErr);
like image 134
Guru Stron Avatar answered Dec 31 '25 11:12

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!