Repository navigation
HttpClient logging based on new .NET 8 runtime APIs #4224
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
Merged
Merged
Changes from all commits
Commits
Show all changes
39 commits
Select commit
Hold shift + click to select a range
4614a5a
fixes + tests
xakep139 8e30724
try to use new logging APIs
xakep139 8dc3a32
minor fix
xakep139 abf5d88
update dependencies
xakep139 8a5ae6a
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 46b3c52
implement async logging part
xakep139 e1eb602
simplify extensions
xakep139 e9fee43
fixes + further dev
xakep139 2026789
further dev
xakep139 57be31d
fixes + update tests
xakep139 bff6a42
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 7ae1508
CR
xakep139 82a3f0c
Update src/LegacySupport/TaskWaitAsync/TaskExtensions.cs
xakep139 f223f8b
fix a warning
xakep139 7f17330
CR
xakep139 b9e6e7d
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 30bc9e8
fixes after merge
xakep139 087a327
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 cc6086c
fix an edge case + test
xakep139 08d093d
fix more bugs + tests
xakep139 6fa3547
minor fixes
xakep139 cec1ae8
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 a2a15ed
fixes after merge with main
xakep139 a7c3428
fix a bug in auto activation
xakep139 4f2bfbf
Update AutoActivationExtensions.cs
xakep139 f9039f5
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 ab8c33b
CR
xakep139 ee19b43
Leverage KeyedServices feature in HttpClient logging (#4253)
xakep139 c0f4a9c
merge with main
xakep139 687509c
fixes after merge
xakep139 cf5daef
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 af7dbf1
resolve a TODO item;
xakep139 5f69923
fix tests;
xakep139 ac0d2eb
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 67605df
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 c05d8e1
increase code coverage;
xakep139 9b1ea6e
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 045a6ca
Merge branch 'main' into xakep139/outgoing-http-logging
xakep139 7203050
resolve the last TODO item
xakep139 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
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
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
228 changes: 56 additions & 172 deletions
228
src/Libraries/Microsoft.Extensions.Http.Telemetry/Logging/HttpClientLoggingExtensions.cs
Large diffs are not rendered by default.
Oops, something went wrong.
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
242 changes: 242 additions & 0 deletions
242
src/Libraries/Microsoft.Extensions.Http.Telemetry/Logging/Internal/HttpClientLogger.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,242 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Linq; | ||
| using System.Net.Http; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Http.Logging; | ||
| using Microsoft.Extensions.Http.Telemetry.Logging.Internal; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Extensions.ObjectPool; | ||
| using Microsoft.Extensions.Options; | ||
| using Microsoft.Extensions.Telemetry.Logging; | ||
| using Microsoft.Shared.Pools; | ||
|
|
||
| namespace Microsoft.Extensions.Http.Telemetry.Logging; | ||
|
|
||
| internal sealed class HttpClientLogger : IHttpClientAsyncLogger | ||
| { | ||
| private const string SyncLoggingExceptionMessage = "Synchronous logging is not supported"; | ||
|
|
||
| private readonly ObjectPool<List<KeyValuePair<string, string>>> _headersPool = | ||
| PoolFactory.CreateListPool<KeyValuePair<string, string>>(); | ||
|
|
||
| private readonly ObjectPool<LogRecord> _logRecordPool = | ||
| PoolFactory.CreateResettingPool<LogRecord>(); | ||
|
|
||
| private readonly bool _logRequestStart; | ||
| private readonly bool _logResponseHeaders; | ||
| private readonly bool _logRequestHeaders; | ||
| private readonly bool _pathParametersRedactionSkipped; | ||
| private ILogger<HttpClientLogger> _logger; | ||
| private IHttpRequestReader _httpRequestReader; | ||
| private IHttpClientLogEnricher[] _enrichers; | ||
|
|
||
| public HttpClientLogger( | ||
| IServiceProvider serviceProvider, | ||
| ILogger<HttpClientLogger> logger, | ||
| IEnumerable<IHttpClientLogEnricher> enrichers, | ||
| IOptionsMonitor<LoggingOptions> optionsMonitor, | ||
| [ServiceKey] string? serviceKey = null) | ||
| : this( | ||
| logger, | ||
| serviceProvider.GetRequiredOrKeyedRequiredService<IHttpRequestReader>(serviceKey), | ||
| enrichers, | ||
| optionsMonitor.GetKeyedOrCurrent(serviceKey)) | ||
| { | ||
| } | ||
|
|
||
| internal HttpClientLogger( | ||
| ILogger<HttpClientLogger> logger, | ||
| IHttpRequestReader httpRequestReader, | ||
| IEnumerable<IHttpClientLogEnricher> enrichers, | ||
| LoggingOptions options) | ||
| { | ||
| _logger = logger; | ||
| _httpRequestReader = httpRequestReader; | ||
| _enrichers = enrichers.Where(static x => x is not null).ToArray(); | ||
| _logRequestStart = options.LogRequestStart; | ||
| _logResponseHeaders = options.ResponseHeadersDataClasses.Count > 0; | ||
| _logRequestHeaders = options.RequestHeadersDataClasses.Count > 0; | ||
| _pathParametersRedactionSkipped = options.RequestPathParameterRedactionMode == HttpRouteParameterRedactionMode.None; | ||
| } | ||
|
|
||
| [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "The logger shouldn't throw")] | ||
| public async ValueTask<object?> LogRequestStartAsync(HttpRequestMessage request, CancellationToken cancellationToken = default) | ||
| { | ||
| var logRecord = _logRecordPool.Get(); | ||
|
|
||
| List<KeyValuePair<string, string>>? requestHeadersBuffer = null; | ||
| if (_logRequestHeaders) | ||
| { | ||
| requestHeadersBuffer = _headersPool.Get(); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| await _httpRequestReader.ReadRequestAsync(logRecord, request, requestHeadersBuffer, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| if (_logRequestStart) | ||
| { | ||
| Log.OutgoingRequest(_logger, LogLevel.Information, logRecord); | ||
| } | ||
|
|
||
| return logRecord; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| // If redaction is skipped, we can log unredacted request path; otherwise use "logRecord.Path" (even though it might not be set): | ||
| var pathToLog = _pathParametersRedactionSkipped | ||
| ? request.RequestUri?.AbsolutePath | ||
| : logRecord.Path; | ||
|
|
||
| Log.RequestReadError(_logger, ex, request.Method, request.RequestUri?.Host, pathToLog); | ||
|
|
||
| // Return back pooled objects (since the logRecord wasn't fully prepared): | ||
| _logRecordPool.Return(logRecord); | ||
|
|
||
| if (requestHeadersBuffer is not null) | ||
| { | ||
| _headersPool.Return(requestHeadersBuffer); | ||
| } | ||
|
|
||
| // Recommendation is to swallow the exception (logger shouldn't throw), so we don't re-throw here: | ||
| return null; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As @CarnaViire pointed, a logger shouldn't re-throw (but it will change our current behavior) |
||
| } | ||
| } | ||
|
|
||
| public async ValueTask LogRequestStopAsync( | ||
| object? context, | ||
| HttpRequestMessage request, | ||
| HttpResponseMessage response, | ||
| TimeSpan elapsed, | ||
| CancellationToken cancellationToken = default) | ||
| => await LogResponseAsync(context, request, response, null, elapsed, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| public async ValueTask LogRequestFailedAsync( | ||
| object? context, | ||
| HttpRequestMessage request, | ||
| HttpResponseMessage? response, | ||
| Exception exception, | ||
| TimeSpan elapsed, | ||
| CancellationToken cancellationToken = default) | ||
| => await LogResponseAsync(context, request, response, exception, elapsed, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| public object? LogRequestStart(HttpRequestMessage request) | ||
| => throw new NotSupportedException(SyncLoggingExceptionMessage); | ||
|
|
||
| public void LogRequestStop(object? context, HttpRequestMessage request, HttpResponseMessage response, TimeSpan elapsed) | ||
| => throw new NotSupportedException(SyncLoggingExceptionMessage); | ||
|
|
||
| public void LogRequestFailed(object? context, HttpRequestMessage request, HttpResponseMessage? response, Exception exception, TimeSpan elapsed) | ||
| => throw new NotSupportedException(SyncLoggingExceptionMessage); | ||
|
|
||
| private static LogLevel GetLogLevel(LogRecord logRecord) | ||
| { | ||
| const int HttpErrorsRangeStart = 400; | ||
| const int HttpErrorsRangeEnd = 599; | ||
| int statusCode = logRecord.StatusCode!.Value; | ||
|
|
||
| if (statusCode >= HttpErrorsRangeStart && statusCode <= HttpErrorsRangeEnd) | ||
| { | ||
| return LogLevel.Error; | ||
| } | ||
|
|
||
| return LogLevel.Information; | ||
| } | ||
|
|
||
| [SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "The logger shouldn't throw")] | ||
| private async ValueTask LogResponseAsync( | ||
| object? context, | ||
| HttpRequestMessage request, | ||
| HttpResponseMessage? response, | ||
| Exception? exception, | ||
| TimeSpan elapsed, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| if (context is not LogRecord logRecord) | ||
| { | ||
| var requestState = response is null | ||
| ? "failed" | ||
| : "completed"; | ||
|
|
||
| Log.LoggerContextMissing(_logger, exception, requestState, request.Method, request.RequestUri?.Host); | ||
| return; | ||
| } | ||
|
|
||
| LoggerMessageState? loggerMessageState = null; | ||
| List<KeyValuePair<string, string>>? responseHeadersBuffer = null; | ||
| try | ||
| { | ||
| if (response is not null) | ||
| { | ||
| if (_logResponseHeaders) | ||
| { | ||
| responseHeadersBuffer = _headersPool.Get(); | ||
| } | ||
|
|
||
| await _httpRequestReader.ReadResponseAsync(logRecord, response, responseHeadersBuffer, cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
|
||
| loggerMessageState = LoggerMessageHelper.ThreadLocalState; | ||
| FillLogRecord(logRecord, loggerMessageState, in elapsed, request, response, exception); | ||
|
|
||
| if (exception is null) | ||
| { | ||
| Log.OutgoingRequest(_logger, GetLogLevel(logRecord), logRecord); | ||
| } | ||
| else | ||
| { | ||
| Log.OutgoingRequestError(_logger, logRecord, exception); | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| // Logger shouldn't throw, so we just log the exception and don't re-throw it: | ||
| Log.ResponseReadError(_logger, ex, request.Method, logRecord.Host, logRecord.Path); | ||
| } | ||
| finally | ||
| { | ||
| var requestHeadersBuffer = logRecord.RequestHeaders; // Store the value first, and then return logRecord to the pool. | ||
| _logRecordPool.Return(logRecord); | ||
| loggerMessageState?.Clear(); | ||
|
|
||
| if (responseHeadersBuffer is not null) | ||
| { | ||
| _headersPool.Return(responseHeadersBuffer); | ||
| } | ||
|
|
||
| if (requestHeadersBuffer is not null) | ||
| { | ||
| _headersPool.Return(requestHeadersBuffer); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| [SuppressMessage("Design", "CA1031:Do not catch general exception types", | ||
| Justification = "We intentionally catch all exception types to make Telemetry code resilient to failures.")] | ||
| private void FillLogRecord( | ||
| LogRecord logRecord, LoggerMessageState loggerMessageState, in TimeSpan elapsed, | ||
| HttpRequestMessage request, HttpResponseMessage? response, Exception? exception) | ||
| { | ||
| foreach (var enricher in _enrichers) | ||
| { | ||
| try | ||
| { | ||
| enricher.Enrich(loggerMessageState, request, response, exception); | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| Log.EnrichmentError(_logger, e, enricher.GetType().FullName, request.Method, logRecord.Host, logRecord.Path); | ||
| } | ||
| } | ||
|
|
||
| logRecord.EnrichmentTags = loggerMessageState; | ||
| logRecord.Duration = (long)elapsed.TotalMilliseconds; | ||
| } | ||
| } | ||
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
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.