Skip to content

Commit

Permalink
[dotnet] Log http requests/responses via internal DiagnosticsHttpHand…
Browse files Browse the repository at this point in the history
…ler (SeleniumHQ#13978)

* [dotnet] Add Execution Context

* Added http status code validation

* update validation http status code validation as int

* Update http validation status code from 299 to 399

* Logs Response to HttpClientHandler

* update name

* revert http response message logger

* Remove White Space

* fix build error

* Update InterceptAsync Summary

* Update Logger field initialization

* Remove logger parameter in ResponseLoggerInterceptor method

* fix comment to add responseBody inside the if statement

* Update Delegating Handler and Remove unable to push files in local

* Update from null validation to status code

* Fix comment

* fix minor comments and adjust logic improvement

* Revert "fix minor comments and adjust logic improvement"

This reverts commit 4240536.

* Null check for response content

* Requests/Responses as single log message

* Pass logger from upstream

* Fix missing responses in log

* Put log message in parallel with sending a request

---------

Co-authored-by: Nikolay Borisenko <[email protected]>
  • Loading branch information
2 people authored and sandeepsuryaprasad committed Oct 29, 2024
1 parent 96fd010 commit ef7b1e7
Showing 1 changed file with 60 additions and 12 deletions.
72 changes: 60 additions & 12 deletions dotnet/src/webdriver/Remote/HttpCommandExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace OpenQA.Selenium.Remote
Expand Down Expand Up @@ -247,7 +247,14 @@ private void CreateHttpClient()

httpClientHandler.Proxy = this.Proxy;

this.client = new HttpClient(httpClientHandler);
HttpMessageHandler handler = httpClientHandler;

if (_logger.IsEnabled(LogEventLevel.Trace))
{
handler = new DiagnosticsHttpHandler(httpClientHandler, _logger);
}

this.client = new HttpClient(handler);
this.client.DefaultRequestHeaders.UserAgent.ParseAdd(this.UserAgent);
this.client.DefaultRequestHeaders.Accept.ParseAdd(RequestAcceptHeader);
this.client.DefaultRequestHeaders.ExpectContinue = false;
Expand Down Expand Up @@ -293,18 +300,8 @@ private async Task<HttpResponseInfo> MakeHttpRequest(HttpRequestInfo requestInfo
requestMessage.Content.Headers.ContentType = contentTypeHeader;
}

if (_logger.IsEnabled(LogEventLevel.Trace))
{
_logger.Trace($">> {requestMessage}");
}

using (HttpResponseMessage responseMessage = await this.client.SendAsync(requestMessage).ConfigureAwait(false))
{
if (_logger.IsEnabled(LogEventLevel.Trace))
{
_logger.Trace($"<< {responseMessage}");
}

HttpResponseInfo httpResponseInfo = new HttpResponseInfo();
httpResponseInfo.Body = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
httpResponseInfo.ContentType = responseMessage.Content.Headers.ContentType?.ToString();
Expand Down Expand Up @@ -395,5 +392,56 @@ private class HttpResponseInfo
public string Body { get; set; }
public string ContentType { get; set; }
}

/// <summary>
/// Internal diagnostic handler to log http requests/responses.
/// </summary>
private class DiagnosticsHttpHandler : DelegatingHandler
{
private readonly ILogger _logger;

public DiagnosticsHttpHandler(HttpMessageHandler messageHandler, ILogger logger)
: base(messageHandler)
{
_logger = logger;
}

/// <summary>
/// Sends the specified request and returns the associated response.
/// </summary>
/// <param name="request">The request to be sent.</param>
/// <param name="cancellationToken">A CancellationToken object to allow for cancellation of the request.</param>
/// <returns>The http response message content.</returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
StringBuilder requestLogMessageBuilder = new();
requestLogMessageBuilder.AppendFormat(">> {0}", request);

if (request.Content != null)
{
var requestContent = await request.Content.ReadAsStringAsync().ConfigureAwait(false);
requestLogMessageBuilder.AppendFormat("{0}{1}", Environment.NewLine, requestContent);
}

var responseTask = base.SendAsync(request, cancellationToken).ConfigureAwait(false);

_logger.Trace(requestLogMessageBuilder.ToString());

var response = await responseTask;

StringBuilder responseLogMessageBuilder = new();
responseLogMessageBuilder.AppendFormat("<< {0}", response);

if (!response.IsSuccessStatusCode && response.Content != null)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
responseLogMessageBuilder.AppendFormat("{0}{1}", Environment.NewLine, responseContent);
}

_logger.Trace(responseLogMessageBuilder.ToString());

return response;
}
}
}
}

0 comments on commit ef7b1e7

Please sign in to comment.