Пример #1
0
    /// <summary>
    ///     Logs the request sent to server and corresponding response
    /// </summary>
    /// <param name="request"></param>
    /// <param name="response"></param>
    /// <param name="durationMs"></param>
    private void LogRequest(HttpRequestMessage request, ResponseResult response, double durationMs)
    {
        var requestToLog = new RequestToLog
        {
            resource = request.RequestUri.PathAndQuery,
            // Parameters are custom anonymous objects in order to have the parameter type as a nice string
            // otherwise it will just show the enum value
            parameters = request.Headers.Select(parameter => new RequestParameter
            {
                name  = parameter.Key,
                value = parameter.Value,
                type  = parameter.GetType().ToString()
            }),
            // ToString() here to have the method as a nice string otherwise it will just show the enum value
            method = request.Method.ToString(),
            // This will generate the actual Uri used in the request
            uri = request.RequestUri
        };

        var responseToLog = new ResponseToLog
        {
            statusCode = response.StatusCode,
            content    = response.Content,
            headers    = response.Headers.ToDictionary(o => o.Key, o => string.Join(Environment.NewLine, o.Value)),
            // The Uri that actually responded (could be different from the requestUri if a redirection occurred)
            responseUri  = response.Request.RequestUri,
            errorMessage = response.ErrorMessage,
            durationMs   = durationMs
        };

        logger.LogRequest(requestToLog, responseToLog, durationMs);
    }
        /// <inheritdoc />
        public async Task LogRequest(RequestDetails request)
        {
            if (ShouldSkip(request))
            {
                return;
            }

            using var requestScope = RequestScope(request);
            await _requestLogger.LogRequest(_logger, request);
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            await requestLogger.LogRequest(request, cancellationToken).ConfigureAwait(false);

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

            await requestLogger.LogResponse(response, cancellationToken).ConfigureAwait(false);

            return(response);
        }
        public TestRunMatcherModule(IRequestLogger logger, ITestMatchController testMatcherController) : base("/TestRunMatcher")
        {
            Get["/"] = _ => {
                logger.LogRequest(Request);
                return(View[MainView]);
            };

            Post["/check"] = _ => {
                logger.LogRequest(Request);
                var mainPageModel = new MainPageModel(Request.Form);
                Tuple <object, string> renderData;
                try {
                    var result = testMatcherController.MatchTestRuns(mainPageModel.OldRunUrl, mainPageModel.NewRunUrl);
                    renderData = HandleResult(mainPageModel, result);
                } catch (Exception ex) {
                    renderData = HandleError(mainPageModel, ex.Message + Environment.NewLine + ex.StackTrace);
                }
                return(renderData.Map((model, view) => View[view, model]));
            };
        }
 protected void CreateLog(HttpContext context, IRequestLogger requestLogger, string requestBody,
                          string responseBody)
 {
     requestLogger.LogRequest(
         clientAddress: GetClientAddress(context),
         requestUrl: GetUrl(context),
         requestMethod: context.Request.Method,
         requestHeaders: context.Request.Headers,
         requestBody: requestBody,
         responseStatus: context.Response.StatusCode.ToString(),
         responseHeaders: context.Response.Headers,
         responseBody: responseBody);
 }
Пример #6
0
        private void FinishRequest(OnPremiseConnectorRequest request, IOnPremiseConnectorResponse response, LinkInformation link, string path, HttpStatusCode statusCode)
        {
            if (request == null)
            {
                return;
            }

            request.RequestFinished = DateTime.UtcNow;

            _logger?.Verbose("Finishing request. request-id={RequestId}, link-id={LinkId}, link-name={LinkName}, on-premise-duration={RemoteDuration}, global-duration={GlobalDuration}", request.RequestId, link.Id, link.SymbolicName, response?.RequestFinished - response?.RequestStarted, request.RequestFinished - request.RequestStarted);

            _traceManager.Trace(request, response, link.TraceConfigurationIds);
            _requestLogger.LogRequest(request, response, link.Id, _backendCommunication.OriginId, path, statusCode);
        }
