Search code examples
c#loggingasp.net-core.net-corekestrel-http-server

ASP.NET Core include timestamp in all log entries


I have a ASP.NET Core 2.0 application with built-in console logging enabled. Here is the WebHost creation:

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

webHost.Run();

When sending an HTTP POST request, the following log messages are generated and showed in the 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

As a requirement for going in production, I need all log entries to include a timestamp: now, I know I could provide the timestamp myself when calling the Log() method as explained in this open issue on the GitHub ASP.NET Logging repository, however how am I supposed to do so on log messages generated by the WebHost directly (like the ones showed above)? Is there a way to add the timestamp without having to rewrite a complete custom Logger as in the solution proposed in this StackOverflow answer?

Thanks.


Solution

  • Using a third-party solution is the right answer.

    As explained in the same github discussion you linked about the built-in logging:

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

    and

    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.

    I would strongly recommend (also in the github issue) that you consider a well-maintained structured-logging package like Serilog.

    I'm sure the custom code you linked is probably fine, but Serilog has many contributors and you can be sure it'll be up-to-date well into the future. The main page will link you to extensions specific to ASP.NET Core logging. (I don't have any vested interest in the product, but I do use it, it's quite easy to set up and use, and is very flexible.)

    Structured logging lets you add arbitrary JSON data to your logs, which is a huge benefit during troubleshooting over simple "write a string of text" logging like we used to do.