首页 > 解决方案 > 将日期添加到 ASP .NET Core 2.1 默认记录器

问题描述

我正在使用 ASP.NET 的默认记录器,它正在创建这样的日志

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\Test\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data, this mode should only be enabled during development.

但我想将 DateTime.Now 附加到它上面

[2019.12.19 10:00] info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\Test\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
[2019.12.19 10:00] warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
      Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data, this mode should only be enabled during development.

我尝试使用 Serilog,但我无法获取那些默认日志,只显示我直接创建的那些 Log.Error("error");

标签: c#asp.net-corelogging

解决方案


在 ASP.Net Core 中,您可以配置记录器以包含时间戳。

public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateWebHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logger=>
            {
                logger.AddConsole(x => x.TimestampFormat = "[HH:mm:ss] "); 
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>().UseIIS();
            });
    }

推荐阅读