Log date & time with the .NET core console logger

Hamza Sabljakovic
2 min readNov 20, 2020
Photo by Lukas Blazek on Unsplash

By default, once a new .net core project is created, the logger configuration provided by Microsoft does not print the date & time of when the log was created. It goes without saying that time when the event happened is an extremely useful part of a log line. Sooner or later, during the development but especially once the application is deployed to a live environment and used by multiple users/consumers you will need to know when a specific event occurred. Luckily, it’s very straight forward to change the console logger configuration to include the date & time as a part of the log line.

.net core console logger with date time log output example
.net core console logger with date time

All we have to do is update the CreateHostBuilder method in the Program.cs file from:

.net core host builder configuration

to:

.net core host builder configuration for console logger to include date & time

The AddConsole method is the one where we configure the date & time format, the other one, ClearProviders is responsible for disabling the default console output. Without the ClearProviders we would end up with duplicated logs as shown in the image below.

Log example without invoking the ClearProviders method log output example
Log example without invoking the ClearProviders method

However, the Console logger is not suitable for every use case, therefore I would like to mention a very good alternative — Serilog. Besides being highly configurable, it also has integration with all major log processing solutions such as ElasticSearch, AWS cloud watch, new relic, etc.

--

--