digor_ua
digor_ua

Reputation: 592

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?

Upvotes: 37

Views: 28977

Answers (6)

Simon_Weaver
Simon_Weaver

Reputation: 145950

Visual Studio / .AddDebug() not showing timestamps

If you're in Visual Studio and needing timestamps on debug logs (eg. logs from EF Core showing SQL) the only option AFAIK (since AddDebug has no arguments) is this handy little icon.

It will toggle timestamps on and off for future log entries.

Picture of Visual Studio output log with clock icon circled

Upvotes: 0

R. V.
R. V.

Reputation: 846

For ASP.NET Core, you might prefer to configure logger formatter in configuration file appsettings.json over wiring it directly into the code. In addition to the timestamp format you can also configure whether to use UTC. Don't forget to add FormatterName to make the configuration work as below:

{
  "Logging": {
    "Console": {
      "FormatterName": "simple",
      "FormatterOptions": {
        "TimestampFormat": "[yyyy-MM-dd HH:mm:ss] ",
        "UseUtcTimestamp": true
      }
    }
  }
}

This works out of the box, provided that WebApplication.CreateBuilder(args) is invoked in Program.cs.

Note: previosly, the TimestampFormat was configured directly on provider level, but this is obsolete and buggy (reloading configuration disables it).

More on console log formatting in .NET docs.

Upvotes: 30

Ogglas
Ogglas

Reputation: 69978

Here is another alternative:

using System;
using Microsoft.Extensions.Logging;

public class TimedLogger<T>: ILogger<T>
{
    private readonly ILogger _logger;

    public TimedLogger(ILogger logger) => _logger = logger;

    public TimedLogger(ILoggerFactory loggerFactory): this(new Logger<T>(loggerFactory)) { }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) =>
        _logger.Log(logLevel, eventId, state, exception, (s, ex) => $"[{DateTime.UtcNow:HH:mm:ss.fff}]: {formatter(s, ex)}");

    public bool IsEnabled(LogLevel logLevel) => _logger.IsEnabled(logLevel);

    public IDisposable BeginScope<TState>(TState state) => _logger.BeginScope(state);
}

Then replace ConfigureServices like this:

services.Replace(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(TimedLogger<>)))

Using Lamar you can use it like this:

For(typeof(ILogger<>)).Use(typeof(TimedLogger<>));

Source:

https://github.com/aspnet/Logging/issues/483#issuecomment-328355974

Upvotes: 1

Tim Taurit
Tim Taurit

Reputation: 9239

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...

Upvotes: 17

sschoof
sschoof

Reputation: 1721

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] ";
         });
    })

Upvotes: 52

Ilya Chumakov
Ilya Chumakov

Reputation: 25019

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

Upvotes: 12

Related Questions