smn*_*ino 4 c# logging .net-core kestrel-http-server asp.net-core
我有一个ASP.NET Core 2.0应用程序,启用了内置控制台日志记录.这是WebHost的创建:
var webHost = WebHost.CreateDefaultBuilder(args)
.UseUrls("http://localhost:5002")
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
webHost.Run();
Run Code Online (Sandbox Code Playgroud)
发送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
Run Code Online (Sandbox Code Playgroud)
作为进入生产的一个要求,我需要所有日志条目都包含一个时间戳:现在,我知道我可以在调用Log()方法时自己提供时间戳,如GitHub ASP.NET Logging存储库中的这个开放性问题所述,但是我应该如何直接在WebHost生成的日志消息上这样做(如上所示)?有没有办法添加时间戳,而不必像在StackOverflow答案中提出的解决方案那样重写完整的自定义Logger ?
谢谢.
Eug*_*hov 10
如链接问题所示,此功能现在内置于 Microsoft.Extensions.Logging.Console 中。您可以通过设置 TimestampFormat 来激活它:
new ServiceCollection()
.AddLogging(opt =>
{
opt.AddConsole(c =>
{
c.TimestampFormat = "[HH:mm:ss] ";
});
})
Run Code Online (Sandbox Code Playgroud)
使用第三方解决方案是正确的答案.
正如在同一个github讨论中所解释的那样,您链接了有关内置日志记录的信息:
这实际上是一个日志记录抽象,默认接收器是非常基本的,通常可以移植到其他系统以获得更多功能.
和
有许多令人惊叹的第三方日志系统,其功能比我们提供的OOTB更丰富.我建议你在生产应用程序中使用它们.
我强烈建议(也在github问题中)你认为像Serilog这样维护良好的结构化日志包.
我确定您链接的自定义代码可能很好,但Serilog有许多贡献者,您可以确定它将在未来很好地进行更新.主页面将链接到特定于ASP.NET Core日志记录的扩展.(我对产品没有任何既得利益,但我确实使用它,它很容易设置和使用,并且非常灵活.)
结构化日志记录允许您将任意JSON数据添加到日志中,这在通过简单的"写入一串文本"日志记录进行故障排除时是一个巨大的好处,就像我们以前一样.
| 归档时间: |
|
| 查看次数: |
2457 次 |
| 最近记录: |