Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks.

like image 900
BooFar Avatar asked May 28 '17 17:05

BooFar


People also ask

Which of the format collections are used for input and output format in ASP.NET Core Web API?

ASP.NET Core MVC supports data exchange in Web APIs using input and output formatters. Input formatters are used by Model Binding. Output formatters are used to format responses. The framework provides built-in input and output formatters for JSON and XML.

What is the use of ILogger in .NET Core?

ILoggerFactory is a factory interface that we can use to create instances of the ILogger type and register logging providers. It acts as a wrapper for all the logger providers registered to it and a logger it creates can write to all the logger providers at once.

What is Serilog .NET Core?

Serilog is a . NET library that provides diagnostic logging to files, the console, and almost everywhere you would like. Serilog can be used in classic . NET Framework applications and for applications running on the latest and greatest .


4 Answers

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.

like image 65
Martin Ullrich Avatar answered Oct 05 '22 04:10

Martin Ullrich


As @MartinUllrich already mentioned this line break can't be disabled and you have to implement a custom logger to avoid it.

Registration:

loggerFactory.AddProvider(new CustomLoggerProvider());

The implementation (can be extended with using of the original ConsoleLogger source code - for example, you could add the GetLogLevelConsoleColors method):

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;
        }
    }
}
like image 30
Ilya Chumakov Avatar answered Oct 05 '22 03:10

Ilya Chumakov


This is updated in .NET 5: https://docs.microsoft.com/en-us/dotnet/core/extensions/console-log-formatter. Now provides simple, systemd and json

like image 41
Wouter Van Ranst Avatar answered Oct 05 '22 05:10

Wouter Van Ranst


Although you can't specify your own custom format, it does support an alternative "systemd" format which you can select like this:

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

This outputs each log entry on one line even if you the text has newlines in it (so exceptions aren't very pretty). It also doesn't use colors which is an advantage if you're redirecting to a file.

like image 45
Andy Avatar answered Oct 05 '22 03:10

Andy