Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 620
smn.tino Avatar asked Mar 06 '18 10:03

smn.tino


1 Answers

As indicated in the linked question, this feature is now built-in to the Microsoft.Extensions.Logging.Console. You can activate it by setting the TimestampFormat:

  new ServiceCollection()
     .AddLogging(opt =>
     {
         opt.AddConsole(c =>
         {
            c.TimestampFormat = "[HH:mm:ss] ";
         });
    })
like image 194
Eugene Kulabuhov Avatar answered Sep 20 '22 06:09

Eugene Kulabuhov