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:
- - Serilog.AspNetCore (latest, at the time of this example, was 2.1.2-dev-00028)
- - Serilog.Sinks.Console (latest, at the time of this example, was 3.1.2-dev-00779)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore; | |
using Microsoft.AspNetCore.Hosting; | |
using Serilog; | |
using Serilog.Events; | |
using System; | |
namespace test | |
{ | |
public class Program | |
{ | |
public static int Main(string[] args) | |
{ | |
//Specify the template to use via Console | |
Log.Logger = new LoggerConfiguration() | |
.MinimumLevel.Debug() | |
.MinimumLevel.Override("Microsoft", LogEventLevel.Information) | |
.Enrich.FromLogContext() | |
.WriteTo.Console(outputTemplate: "[{Timestamp:yyyy-MMM-dd HH:mm:ss.fff}] [{Level}] {Message}{NewLine}{Exception}") | |
.CreateLogger(); | |
try | |
{ | |
Log.Information("Starting web host"); | |
BuildWebHost(args).Run(); | |
return 0; | |
} | |
catch (Exception ex) | |
{ | |
Log.Fatal(ex, "Host terminated unexpectedly"); | |
return 1; | |
} | |
finally | |
{ | |
Log.CloseAndFlush(); | |
} | |
} | |
//Use serilog here | |
public static IWebHost BuildWebHost(string[] args) => | |
WebHost.CreateDefaultBuilder(args) | |
.UseStartup<Startup>() | |
.UseSerilog() | |
.Build(); | |
} | |
} |
And now you will see the log that you need:
Hope it helps!
Jordi
Jordi
Comments
Post a Comment