35

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?

digor_ua
  • 572
  • 2
  • 7
  • 20

4 Answers4

51

The feature was added into version 3 of the Microsoft.Extensions.Logging.Console(here is the pr). You can activate this with setting the TimestampFormat:

  new ServiceCollection()
     .AddLogging(opt =>
     {
         opt.AddConsole(c =>
         {
            c.TimestampFormat = "[HH:mm:ss] ";
         });
    })
sschoof
  • 1,531
  • 1
  • 17
  • 24
  • 1
    For valid format strings, see [`DateTime.ToString(string? format)`](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tostring) – Pang Oct 07 '20 at 04:41
  • 4
    In .NET 5, this has been deprecated. See https://learn.microsoft.com/en-us/dotnet/core/extensions/console-log-formatter – Stef Heyenrath Nov 25 '20 at 08:26
  • 4
    @StefHeyenrath the deprecation is for ***`ConsoleLoggerFormat`*** not for the `TimestampFormat` mentioned here. – Adarsha Jun 02 '21 at 16:18
  • 1
    The only overload for `AddConsole` that can configure time format is obsolete .NET 5+. The docs recommend @PawelBulwan's answer below. i.e. use `AddSimpleConsole()` or other new flavor `AddJsonConsole()`, etc., not `AddConsole()` as in this answer. – yzorg Jul 25 '22 at 13:56
  • Not sure why folks keep saying this overload isn't deprecated. It specifically is for this purpose in 5+. (Why recommend the overload if it doesn't solve the OP question, if you can't set time format)? – yzorg Jul 25 '22 at 13:56
21

For ASP.NET Core, you might prefer to use configuration file appsettings.json over wiring it directly into the code.

{
  "Logging": {
    "Console": {
      "TimestampFormat": "[yyyy-MM-dd HH:mm:ss] "
    }
  }
}

This works out of the box, provided that Host.CreateDefaultBuilder() is invoked in Program.cs

R. V.
  • 636
  • 7
  • 9
15

Example in .NET 5 (ASP.NET Core):

public void ConfigureServices(IServiceCollection services)
{
    services.AddLogging(options =>
    {
        options.AddSimpleConsole(c =>
        {
            c.TimestampFormat = "[yyyy-MM-dd HH:mm:ss] ";
            // c.UseUtcTimestamp = true; // something to consider
        });
    });

    // ...
}

Output example:

[2020-12-13 12:55:44] info: Microsoft.Hosting.Lifetime[0] Application is shutting down...
Paweł Bulwan
  • 8,467
  • 5
  • 39
  • 50
  • 1
    One thing that I didn't get is that this does not modify the "Debug" log (found in Visual Studio). From VS, to see the log with timestamps, you should modify the "show output from" to the web server's logs. I don't believe there is a way to add timestamps to the debug log as AddDebug takes no arguments. – tleb Dec 17 '20 at 11:06
  • This is flagged as Depricated in .Net 5 – Matt Feb 02 '21 at 19:33
  • 1
    @Matt @StefHeyenrath the deprecation is for `ConsoleLoggerFormat` not for the `TimestampFormat` mentioned here. https://learn.microsoft.com/en-us/dotnet/core/extensions/console-log-formatter indeed specifies "In .NET 5, support for custom formatting was added to console logs in the Microsoft.Extensions.Logging.Console namespace." – Adarsha Jun 02 '21 at 16:19
  • @Adarsha Thank you for clarifying, I had accidentally done `options.AddConsole` not `options.AddSimpleConsole` – Matt Jun 03 '21 at 09:55
10

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
Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
  • 1
    Thank you. Your library is brilliant. I've just added link to Nuget package, removed references to standard Logging libraries, updated initialization and it works as expected/ – digor_ua Aug 01 '17 at 13:17