ASP.NET Core包含所有日志条目中的时间戳

问题描述 投票:2回答:1

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

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

webHost.Run();

发送HTTP POST请求时,将生成以下日志消息并显示在Console stdout中:

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直接生成的消息(如上所示)?有没有办法添加时间戳,而不必像this StackOverflow answer中提出的解决方案那样重写完整的自定义Logger?

谢谢。

c# logging asp.net-core .net-core kestrel-http-server
1个回答
6
投票

使用第三方解决方案是正确的答案。

正如explained在同一个github讨论中你链接的内置日志记录:

这实际上是一个日志记录抽象,默认接收器是非常基本的,通常可以移植到其他系统以获得更多功能。

有许多令人惊叹的第三方日志系统,其功能比我们提供的OOTB更丰富。我建议你在生产应用程序中使用它们。

我强烈建议(也在github问题中)你认为维护良好的结构化日志包如Serilog

我确定您链接的自定义代码可能很好,但Serilog有许多贡献者,您可以确定它将在未来很好地进行更新。主页面将链接到特定于ASP.NET Core日志记录的扩展。 (我对产品没有任何既得利益,但我确实使用它,它很容易设置和使用,并且非常灵活。)

结构化日志记录允许您将任意JSON数据添加到日志中,这在通过简单的“写入一串文本”日志记录进行故障排除时是一个巨大的好处,就像我们以前一样。

© www.soinside.com 2019 - 2024. All rights reserved.