控制台日志中的日期和时间

时间:2017-12-14 13:59:04

标签: asp.net-core

他们是否可以在生产和开发环境的asp.net core 2.0项目的控制台日志中提及日期和时间?

我的创业公司有以下内容:

G

Appsettings.json:

services.AddLogging(builder =>
{
            builder.AddConfiguration(Configuration.GetSection("Logging"+Environment.EnvironmentName))
                    .AddConsole()
                    .AddDebug();
});

当前[开发]日志布局(没有日志行的日期或时间):

"LoggingDevelopment": {
    "IncludeScopes": false,
    "Console": {
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
      }
    }
  },
  "LoggingProduction": {
    "IncludeScopes": false,
    "Console": {
      "LogLevel": {
        "Default": "Error",
        "System": "Error",
        "Microsoft": "Error"
      }
    }
  },

在错误行的生产模式中,日期和时间非常方便。

1 个答案:

答案 0 :(得分:3)

默认控制台记录器非常有限。当然总是有可能使用像serpent5提供的Github问题中所述的lambda格式化程序。但只有使用原始ILogger.Log()方法才能访问它。 它不适用于ILoggerLogInformationLogError个附加信息。如果您不控制日志记录调用,则此选项也不可用。实际上,当您通过ASP.NET Core内部类完成日志记录时就是这种情况。

因此,您需要为.Net Core更灵活地实施记录器。我建议使用Serilog。它非常简单,但同时非常灵活和强大。

要将Serilog集成到ASP.Net Core应用程序中,请执行以下操作:

  1. 安装以下NuGet包:

    Serilog.AspNetCore

    Serilog.Sinks.Console

    除了控制台之外,Serilog还支持许多其他目标,如滚动文件,电子邮件,SQL Server等。请参阅此列表中的其他Serilog targets

  2. 在应用程序启动时配置Serilog:

  3. 以下是一个示例:

    public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .Enrich.FromLogContext()
                .WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Message}{NewLine}{Exception}")
                .CreateLogger();
    
            BuildWebHost(args).Run();
        }
    
        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSerilog()
                .Build();
    }
    

    提供的输出模板为记录的消息添加日期和时间:

    enter image description here