Пример #7
0
        public async Task Invoke(HttpContext context)
        {
            Stopwatch sw = Stopwatch.StartNew();

            // Call the next delegate/middleware in the pipeline
            await _next(context);

            sw.Stop();

            await _requestLogger.LogRequest(context, sw.ElapsedMilliseconds);

            if (context.Items.ContainsKey(Stactive.StactiveEventsKey))
            {
                ProcessEvents(context);
            }
        }
Пример #8
0
        private void FinishRequest(IOnPremiseConnectorRequest request, IOnPremiseConnectorResponse response, Guid linkId, string path, HttpStatusCode statusCode)
        {
            request.RequestFinished = DateTime.UtcNow;

            _logger?.Verbose("Finishing request. request-id={RequestId}, link-id={LinkId}, on-premise-duration={RemoteDuration}, global-duration={GlobalDuration}", request.RequestId, linkId, response?.RequestFinished - response?.RequestStarted, request.RequestFinished - request.RequestStarted);

            // TODO this may be debounced for e.g. 5 minutes to skip querying on each request in future release
            var currentTraceConfigurationId = _traceManager.GetCurrentTraceConfigurationId(linkId);

            if (currentTraceConfigurationId != null)
            {
                _traceManager.Trace(request, response, currentTraceConfigurationId.Value);
            }

            _requestLogger.LogRequest(request, response, linkId, _backendCommunication.OriginId, path, statusCode);
        }
Пример #9
0
        public async Task <IHttpActionResult> PingAsync(Guid id)
        {
            var requestId = Guid.NewGuid().ToString();
            var onPremiseConnectorRequest = new OnPremiseConnectorRequest
            {
                HttpMethod     = "PING",
                Url            = "",
                RequestStarted = DateTime.UtcNow,
                OriginId       = _backendCommunication.OriginId,
                RequestId      = requestId
            };

            await _backendCommunication.SendOnPremiseConnectorRequest(id.ToString(), onPremiseConnectorRequest);

            var onPremiseTargetReponse = await _backendCommunication.GetResponseAsync(requestId);

            onPremiseConnectorRequest.RequestFinished = DateTime.UtcNow;

            _requestLogger.LogRequest(onPremiseConnectorRequest, onPremiseTargetReponse, HttpStatusCode.OK, id, _backendCommunication.OriginId, "invalid/Ping.local/");

            return(Ok());
        }
Пример #10
0
        public virtual bool HandleRequest(Uri referrer, Uri urlNotFound, out CustomRedirect foundRedirect)
        {
            var redirect = _redirectHandler.Find(urlNotFound);

            foundRedirect = null;

            if (redirect != null)
            {
                // Url has been deleted from this site
                if (redirect.State.Equals((int)RedirectState.Deleted))
                {
                    foundRedirect = redirect;
                    return(true);
                }

                if (redirect.State.Equals((int)RedirectState.Saved))
                {
                    // Found it, however, we need to make sure we're not running in an
                    // infinite loop. The new url must not be the referrer to this page
                    if (string.Compare(redirect.NewUrl, urlNotFound.PathAndQuery, StringComparison.InvariantCultureIgnoreCase) != 0)
                    {
                        foundRedirect = redirect;
                        return(true);
                    }
                }
            }
            else
            {
                // log request to database - if logging is turned on.
                if (_configuration.Logging == LoggerMode.On)
                {
                    // Safe logging
                    var logUrl = _configuration.LogWithHostname ? urlNotFound.ToString() : urlNotFound.PathAndQuery;
                    _requestLogger.LogRequest(logUrl, referrer?.ToString());
                }
            }
            return(false);
        }
