Saturday, 10 August 2019

Date and Time in Console log in ASP.NET Core

One of the challenges that I found so far when moving towards ASP.NET Core is that the default console logger (built-in) that comes with it is not as verbose as I was expecting when displaying Dates and Times. To me this is the most obvious reason as I want to see when something happened:


As you can see in the image above, you can appreciate all the actions that are happening to the different controllers but there is no timestamp. This was raised as an issue with the aspnet team but it was deferred for later as it was not a critical piece of functionality...I guess who defines if this is critical or not. In any case, I'm the bearer of good news with the solution to your problems.

Serilog to the rescue!

With Serilog you can easily create a template so we display the message in any way we see fit. To accomplish this, here are the different components that you need (I'm already using the latest .NET Core 3.0 Preview 7):

Install the following packages:
  1. - Serilog.AspNetCore (latest, at the time of this example, was 2.1.2-dev-00028)
  2. - Serilog.Sinks.Console (latest, at the time of this example, was 3.1.2-dev-00779)
Add the following code to your Program.cs file:


And now you will see the log that you need:


Hope it helps!
Jordi

0 comments:

Post a Comment