dotnet / dotnet/aspnetcore

Extend HttpLogging & W3C logging middleware to have a custom callback that can supply extra fields for the log.

Open
#60,817 1 comment 0 reactions 0 assignees View on GitHub
api-suggestion area-networking feature-http-logging
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

## Background and Motivation

There are a number of requests for specific log fields to be included in the log output. We can spend a lot of effort adding "configuration" options for app code to be able to specify what fields they want and in what format, or we can give a simple way for app code to add what it wants. This proposal is for the latter - have a callback that can be used as part of the logging middleware to add extra log entries as needed.

## Proposed API

For HttpLogging, there should be callbacks that can be registered for each phase that logging is performed at. The callback is given the HttpContext (simpler than a custom context per phase) and returns an IEnumerable>.

``` c#
builder.Services.AddHttpLogging(o => {
o.AddCustomEntries(HttpLoggingPhase.RequestHeaders, (HttpContext ctx) =>
{
return new KeyValuePair[] {
new KeyValuePair(KeyValuePair"MyCustomName", ctx.Response.StatusCode.ToString())
};
});
```

For W3C logging a similar callback is available, but it is only fired once, so does not need the phase aspect.

``` c#
builder.Services.AddW3CLogging(logging =>
{
// Log all W3C fields
logging.LoggingFields = W3CLoggingFields.All;
logging.AddCustomEntries((HttpContext ctx) =>
{
return new KeyValuePair[] {
new KeyValuePair(KeyValuePair"MyCustomName", ctx.Response.StatusCode.ToString())
};
});
});
```

## Alternate designs

The callback in-turn could be handed an API that could be used to add fields to the resulting log entries. If there is an internal class that could be extended with an interface with the add key/value pair method, then we could save having to allocate a collection of key/value pairs in the app code.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.