datetimelogging.net-core

Log event datetime with.Net Core Console logger


I'm using logging to Console output, that built-in to .Net Core framework. Here initialization of the logger:

var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(new LoggerFactory()
                    .AddConsole());

Also for logging I'm using Microsoft.Extensions.Logging.LoggerExtensions class with methods Log... Here an example of logging in my App:

_logger.LogInformation(eventId, "Action is started.");

Where _logger is instance of ILogger<T> class and initialized in the class constructor with built-in dependency injection. As result of calling of the above method Console output shows following string:

info: NameSpaceName.ClassName[eventId] Action is started.

I would like to display date-time in the Console output, that points to time, when the Log method is executed, but it seems that Log.. methods don't contain any methods that allow to display date time.

Does it exist some method or additioanl classes-formatters that allow to display the action datetime in console output without passing it to the method as part of the message?


Solution

  • Built-in .NET Core console logger doesn't log date-time. Track this issue to get more details. The easiest workaround is:

    logger.Log(LogLevel.Information, 1, someObj, null, (s, e) => DateTime.Now + " " + s.ToString());
    

    I wrote a custom console logger to automatically log the timestamp and do other useful tricks:

    [2017.06.15 23:46:44] info: WebHost[1]      Request starting HTTP/1.1 GET http://localhost:6002/hc