Request to make Kestrel BadHttpRequestException.Reason public
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 5h
- Merged PRs (30d)
- 276
Description
### Is your feature request related to a problem? Please describe.
I'm implementing metrics telemetry for my web application and would like to have counters for different reasons we reject requests--whether it is due to Kestrel rejecting the request in its code or our application code rejecting the request.
I can't use BadHttpRequestException.Message because I can't guarantee the string doesn't have parameterized data in it (i.e. see use of `{detail}`/CoreStrings.FormatBadRequest). Pattern matching on the message would feel like unnecessary overhead. Parameterized messages would not be limited to a finite set of possible values, which would cause an explosion in the number of time series for the metrics collection.
### Describe the solution you'd like
Please make BadHttpRequestException.Reason and enum RequestRejectionReason public. Then it would be trivial to have a counter like the code below.
To capture these counters, one could have a custom ILoggerFactory, which can create an ILogger for kestrel with a method that would be like the following code below. You could imagine that `badRequestCounter` may be a monotonically increasing counter whose storage is similar to `Dictionary`. One may poll these values on an interval to put in a time-series database to calculate bad requests/second and set alerts. One could probably use scopes and a more sophisticated Log method to add additional dimensions to this counter.
```
internal void Log(LogLevel logLevel, string categoryName, string eventIdName, string originalFormat, Func formatter, TState state, Exception exception)
{
if (exception is BadHttpRequestException bre)
{
badRequestCounter.Increment(bre.Reason.ToString())
}
}
```
### Additional context
Related #11208
Contributor guide
Assessment
This issue has not been assessed yet.