.net core 3.0日志中打印时间 | logging timestamp in .net core

“遭万人唾弃”的.net core在3.0中终于可以在日志中打印时间戳了, 一个大家都觉得是炒鸡煎蛋的功能在github上挂了3年(https://github.com/aspnet/Logging/issues/483).

目前只发现在Microsoft.Extensions.Logging.Console中有这么一个TimestampFormat, 是不是也就意味着只能在Console Log中打印时间戳 ?

用法1, AddConsole时指定Format:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddLogging(opt =>
            {
                opt.AddConsole(cfg => { cfg.TimestampFormat = "[yyyy-MM-dd HH:mm:ss]"; });
            });
        }

        //...
    }
}

 

用法2, appsettings.json中配置Format:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "Console": {
      "TimestampFormat": "[yyyy-MM-dd HH:mm:ss]"
    }
  }
  //...
}