-
Notifications
You must be signed in to change notification settings - Fork 887
Add configurable HTTP status code log levels for HttpClientLogging #7638
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Marcus-Kanon
wants to merge
4
commits into
dotnet:main
Choose a base branch
from
Marcus-Kanon:feature/7637-configurable-http-logging-level
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
46 changes: 46 additions & 0 deletions
46
src/Libraries/Microsoft.Extensions.Http.Diagnostics/Logging/HttpStatusCodeLogLevelRule.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Collections.Generic; | ||
| using System.ComponentModel.DataAnnotations; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Shared.DiagnosticIds; | ||
|
|
||
| namespace Microsoft.Extensions.Http.Logging; | ||
|
|
||
| /// <summary> | ||
| /// Maps a status code or range of status codes to a specific log level. | ||
| /// </summary> | ||
| [Experimental(diagnosticId: DiagnosticIds.Experiments.Telemetry, UrlFormat = DiagnosticIds.UrlFormat)] | ||
| public class HttpStatusCodeLogLevelRule : IValidatableObject | ||
| { | ||
| /// <summary> | ||
| /// Gets or sets the minimum status code this rule applies to (inclusive). | ||
| /// </summary> | ||
| [Range(100, 599)] | ||
| public int FromStatusCode { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the maximum status code this rule applies to (inclusive). | ||
| /// When <see langword="null"/>, matches only <see cref="FromStatusCode"/> (exact match). | ||
| /// </summary> | ||
| [Range(100, 599)] | ||
| public int? ToStatusCode { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the log level to use for responses matching this rule. | ||
| /// </summary> | ||
| public LogLevel LogLevel { get; set; } = LogLevel.Information; | ||
|
|
||
| /// <inheritdoc/> | ||
| public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) | ||
| { | ||
| if (ToStatusCode.HasValue && ToStatusCode.Value < FromStatusCode) | ||
| { | ||
| yield return new ValidationResult( | ||
| $"{nameof(ToStatusCode)} must be greater than or equal to {nameof(FromStatusCode)}.", | ||
| [nameof(ToStatusCode)]); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
229 changes: 229 additions & 0 deletions
229
...osoft.Extensions.Http.Diagnostics.Tests/Logging/HttpClientLoggerStatusCodeLogLevelTest.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,229 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Collections.Generic; | ||
| using System.Net; | ||
| using System.Net.Http; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.Compliance.Classification; | ||
| using Microsoft.Extensions.Compliance.Testing; | ||
| using Microsoft.Extensions.Http.Diagnostics; | ||
| using Microsoft.Extensions.Http.Diagnostics.Test.Logging.Internal; | ||
| using Microsoft.Extensions.Http.Logging.Internal; | ||
| using Microsoft.Extensions.Http.Logging.Test.Internal; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Extensions.Logging.Testing; | ||
| using Microsoft.Extensions.Telemetry.Internal; | ||
| using Moq; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Extensions.Http.Logging.Test; | ||
|
|
||
| public class HttpClientLoggerStatusCodeLogLevelTest | ||
| { | ||
| [Theory] | ||
| [InlineData(HttpStatusCode.NotFound, LogLevel.Warning)] | ||
| [InlineData(HttpStatusCode.BadRequest, LogLevel.Warning)] | ||
| [InlineData(HttpStatusCode.InternalServerError, LogLevel.Error)] | ||
| public async Task StatusCodeLogLevelRules_MatchesConfiguredRule(HttpStatusCode statusCode, LogLevel expectedLevel) | ||
| { | ||
| var options = new LoggingOptions | ||
| { | ||
| StatusCodeLogLevelRules = | ||
| [ | ||
| new HttpStatusCodeLogLevelRule { FromStatusCode = 400, ToStatusCode = 499, LogLevel = LogLevel.Warning }, | ||
| new HttpStatusCodeLogLevelRule { FromStatusCode = 500, ToStatusCode = 599, LogLevel = LogLevel.Error }, | ||
| ] | ||
| }; | ||
|
|
||
| var fakeLogger = new FakeLogger<HttpClientLogger>(); | ||
| using var httpResponseMessage = new HttpResponseMessage(statusCode); | ||
|
|
||
| using var handler = CreateHandler(fakeLogger, options, httpResponseMessage); | ||
| using var client = new HttpClient(handler); | ||
| using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.com/test"); | ||
|
|
||
| await client.SendAsync(httpRequestMessage, CancellationToken.None); | ||
|
|
||
| var logRecords = fakeLogger.Collector.GetSnapshot(); | ||
| var logRecord = Assert.Single(logRecords); | ||
| Assert.Equal(expectedLevel, logRecord.Level); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task StatusCodeLogLevelRules_FirstMatchWins() | ||
| { | ||
| var options = new LoggingOptions | ||
| { | ||
| StatusCodeLogLevelRules = | ||
| [ | ||
| new HttpStatusCodeLogLevelRule { FromStatusCode = 404, LogLevel = LogLevel.Debug }, | ||
| new HttpStatusCodeLogLevelRule { FromStatusCode = 400, ToStatusCode = 499, LogLevel = LogLevel.Warning }, | ||
| ] | ||
| }; | ||
|
|
||
| var fakeLogger = new FakeLogger<HttpClientLogger>(); | ||
| using var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.NotFound); | ||
|
|
||
| using var handler = CreateHandler(fakeLogger, options, httpResponseMessage); | ||
| using var client = new HttpClient(handler); | ||
| using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.com/test"); | ||
|
|
||
| await client.SendAsync(httpRequestMessage, CancellationToken.None); | ||
|
|
||
| var logRecords = fakeLogger.Collector.GetSnapshot(); | ||
| var logRecord = Assert.Single(logRecords); | ||
| Assert.Equal(LogLevel.Debug, logRecord.Level); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task StatusCodeLogLevelRules_NoMatch_FallsBackToDefaultBehavior() | ||
| { | ||
| var options = new LoggingOptions | ||
| { | ||
| StatusCodeLogLevelRules = | ||
| [ | ||
| new HttpStatusCodeLogLevelRule { FromStatusCode = 404, LogLevel = LogLevel.Debug }, | ||
| ] | ||
| }; | ||
|
|
||
| var fakeLogger = new FakeLogger<HttpClientLogger>(); | ||
| using var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError); | ||
|
|
||
| using var handler = CreateHandler(fakeLogger, options, httpResponseMessage); | ||
| using var client = new HttpClient(handler); | ||
| using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.com/test"); | ||
|
|
||
| await client.SendAsync(httpRequestMessage, CancellationToken.None); | ||
|
|
||
| var logRecords = fakeLogger.Collector.GetSnapshot(); | ||
| var logRecord = Assert.Single(logRecords); | ||
| Assert.Equal(LogLevel.Error, logRecord.Level); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task StatusCodeLogLevelRules_EmptyRules_UsesDefaultBehavior() | ||
| { | ||
| var options = new LoggingOptions(); | ||
|
|
||
| var fakeLogger = new FakeLogger<HttpClientLogger>(); | ||
| using var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK); | ||
|
|
||
| using var handler = CreateHandler(fakeLogger, options, httpResponseMessage); | ||
| using var client = new HttpClient(handler); | ||
| using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.com/test"); | ||
|
|
||
| await client.SendAsync(httpRequestMessage, CancellationToken.None); | ||
|
|
||
| var logRecords = fakeLogger.Collector.GetSnapshot(); | ||
| var logRecord = Assert.Single(logRecords); | ||
| Assert.Equal(LogLevel.Information, logRecord.Level); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ExceptionLogLevel_UsesConfiguredLevel() | ||
| { | ||
| var options = new LoggingOptions | ||
| { | ||
| ExceptionLogLevel = LogLevel.Warning, | ||
| }; | ||
|
|
||
| var exception = new HttpRequestException("test"); | ||
| var fakeLogger = new FakeLogger<HttpClientLogger>(); | ||
|
|
||
| using var handler = new TestLoggingHandler( | ||
| new HttpClientLogger( | ||
| fakeLogger, | ||
| Mock.Of<IHttpRequestReader>(), | ||
| [], | ||
| options), | ||
| new TestingHandlerStub((_, _) => throw exception)); | ||
|
|
||
| using var client = new HttpClient(handler); | ||
| using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.com/test"); | ||
|
|
||
| await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(httpRequestMessage, CancellationToken.None)); | ||
|
|
||
| var logRecords = fakeLogger.Collector.GetSnapshot(); | ||
| var logRecord = Assert.Single(logRecords); | ||
| Assert.Equal(LogLevel.Warning, logRecord.Level); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task ExceptionLogLevel_DefaultIsError() | ||
| { | ||
| var options = new LoggingOptions(); | ||
|
|
||
| var exception = new HttpRequestException("test"); | ||
| var fakeLogger = new FakeLogger<HttpClientLogger>(); | ||
|
|
||
| using var handler = new TestLoggingHandler( | ||
| new HttpClientLogger( | ||
| fakeLogger, | ||
| Mock.Of<IHttpRequestReader>(), | ||
| [], | ||
| options), | ||
| new TestingHandlerStub((_, _) => throw exception)); | ||
|
|
||
| using var client = new HttpClient(handler); | ||
| using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.com/test"); | ||
|
|
||
| await Assert.ThrowsAsync<HttpRequestException>(() => client.SendAsync(httpRequestMessage, CancellationToken.None)); | ||
|
|
||
| var logRecords = fakeLogger.Collector.GetSnapshot(); | ||
| var logRecord = Assert.Single(logRecords); | ||
| Assert.Equal(LogLevel.Error, logRecord.Level); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task StatusCodeLogLevelRules_ExactMatch_WithNullToStatusCode() | ||
| { | ||
| var options = new LoggingOptions | ||
| { | ||
| StatusCodeLogLevelRules = | ||
| [ | ||
| new HttpStatusCodeLogLevelRule { FromStatusCode = 429, ToStatusCode = null, LogLevel = LogLevel.Warning }, | ||
| ] | ||
| }; | ||
|
|
||
| var fakeLogger = new FakeLogger<HttpClientLogger>(); | ||
| using var httpResponseMessage = new HttpResponseMessage((HttpStatusCode)429); | ||
|
|
||
| using var handler = CreateHandler(fakeLogger, options, httpResponseMessage); | ||
| using var client = new HttpClient(handler); | ||
| using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.com/test"); | ||
|
|
||
| await client.SendAsync(httpRequestMessage, CancellationToken.None); | ||
|
|
||
| var logRecords = fakeLogger.Collector.GetSnapshot(); | ||
| var logRecord = Assert.Single(logRecords); | ||
| Assert.Equal(LogLevel.Warning, logRecord.Level); | ||
| } | ||
|
|
||
| private static TestLoggingHandler CreateHandler( | ||
| FakeLogger<HttpClientLogger> fakeLogger, | ||
| LoggingOptions options, | ||
| HttpResponseMessage response) | ||
| { | ||
| var mockHeadersRedactor = new Mock<IHttpHeadersRedactor>(); | ||
| mockHeadersRedactor | ||
| .Setup(r => r.Redact(It.IsAny<IEnumerable<string>>(), It.IsAny<DataClassification>())) | ||
| .Returns("Redacted"); | ||
|
|
||
| var headersReader = new HttpHeadersReader(options.ToOptionsMonitor(), mockHeadersRedactor.Object); | ||
|
|
||
| return new TestLoggingHandler( | ||
| new HttpClientLogger( | ||
| fakeLogger, | ||
| new HttpRequestReader( | ||
| options, | ||
| Mock.Of<IHttpRouteFormatter>(), | ||
| Mock.Of<IHttpRouteParser>(), | ||
| headersReader, | ||
| Mock.Of<IOutgoingRequestContext>()), | ||
| [], | ||
| options), | ||
| new TestingHandlerStub((_, _) => Task.FromResult(response))); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.