标准ASP.NET日志记录器LogError到stderr

tquggr8v  于 11个月前  发布在  .NET
关注(0)|答案(1)|浏览(90)

是否可以配置ASP.NET Core默认日志记录器,将错误级别日志记录到stderr
这是我的配置:

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

字符串
和用法:

_logger.LogError("Test error log");


的数据
消息格式很好,LogLevel设置为Error,但它在std out not err中

6kkfgxo0

6kkfgxo01#

您可以通过显式调用AddConsole(由AddJsonConsole内部调用)来配置ConsoleLoggerOptions.LogToStandardErrorThreshold

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

字符串
或者通过显式configure调用:

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


此外,它应该是可管理的配置:

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


你也可以看看Serilog,它也支持通过standardErrorFromLevel设置将错误重定向到stderr-例如this github issue
小演示(用于控制台应用程序):

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

相关问题