ASP.NET 核心在所有日志条目中包含时间戳

ASP.NET Core include timestamp in all log entries

我有一个启用了内置控制台日志记录的 ASP.NET Core 2.0 应用程序。这是 WebHost 的创建:

var webHost = WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://localhost:5002")
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

webHost.Run();

发送 HTTP POST 请求时,会生成以下日志消息并显示在控制台标准输出中:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 POST http://localhost:5002/api/sample application/json 2144
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
  Executing action method MyApp.Controllers.SampleController.Post (Model.Solve) with arguments (MyApp.Request.MyRequest) - ModelState is Valid
info: Microsoft.AspNetCore.Mvc.Internal.ObjectResultExecutor[1]
  Executing ObjectResult, writing value Microsoft.AspNetCore.Mvc.ControllerContext.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
  Executed action MyApp.Controllers.SampleController.Post (MyApp) in 1201.9411ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 1446.1907ms 200 application/json; charset=utf-8

作为投入生产的一项要求,我需要所有日志条目都包含一个时间戳:现在,我知道我可以在调用 Log() 方法时自己提供时间戳,如 this open issue on the GitHub ASP.NET Logging repository 中所述,但是我应该如何对 WebHost 直接生成的日志消息执行此操作(如上所示)? 有没有一种方法可以添加时间戳,而不必像 中提出的解决方案那样重写完整的自定义记录器?

谢谢。

使用 third-party 解决方案是正确的答案。

正如 explained 在同一个 github 讨论中,您 link 讨论了 built-in 日志记录:

This really is a logging abstraction, the default sinks are very extremely basic and usually farm out to other systems to get more features.

There are so many amazing 3rd party logging systems with richer features than what we will ever provide OOTB. I'd recommend you use those in your production applications.

我强烈建议(也在 github 问题中)您考虑 well-maintained structured-logging 软件包,例如 Serilog.

我确定您 link 编辑的自定义代码可能没问题,但 Serilog 有很多贡献者,您可以肯定它会 up-to-date 到未来。主页将 link 您转到特定于 ASP.NET 核心日志记录的扩展。 (我对该产品没有任何既得利益,但我确实使用过它,设置和使用起来非常容易,而且非常灵活。)

结构化日志记录允许您向日志中添加任意 JSON 数据,这在故障排除过程中比我们过去所做的简单 "write a string of text" 日志记录有很大好处。

如链接问题中所述,此功能现在 built-in 到 Microsoft.Extensions.Logging.Console。您可以通过设置 TimestampFormat 来激活它:

  new ServiceCollection()
     .AddLogging(opt =>
     {
         opt.AddConsole(c =>
         {
            c.TimestampFormat = "[HH:mm:ss] ";
         });
    })