.net core 3.0日志中打印时间 | logging timestamp in .net core
· One min read
“遭万人唾弃”的.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();
<span style="color: #ff0000;">services.AddLogging(opt =>
{
opt.AddConsole(cfg => { cfg.TimestampFormat = "[yyyy-MM-dd HH:mm:ss]"; });
});</span>
}
//...
}
}
用法 2, appsettings.json 中配置 Format:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
},
<span style="color: #ff0000;">"Console": {
"TimestampFormat": "[yyyy-MM-dd HH:mm:ss]"
}</span>
}
//...
}
