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");

Message is nicely formatted, LogLevel is set to Error but it is in std out not err
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With