dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.19k stars 9.93k forks source link

Add custom format support to HttpLogging middleware #46989

Open Martinn2 opened 1 year ago

Martinn2 commented 1 year ago

In production i want to log each http request in the format I select. With HttpLogging I can selected Headers and LoggingFields but I cannot format the result, which looks something like this.

image

I need to be able create single line logs and reorder logged properties

Describe the solution you'd like

In HttpLoggingOptions I would like to be able to specify string format. It would look something like this:

builder.Services.AddHttpLogging(options =>
{
    options.LogFormat = "Protocol {HttpProtocol} Scheme: {RequestScheme} \n Path: {Path}";
});

Additional context

No response

Tratcher commented 1 year ago

The 1-line format is available with the W3C logger. https://learn.microsoft.com/en-us/aspnet/core/fundamentals/w3c-logger/?view=aspnetcore-7.0 The Hosting logs also provide a 1-line request/response log.

Martinn2 commented 1 year ago

W3C format looks good, but it seems it supports only logging to the file. I need to use standard ILogger as HttpLogging does

adityamandaleeka commented 1 year ago

Triage: customizing the HttpLogging this way seems reasonable as something we should consider, but we won't be able to get to this in the near future.

In the meantime, you can achieve what you're looking for by writing your own middleware for this purpose.

adityamandaleeka commented 1 year ago

If anyone else is interested in this, please leave a comment or a 👍 on the first comment.

vecera-vojtech commented 1 month ago

I'd love this functionality since as of now I have to do a custom implementation of the logger just because of it.

It would also by nice to have option to enforce logging of only Headers specified in RequestHeaders. Atm values of those which are not added to the list are redacted. That pollutes and logs and makes us log values with no added value for us (and lets not mention the additional cost for the log storage if we would use it all our microservices). There is workaround, where I can prune the LogContext Parameters in OnResponse method. But I disslike the fact, that the values are even added to the list to just be deleted, seems like unnecessary overhead to me.

Also setting the LogLevel via interceptor would be nice, so we can log responses with HTTP Status code >=400 as warning/errors instead of having all as information.