Search code examples
c#loggingconsole-application.net-core

Is there a way to format the output format in .NET Core logging?


I'm using the built in logging provider for logging into the console (Microsoft.Extensions.Logging.Console) in a .NET Core console application.

Each logging entry produces two lines in the output. I would like to have each entry in one single line. Is there a way to customize the output format?

Here is an example how I use it:

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...");
}

What I get is:

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

What I would like to have is something like this:

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

Any idea? I know, I could write a custom logger, but I would like to know if there is an other way.


Solution

  • Update: Since .NET 5 this can be customized as shown by other answers: Console log formatter documentation

    Original Answer:

    At the moment, this not configurable. The source code is here on GitHub:

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

    If you want that, you need to write your own logger. However you can just copy the source code of the console logger, modify as needed and change the namespaces so it doesn't interfere with the version Microsoft ships.

    You can also open an issue on the logging repo to ask for this option.