-
Notifications
You must be signed in to change notification settings - Fork 5.3k
[HttpClientFactory] Do not log query string by default #103769
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
21 commits
Select commit
Hold shift + click to select a range
d3b0e77
Do not log query strings in HttpClientFactory
antonfirsov af01fc6
shuffle tests
antonfirsov e3fb184
Update GetUriString
antonfirsov ea4b8ad
add tests for relative Uri logging
antonfirsov 7a7bf09
remove unnecessary using
antonfirsov 098279a
move log message implementation into LogHelper, introduce an environm…
antonfirsov 9ebabcc
redact query string with '*'
antonfirsov 0d49a23
suggestion
antonfirsov f6c3095
rename switch
antonfirsov 8361df7
suggestions
antonfirsov 4d7a777
Merge branch 'main' into querystring-01
antonfirsov 236fc8d
Merge branch 'querystring-01' of https://github.com/antonfirsov/runti…
antonfirsov b9daee4
adjustments
antonfirsov a894f8b
handle fragment
antonfirsov fed974b
remove userinfo from absolute Uri-s
antonfirsov ca88ab0
Redact relative Uri unconditionally
antonfirsov e711ec9
Merge branch 'main' into querystring-01
antonfirsov e557330
Harmonize redaction:
antonfirsov 902f459
AggressiveInlining
antonfirsov 74b1d04
save 1 allocation in LoggingScopeHttpMessageHandler
antonfirsov 956de73
Update src/libraries/Microsoft.Extensions.Http/src/Logging/LogHelper.cs
antonfirsov 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
193 changes: 193 additions & 0 deletions
193
src/libraries/Microsoft.Extensions.Http/src/Logging/LogHelper.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,193 @@ | ||
| // 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.Diagnostics; | ||
| using System.Net.Http; | ||
| using System.Runtime.CompilerServices; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.Internal; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Microsoft.Extensions.Http.Logging | ||
| { | ||
| internal static class LogHelper | ||
| { | ||
| private static readonly LogDefineOptions s_skipEnabledCheckLogDefineOptions = new LogDefineOptions() { SkipEnabledCheck = true }; | ||
| private static readonly bool s_disableUriRedaction = GetDisableUriRedactionSettingValue(); | ||
|
|
||
| private static class EventIds | ||
| { | ||
| public static readonly EventId RequestStart = new EventId(100, "RequestStart"); | ||
| public static readonly EventId RequestEnd = new EventId(101, "RequestEnd"); | ||
|
|
||
| public static readonly EventId RequestHeader = new EventId(102, "RequestHeader"); | ||
| public static readonly EventId ResponseHeader = new EventId(103, "ResponseHeader"); | ||
|
|
||
| public static readonly EventId PipelineStart = new EventId(100, "RequestPipelineStart"); | ||
| public static readonly EventId PipelineEnd = new EventId(101, "RequestPipelineEnd"); | ||
|
|
||
| public static readonly EventId RequestPipelineRequestHeader = new EventId(102, "RequestPipelineRequestHeader"); | ||
| public static readonly EventId RequestPipelineResponseHeader = new EventId(103, "RequestPipelineResponseHeader"); | ||
| } | ||
|
|
||
| private static readonly Action<ILogger, HttpMethod, string?, Exception?> _requestStart = LoggerMessage.Define<HttpMethod, string?>( | ||
| LogLevel.Information, | ||
| EventIds.RequestStart, | ||
| "Sending HTTP request {HttpMethod} {Uri}", | ||
| s_skipEnabledCheckLogDefineOptions); | ||
|
|
||
| private static readonly Action<ILogger, double, int, Exception?> _requestEnd = LoggerMessage.Define<double, int>( | ||
| LogLevel.Information, | ||
| EventIds.RequestEnd, | ||
| "Received HTTP response headers after {ElapsedMilliseconds}ms - {StatusCode}"); | ||
|
|
||
| private static readonly Func<ILogger, HttpMethod, string?, IDisposable?> _beginRequestPipelineScope = LoggerMessage.DefineScope<HttpMethod, string?>("HTTP {HttpMethod} {Uri}"); | ||
|
|
||
| private static readonly Action<ILogger, HttpMethod, string?, Exception?> _requestPipelineStart = LoggerMessage.Define<HttpMethod, string?>( | ||
| LogLevel.Information, | ||
| EventIds.PipelineStart, | ||
| "Start processing HTTP request {HttpMethod} {Uri}"); | ||
|
|
||
| private static readonly Action<ILogger, double, int, Exception?> _requestPipelineEnd = LoggerMessage.Define<double, int>( | ||
| LogLevel.Information, | ||
| EventIds.PipelineEnd, | ||
| "End processing HTTP request after {ElapsedMilliseconds}ms - {StatusCode}"); | ||
|
|
||
| private static bool GetDisableUriRedactionSettingValue() | ||
| { | ||
| if (AppContext.TryGetSwitch("System.Net.Http.DisableUriRedaction", out bool value)) | ||
| { | ||
| return value; | ||
| } | ||
|
|
||
| string? envVar = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_HTTP_DISABLEURIREDACTION"); | ||
|
|
||
| if (bool.TryParse(envVar, out value)) | ||
| { | ||
| return value; | ||
| } | ||
| else if (uint.TryParse(envVar, out uint intVal)) | ||
| { | ||
| return intVal != 0; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| public static void LogRequestStart(this ILogger logger, HttpRequestMessage request, Func<string, bool> shouldRedactHeaderValue) | ||
| { | ||
| // We check here to avoid allocating in the GetRedactedUriString call unnecessarily | ||
| if (logger.IsEnabled(LogLevel.Information)) | ||
| { | ||
| _requestStart(logger, request.Method, GetRedactedUriString(request.RequestUri), null); | ||
| } | ||
|
|
||
| if (logger.IsEnabled(LogLevel.Trace)) | ||
| { | ||
| logger.Log( | ||
| LogLevel.Trace, | ||
| EventIds.RequestHeader, | ||
| new HttpHeadersLogValue(HttpHeadersLogValue.Kind.Request, request.Headers, request.Content?.Headers, shouldRedactHeaderValue), | ||
| null, | ||
| (state, ex) => state.ToString()); | ||
| } | ||
| } | ||
|
|
||
| public static void LogRequestEnd(this ILogger logger, HttpResponseMessage response, TimeSpan duration, Func<string, bool> shouldRedactHeaderValue) | ||
| { | ||
| _requestEnd(logger, duration.TotalMilliseconds, (int)response.StatusCode, null); | ||
|
|
||
| if (logger.IsEnabled(LogLevel.Trace)) | ||
| { | ||
| logger.Log( | ||
| LogLevel.Trace, | ||
| EventIds.ResponseHeader, | ||
| new HttpHeadersLogValue(HttpHeadersLogValue.Kind.Response, response.Headers, response.Content?.Headers, shouldRedactHeaderValue), | ||
| null, | ||
| (state, ex) => state.ToString()); | ||
| } | ||
| } | ||
|
|
||
| public static IDisposable? BeginRequestPipelineScope(this ILogger logger, HttpRequestMessage request, out string? formattedUri) | ||
| { | ||
| formattedUri = GetRedactedUriString(request.RequestUri); | ||
| return _beginRequestPipelineScope(logger, request.Method, formattedUri); | ||
| } | ||
|
|
||
| public static void LogRequestPipelineStart(this ILogger logger, HttpRequestMessage request, string? formattedUri, Func<string, bool> shouldRedactHeaderValue) | ||
| { | ||
| _requestPipelineStart(logger, request.Method, formattedUri, null); | ||
|
|
||
| if (logger.IsEnabled(LogLevel.Trace)) | ||
| { | ||
| logger.Log( | ||
| LogLevel.Trace, | ||
| EventIds.RequestPipelineRequestHeader, | ||
| new HttpHeadersLogValue(HttpHeadersLogValue.Kind.Request, request.Headers, request.Content?.Headers, shouldRedactHeaderValue), | ||
| null, | ||
| (state, ex) => state.ToString()); | ||
| } | ||
| } | ||
|
|
||
| public static void LogRequestPipelineEnd(this ILogger logger, HttpResponseMessage response, TimeSpan duration, Func<string, bool> shouldRedactHeaderValue) | ||
| { | ||
| _requestPipelineEnd(logger, duration.TotalMilliseconds, (int)response.StatusCode, null); | ||
|
|
||
| if (logger.IsEnabled(LogLevel.Trace)) | ||
| { | ||
| logger.Log( | ||
| LogLevel.Trace, | ||
| EventIds.RequestPipelineResponseHeader, | ||
| new HttpHeadersLogValue(HttpHeadersLogValue.Kind.Response, response.Headers, response.Content?.Headers, shouldRedactHeaderValue), | ||
| null, | ||
| (state, ex) => state.ToString()); | ||
| } | ||
| } | ||
|
|
||
| internal static string? GetRedactedUriString(Uri? uri) | ||
| { | ||
| if (uri is null) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| if (s_disableUriRedaction) | ||
| { | ||
| return uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.ToString(); | ||
| } | ||
|
|
||
| if (!uri.IsAbsoluteUri) | ||
antonfirsov marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| // We cannot guarantee the redaction of UserInfo for relative Uris without implementing some subset of Uri parsing in this package. | ||
| // To avoid this, we redact the whole Uri. Seeing a relative Uri in LoggingHttpMessageHandler or LoggingScopeHttpMessageHandler | ||
| // requires a custom handler chain with custom expansion logic implemented by the user's HttpMessageHandler. | ||
| // In such advanced scenarios we recommend users to log the Uri in their handler. | ||
| return "*"; | ||
| } | ||
|
|
||
| string pathAndQuery = uri.PathAndQuery; | ||
| int queryIndex = pathAndQuery.IndexOf('?'); | ||
|
|
||
| bool redactQuery = queryIndex >= 0 && // Query is present. | ||
| queryIndex < pathAndQuery.Length - 1; // Query is not empty. | ||
|
|
||
| return (redactQuery, uri.IsDefaultPort) switch | ||
| { | ||
| (true, true) => $"{uri.Scheme}://{uri.Host}{GetPath(pathAndQuery, queryIndex)}*", | ||
| (true, false) => $"{uri.Scheme}://{uri.Host}:{uri.Port}{GetPath(pathAndQuery, queryIndex)}*", | ||
| (false, true) => $"{uri.Scheme}://{uri.Host}{pathAndQuery}", | ||
| (false, false) => $"{uri.Scheme}://{uri.Host}:{uri.Port}{pathAndQuery}" | ||
| }; | ||
|
|
||
| #if NET | ||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| static ReadOnlySpan<char> GetPath(string pathAndQuery, int queryIndex) => pathAndQuery.AsSpan(0, queryIndex + 1); | ||
| #else | ||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| static string GetPath(string pathAndQuery, int queryIndex) => pathAndQuery.Substring(0, queryIndex + 1); | ||
| #endif | ||
| } | ||
| } | ||
| } | ||
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
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.