【问题标题】:Is there a way to format the output format in .NET Core logging?有没有办法在 .NET Core 日志记录中格式化输出格式?
【发布时间】:2017-10-29 01:08:30
【问题描述】:

我正在使用内置的日志记录提供程序在 .NET Core 控制台应用程序中登录控制台 (Microsoft.Extensions.Logging.Console)。

每个日志记录条目在输出中产生两行。我想将每个条目放在一行中。 有没有办法自定义输出格式?

这是我如何使用它的示例:

static void Main(string[] args)
{
    var serviceProvider = new ServiceCollection()
      .AddLogging() // This adds the Microsoft logging.
      .AddSingleton<IProjectGeneratorService, CSharpProjectGeneratorService>()
      .BuildServiceProvider();

    // Configure the console logging.
    serviceProvider
      .GetService<ILoggerFactory>()
      .AddConsole(LogLevel.Debug);

    // Write a logging entry
    var logger = serviceProvider.GetService<ILoggerFactory>().CreateLogger<Program>();
    logger.LogDebug("Application started...");
}

我得到的是:

dbug: Generator.Program[0]
      Application started...

我想要的是这样的:

dbug: Generator.Program[0]: Application started...

有什么想法吗?我知道,我可以编写一个自定义记录器,但我想知道是否有其他方法。

谢谢。

【问题讨论】:

  • 最后我改进了 Microsoft logger 并发布了它github.com/ilya-chumakov/LoggingAdvanced。使用该包,可以删除消息部分之间的换行符。此外,我添加了另一个杀手级功能 - 时间戳!
  • 自上次关于此问题的活动以来已经快 3 年了。 Miscrosoft 是否在 .Net Core 3 中加入了这样的功能?

标签: c# logging console-application .net-core


【解决方案1】:

正如@MartinUllrich 已经提到的,这个换行符不能被禁用,你必须实现一个自定义记录器来避免它。

注册:

loggerFactory.AddProvider(new CustomLoggerProvider());

实现(可以使用原始ConsoleLogger源代码进行扩展-例如,您可以添加GetLogLevelConsoleColors方法):

public class CustomLoggerProvider : ILoggerProvider
{
    public void Dispose() { }

    public ILogger CreateLogger(string categoryName)
    {
        return new CustomConsoleLogger(categoryName);
    }

    public class CustomConsoleLogger : ILogger
    {
        private readonly string _categoryName;

        public CustomConsoleLogger(string categoryName)
        {
            _categoryName = categoryName;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            Console.WriteLine($"{logLevel}: {_categoryName}[{eventId.Id}]: {formatter(state, exception)}");
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return null;
        }
    }
}

【讨论】:

  • 格式化程序不包含您需要单独记录的异常详细信息
【解决方案2】:

目前,这无法配置。源码is here on GitHub

logBuilder.Append(logName);
logBuilder.Append("[");
logBuilder.Append(eventId);
logBuilder.AppendLine("]");

如果需要,您需要编写自己的记录器。但是,您可以只复制控制台记录器的源代码,根据需要进行修改并更改命名空间,这样就不会干扰 Microsoft 发布的版本。

您也可以打开issue on the logging repo 询问此选项。

【讨论】:

  • 好的,我认为这是唯一的方法。感谢您的链接和代码 sn-p。这节省了我自己搜索的时间:-)
【解决方案3】:

这是在 .NET 5 中更新的:https://docs.microsoft.com/en-us/dotnet/core/extensions/console-log-formatter。现在提供simple、systemd和json

【讨论】:

  • 我不确定最初的问题是关于自定义日志格式,还是只是没有换行符的问题。 Systemd 和 JSON 选项适用于许多将每个换行符视为单独的日志条目的日志聚合器,例如 AWS CloudWatch。
【解决方案4】:

虽然您不能指定自己的自定义格式,但它确实支持另一种“systemd”格式,您可以像这样选择:

logging.AddConsole(options => {
  options.Format=ConsoleLoggerFormat.Systemd;
});

这会在一行中输出每个日志条目即使文本中有换行符(因此异常不是很漂亮)。它也不使用颜色,如果您要重定向到文件,这是一个优势。

【讨论】:

    【解决方案5】:

    现在使用 Microsoft.Extensions.Logging.Console 5.0.0 包中的 SimpleConsoleFormatter 很容易做到这一点。

    SimpleConsoleFormatter 的源代码是here on Github

    例子:

    static void Main(string[] args)
    {
          var serviceProvider = new ServiceCollection()
                .AddLogging(loggingBuilder => loggingBuilder
                    .AddSimpleConsole(formatterOptions =>
                    {
                        formatterOptions.SingleLine = true;
                    })
                    .SetMinimumLevel(LogLevel.Debug))
                .BuildServiceProvider();
    
          // Write a logging entry
          var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
          logger.LogDebug("Application started...");
    }
    

    输出:

    dbug: Generator.Program[0]: Application started...
    

    【讨论】:

      【解决方案6】:

      你可以使用像 Serilog 这样的日志库。

      使用ASP.NET Core integration 中的说明,您稍后可以通过Console sink 提供一个日志输出模板

      .WriteTo.Console(
          outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
      

      【讨论】:

        【解决方案7】:

        从 .NET 5 开始,您可以配置日志格式化程序以将每个日志条目写入单行。使用 Formatter 的 SingleLine 属性进行配置

        例如,您可以在appsettings.json 中配置控制台格式化程序,而无需编写任何额外代码:

        {
          "Logging": {
            "LogLevel": {
              "Default": "Information",
              "Microsoft.Hosting.Lifetime": "Information"
            },
            "Console": {
              "FormatterName": "simple",
              "FormatterOptions": {
                "SingleLine": true,
                "TimestampFormat": "HH:mm:ss "
              }
            }
          }
        }
        
        

        您可以在 Microsoft Docs 中找到更多信息:

        【讨论】:

          猜你喜欢
          • 2015-08-01
          • 1970-01-01
          • 2019-08-27
          • 1970-01-01
          • 2020-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多