Пример #11
0
        public async Task <IHttpActionResult> SendPing(Guid id)
        {
            var requestId = Guid.NewGuid().ToString();
            var request   = new OnPremiseConnectorRequest()
            {
                HttpMethod     = "PING",
                Url            = String.Empty,
                RequestStarted = DateTime.UtcNow,
                OriginId       = _backendCommunication.OriginId,
                RequestId      = requestId
            };

            var task = _backendCommunication.GetResponseAsync(requestId);

            _backendCommunication.SendOnPremiseConnectorRequest(id, request);

            var response = await task.ConfigureAwait(false);

            request.RequestFinished = DateTime.UtcNow;
            _requestLogger.LogRequest(request, response, id, _backendCommunication.OriginId, "DEBUG/PING/", response?.StatusCode);

            return((response != null) ? (IHttpActionResult)Ok() : new StatusCodeResult(HttpStatusCode.GatewayTimeout, Request));
        }
Пример #12
0
 private void AssertRequestNotLogged(Uri referrer, Uri urlNotFound)
 {
     A.CallTo(() => _requestLogger.LogRequest(urlNotFound.PathAndQuery, referrer.ToString()))
     .MustNotHaveHappened();
 }
Пример #13
0
        public async Task <HttpResponseMessage> Relay(string path)
        {
            _logger.Trace("Relaying http {0} {1}", path, ControllerContext.Request.Method);

            if (path == null)
            {
                _logger.Info("Path is not set.");
                return(NotFound());
            }

            var pathInformation = _pathSplitter.Split(path);
            var link            = _linkRepository.GetLink(pathInformation.UserName);

            if (link == null)
            {
                _logger.Info("Link for requested path {0} not found", path);
                return(NotFound());
            }

            if (link.IsDisabled)
            {
                _logger.Info("{0}: Link {1} is disabled", link.Id, link.SymbolicName);
                return(NotFound());
            }

            if (string.IsNullOrWhiteSpace(pathInformation.PathWithoutUserName))
            {
                _logger.Info("{0}: Path without username is not found. Wrong path information: {1}", link.Id, path);
                return(NotFound());
            }

            if (link.AllowLocalClientRequestsOnly && !Request.IsLocal())
            {
                _logger.Info("{0}: Link {1} only allows local requests.", link.Id, link.SymbolicName);
                return(NotFound());
            }

            _logger.Trace("{0}: Building on premise connector request. Origin Id: {1}, Path: {2}", link.Id, _backendCommunication.OriginId, path);
            var onPremiseConnectorRequest =
                (OnPremiseConnectorRequest)
                await _onPremiseRequestBuilder.BuildFrom(Request, _backendCommunication.OriginId, pathInformation.PathWithoutUserName);

            _logger.Trace("{0}: Sending on premise connector request.", link.Id);
            await _backendCommunication.SendOnPremiseConnectorRequest(link.Id.ToString(), onPremiseConnectorRequest);

            _logger.Trace("{0}: Waiting for response. Request Id", onPremiseConnectorRequest.RequestId);
            var onPremiseTargetReponse = await _backendCommunication.GetResponseAsync(onPremiseConnectorRequest.RequestId);

            if (onPremiseTargetReponse != null)
            {
                _logger.Trace("{0}: Response received from {1}", link.Id, onPremiseTargetReponse.RequestId);
            }
            else
            {
                _logger.Trace("{0}: On Premise Timeout", link.Id);
            }

            var response = _httpResponseMessageBuilder.BuildFrom(onPremiseTargetReponse, link);

            onPremiseConnectorRequest.RequestFinished = DateTime.UtcNow;

            var currentTraceConfigurationId = _traceManager.GetCurrentTraceConfigurationId(link.Id);

            if (currentTraceConfigurationId != null)
            {
                _traceManager.Trace(onPremiseConnectorRequest, onPremiseTargetReponse, currentTraceConfigurationId.Value);
            }

            _requestLogger.LogRequest(onPremiseConnectorRequest, onPremiseTargetReponse, response.StatusCode, link.Id, _backendCommunication.OriginId, path);

            return(response);
        }
 protected void Application_LogRequest(Object sender, EventArgs e)
 {
     _requestLogger.LogRequest(Request);
 }