Log event datetime with.Net Core Console logger

后端 未结 3 1723
抹茶落季
抹茶落季 2021-02-18 13:33

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

var serviceCollection = new ServiceCollection();
s         


        
相关标签:
3条回答
  • 2021-02-18 14:03

    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...
    
    0 讨论(0)
  • 2021-02-18 14:04

    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] ";
             });
        })
    
    0 讨论(0)
  • 2021-02-18 14:17

    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
    
    0 讨论(0)
提交回复
热议问题