Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core API logging output on multiple lines

I'm working with an API running on .NET Core 3.1 and using the framework's default logging which works great for me. I was wondering if I can change the format of the output logs, though, because each individual log output prints 2 lines.

For example, the following line of code:

logger.LogInformation("'{0} {1}'. Status: {2}. Time: {3}ms.",
  context.Request.Method, context.Request.Path, context.Response.StatusCode, responseTime);

Produces the following output:

info: MyApi.Utilities.RequestLoggerMiddleware[0]
'GET /api/users/current'. Status: 200. Time: 8ms.

Is there some way I can get info: MyApi.Utilities.RequestLoggerMiddleware[0] to print on the same line as the message text?

like image 733
Aaron T Avatar asked Sep 05 '26 17:09

Aaron T


1 Answers

I was able to solve my issue by adding this code after Host.CreateDefaultBuilder(args) in Program.cs and configuring a console logger with the Systemd format:

            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole(configure =>
                {
                    configure.Format = Microsoft.Extensions.Logging.Console.ConsoleLoggerFormat.Systemd;
                });
            })

The output now looks like this:

<6>MyApi.Utilities.RequestLoggerMiddleware[0] 'GET /api/users/current'. Status: 200. Time: 8ms.

like image 92
Aaron T Avatar answered Sep 07 '26 07:09

Aaron T