【问题标题】:ASP.NET Core include timestamp in all log entriesASP.NET Core 在所有日志条目中包含时间戳
【发布时间】:2018-08-14 03:55:42
【问题描述】:

我有一个启用了内置控制台日志记录的 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 直接生成的日志消息执行此操作(如上所示)? 有没有办法像this StackOverflow answer 中提出的解决方案那样,在无需重写完整的自定义 Logger 的情况下添加时间戳?

谢谢。

【问题讨论】:

    标签: c# logging asp.net-core .net-core kestrel-http-server


    【解决方案1】:

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

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

    【讨论】:

    【解决方案2】:

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

    作为explained 在您链接的关于内置日志记录的同一个 github 讨论中:

    这确实是一个日志抽象,默认接收器非常基本,通常会外包给其他系统以获得更多功能。

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

    我强烈建议(也在 github 问题中)您考虑使用维护良好的结构化日志记录包,例如 Serilog

    我确信您链接的自定义代码可能没问题,但是 Serilog 有很多贡献者,您可以确定它会在未来保持最新状态。主页会将您链接到特定于 ASP.NET Core 日志记录的扩展。 (我对这个产品没有任何既得利益,但我确实使用它,它很容易设置和使用,而且非常灵活。)

    结构化日志记录允许您将任意 JSON 数据添加到日志中,这在故障排除过程中比我们过去做的简单“写入文本字符串”日志记录具有巨大优势。

    【讨论】:

      猜你喜欢
      • 2016-11-06
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      • 2017-04-07
      • 2014-11-17
      • 2022-07-08
      • 2018-01-13
      • 2019-03-30
      相关资源
      最近更新 更多