public static void LogUserInformation(ILogger logger, IUserInformationProvider userInformationProvider)
        {
            if (userInformationProvider == null)
            {
                throw new ArgumentNullException(nameof(userInformationProvider));
            }

            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (userInformationProvider.IsAuthenticated())
            {
                BitJwtToken bitJwtToken = userInformationProvider.GetBitJwtToken();
                logger.AddLogData("UserId", bitJwtToken.UserId);
                if (bitJwtToken.CustomProps != null)
                {
                    foreach (var keyVal in bitJwtToken.CustomProps)
                    {
                        logger.AddLogData(keyVal.Key, keyVal.Value);
                    }
                }
                logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
                logger.AddLogData("ClientId", userInformationProvider.GetClientId());
            }
        }
Пример #2
0
        public virtual void Trace(HttpRequestMessage request, string category, TraceLevel level, Action <TraceRecord> traceAction)
        {
            if (request?.GetOwinContext() != null && (level == TraceLevel.Fatal || level == TraceLevel.Warn || level == TraceLevel.Error))
            {
                TraceRecord traceRecord = new TraceRecord(request, category, level);
                traceAction(traceRecord);

                IDependencyResolver scopeDependencyResolver = request.GetOwinContext().GetDependencyResolver();

                ILogger             logger             = scopeDependencyResolver.Resolve <ILogger>();
                IScopeStatusManager scopeStatusManager = scopeDependencyResolver.Resolve <IScopeStatusManager>();

                if (scopeStatusManager.WasSucceeded())
                {
                    scopeStatusManager.MarkAsFailed();
                }

                if (traceRecord.Exception != null)
                {
                    Exception exception = traceRecord.Exception;

                    if (exception is TargetInvocationException && exception.InnerException != null)
                    {
                        exception = exception.InnerException;
                    }
                    if (!logger.LogData.Any(d => d.Key == "X-CorrelationId"))
                    {
                        logger.AddLogData("X-CorrelationId", request.GetCorrelationId());
                    }
                    logger.AddLogData("WebExceptionType", exception.GetType().FullName);
                    logger.AddLogData("WebException", exception);
                    logger.AddLogData("WebApiErrorMessage", traceRecord.Message);
                }
            }
        }
Пример #3
0
 public static void LogUserInformation(ILogger logger, IUserInformationProvider userInformationProvider)
 {
     if (userInformationProvider.IsAuthenticated())
     {
         logger.AddLogData("UserId", userInformationProvider.GetCurrentUserId());
         logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
     }
 }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ILogger logger = actionContext.Request.GetOwinContext()
                             .GetDependencyResolver()
                             .Resolve <ILogger>();

            logger.AddLogData("OperationArgs", actionContext.ActionArguments.Where(arg => LogParameter(arg.Value)).ToArray());
            logger.AddLogData("OperationName", actionContext.ActionDescriptor.ActionName);
            logger.AddLogData("ControllerName", actionContext.ControllerContext.ControllerDescriptor.ControllerName);

            base.OnActionExecuting(actionContext);
        }
        public virtual async Task ClientsLogsControllerMustSaveLogsUsingLogger()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                ODataClient client = testEnvironment.Server.BuildODataClient(token: token, odataRouteName: "Bit");

                await client.Controller <ClientsLogsController, ClientLogDto>()
                .Action(nameof(ClientsLogsController.StoreClientLogs))
                .Set(new ClientsLogsController.StoreClientLogsParameters {
                    clientLogs = new[] { new ClientLogDto {
                                             Message = "1", Route = "R"
                                         } }
                })
                .ExecuteAsync();

                ILogger logger = TestDependencyManager.CurrentTestDependencyManager
                                 .Objects.OfType <ILogger>()
                                 .Last();

                A.CallTo(() => logger.LogWarningAsync("Client-Log"))
                .MustHaveHappened(Repeated.Exactly.Once);

                A.CallTo(() => logger.AddLogData("ClientLogs", A <IEnumerable <ClientLogDto> > .That.Matches(logs => logs.Single().Message == "1")))
                .MustHaveHappened(Repeated.Exactly.Once);
            }
        }
        public virtual async Task JsonParseErrorTest()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                HttpClient httpClient = testEnvironment.Server.BuildHttpClient(token);

                HttpResponseMessage response = await httpClient.PostAsJsonAsync("odata/Test/DtoWithEnum", new
                {
                    Id     = "SOME_STRING_INSTEAD_OF_INT",
                    Gender = "Man",
                    Test   = "string"
                });

                const string expectedErrorMessage = "Newtonsoft.Json.JsonReaderException: Could not convert string to integer: SOME_STRING_INSTEAD_OF_INT. Path 'Id', line 1, position 34.";

                Assert.AreEqual(false, response.IsSuccessStatusCode);
                using (StreamReader reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                    using (JsonTextReader jsonReader = new JsonTextReader(reader))
                    {
                        string errMessage = (await JToken.LoadAsync(jsonReader))["error"].Value <string>("message");
                        Assert.IsTrue(errMessage.Contains(expectedErrorMessage));
                    }

                ILogger logger = TestDependencyManager.CurrentTestDependencyManager
                                 .Objects.OfType <ILogger>()
                                 .Last();

                A.CallTo(() => logger.AddLogData("WebException", A <string> .That.Matches(exp => exp.Contains(expectedErrorMessage))))
                .MustHaveHappenedOnceExactly();
            }
        }
Пример #7
0
        public async Task Invoke(HttpContext context)
        {
            IScopeStatusManager scopeStatusManager = context.RequestServices.GetService <IScopeStatusManager>();

            ILogger logger = context.RequestServices.GetService <ILogger>();

            try
            {
                await Next.Invoke(context);

                string statusCode = context.Response.StatusCode.ToString();
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason = statusCode.StartsWith("5");
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason = statusCode.StartsWith("4");
                if (responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason ||
                    responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason)
                {
                    scopeStatusManager.MarkAsFailed();

                    logger.AddLogData("ResponseStatusCode", statusCode);

                    if (responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason || context.Features.Get <IHttpResponseFeature>().ReasonPhrase == FoundationMetadataBuilder.KnownError)
                    {
                        await logger.LogWarningAsync("Response has failed status code because of some client side reason");
                    }
                    else if (responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason)
                    {
                        await logger.LogFatalAsync("Response has failed status code because of some server side reason");
                    }
                }
                else if (!scopeStatusManager.WasSucceeded())
                {
                    await logger.LogFatalAsync("Scope was failed");
                }
                else
                {
                    scopeStatusManager.MarkAsSucceeded();
                }
            }
            catch (Exception exp)
            {
                if (scopeStatusManager.WasSucceeded())
                {
                    scopeStatusManager.MarkAsFailed();
                }
                await logger.LogExceptionAsync(exp, "Request-Execution-Exception");

                string statusCode = context.Response.StatusCode.ToString();
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason = statusCode.StartsWith("5");
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason = statusCode.StartsWith("4");
                if (responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason == false && responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason == false)
                {
                    IExceptionToHttpErrorMapper exceptionToHttpErrorMapper = context.RequestServices.GetService <IExceptionToHttpErrorMapper>();
                    context.Response.StatusCode = Convert.ToInt32(exceptionToHttpErrorMapper.GetStatusCode(exp));
                    await context.Response.WriteAsync(exceptionToHttpErrorMapper.GetMessage(exp));

                    context.Features.Get <IHttpResponseFeature>().ReasonPhrase = exceptionToHttpErrorMapper.GetReasonPhrase(exp);
                }
                throw;
            }
        }
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            IUserInformationProvider userInformationProvider =
                dependencyResolver.Resolve <IUserInformationProvider>();

            if (userInformationProvider.IsAuthenticated())
            {
                logger.AddLogData("UserId", userInformationProvider.GetCurrentUserId());
                logger.AddLogData("AuthenticationType", userInformationProvider.GetAuthenticationType());
            }

            await Next.Invoke(context);
        }
Пример #9
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ILogger logger = actionContext.Request.GetOwinContext()
                             .GetDependencyResolver()
                             .Resolve <ILogger>();

            logger.AddLogData("ActionArgs", actionContext.ActionArguments.Where(arg => !(arg.Value is ODataQueryOptions) && !(arg.Value is CancellationToken)).ToArray());

            base.OnActionExecuting(actionContext);
        }
        public virtual async Task ClientsLogsControllerMustSaveLogsUsingLogger()
        {
            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment())
            {
                Token token = await testEnvironment.Server.LoginWithCredentials("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.BuildBitODataClient(token: token);

                await client.ClientsLogs()
                .StoreClientLogs(new[] { new ClientLogDto {
                                             Message = "1", Route = "R"
                                         } })
                .ExecuteAsync();

                ILogger logger = testEnvironment.GetObjects <ILogger>()
                                 .Last();

                A.CallTo(() => logger.LogWarningAsync("Client-Log"))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => logger.AddLogData("ClientLogs", A <IEnumerable <ClientLogDto> > .That.Matches(logs => logs.Single().Message == "1")))
                .MustHaveHappenedOnceExactly();
            }
        }
        public virtual async Task RaiseAsync <T>(Event <T> @event)
        {
            if (@event.EventType == EventTypes.Error || @event.EventType == EventTypes.Failure)
            {
                using (Core.Contracts.IDependencyResolver resolver = DependencyManager.CreateChildDependencyResolver())
                {
                    ILogger logger = resolver.Resolve <ILogger>();

                    logger.AddLogData(nameof(EventContext.ActivityId), @event.Context.ActivityId);
                    logger.AddLogData(nameof(EventContext.RemoteIpAddress), @event.Context.RemoteIpAddress);
                    logger.AddLogData(nameof(EventContext.SubjectId), @event.Context.SubjectId);
                    logger.AddLogData(nameof(Event <object> .Category), @event.Category);
                    logger.AddLogData("IdentityServerEventId", @event.Id);
                    logger.AddLogData(nameof(Event <object> .Name), @event.Name);

                    await logger.LogFatalAsync(@event.Message).ConfigureAwait(false);
                }
            }
        }
Пример #12
0
        public virtual async Task StoreClientLogs(StoreClientLogsParameters actionParameters)
        {
            _logger.AddLogData("ClientLogs", actionParameters.clientLogs);

            await _logger.LogWarningAsync("Client-Log");
        }
Пример #13
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IScopeStatusManager scopeStatusManager = dependencyResolver.Resolve <IScopeStatusManager>();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            try
            {
                context.Response.OnSendingHeaders((state) =>
                {
                    // Create a backup header for reason phrase + enhance its value if possible.
                    // We're able to modify reason phrase and other headers in this callback and in catch part of this class only.
                    // We may not change response headers after await Next.Invoke(context); Codes after Next.Invoke gets invoked after OnSendingHeaders.
                    string reasonPhrase = context.Response.ReasonPhrase;
                    // It can gets filled by
                    // 1- WebApi's routing, when no routing gets matched with value "Not Found".
                    // 2- In catch part of this class with either "KnownError" & "UnknownError" values.
                    // 3- In ExceptionHandlerFilterAttribute class with either "KnownError" & "UnknownError" values.
                    // 4- Other codes! It might be empty too!

                    bool responseIsOk = GetResponseStatus(context).responseIsOk;

                    if (!responseIsOk)
                    {
                        if (string.IsNullOrEmpty(reasonPhrase))
                        {
                            reasonPhrase = BitMetadataBuilder.UnknownError;
                        }
                        else if (!string.Equals(reasonPhrase, BitMetadataBuilder.KnownError, StringComparison.CurrentCultureIgnoreCase) && !string.Equals(reasonPhrase, BitMetadataBuilder.UnknownError, StringComparison.CurrentCultureIgnoreCase))
                        {
                            reasonPhrase = $"{BitMetadataBuilder.UnknownError}:{reasonPhrase}";
                        }
                    }
                    if (!responseIsOk)
                    {
                        context.Response.ReasonPhrase = reasonPhrase;
                        if (!context.Response.Headers.ContainsKey("Reason-Phrase"))
                        {
                            context.Response.Headers.Add("Reason-Phrase", new[] { reasonPhrase });
                        }
                    }
                }, state: null);

                await Next.Invoke(context);

                var status = GetResponseStatus(context);
                if (status.responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason ||
                    status.responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason)
                {
                    string reasonPhrase = context.Response.ReasonPhrase;

                    scopeStatusManager.MarkAsFailed(reasonPhrase);

                    logger.AddLogData("ResponseStatusCode", context.Response.StatusCode);
                    logger.AddLogData("ResponseReasonPhrase", reasonPhrase);

                    if (status.responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason || reasonPhrase == BitMetadataBuilder.KnownError)
                    {
                        await logger.LogWarningAsync("Response has failed status code because of some client side reason");
                    }
                    else if (status.responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason)
                    {
                        await logger.LogFatalAsync("Response has failed status code because of some server side reason");
                    }
                }
                else if (!scopeStatusManager.WasSucceeded())
                {
                    await logger.LogFatalAsync($"Scope was failed: {scopeStatusManager.FailureReason}");
                }
                else
                {
                    scopeStatusManager.MarkAsSucceeded();
                }
            }
            catch (Exception exp)
            {
                if (scopeStatusManager.WasSucceeded())
                {
                    scopeStatusManager.MarkAsFailed(exp.Message);
                }
                await logger.LogExceptionAsync(exp, "Request-Execution-Exception");

                string statusCode = context.Response.StatusCode.ToString(CultureInfo.InvariantCulture);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason = statusCode.StartsWith("5", StringComparison.InvariantCultureIgnoreCase);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason = statusCode.StartsWith("4", StringComparison.InvariantCultureIgnoreCase);
                if (responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason == false && responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason == false)
                {
                    IExceptionToHttpErrorMapper exceptionToHttpErrorMapper = dependencyResolver.Resolve <IExceptionToHttpErrorMapper>();
                    context.Response.StatusCode   = Convert.ToInt32(exceptionToHttpErrorMapper.GetStatusCode(exp), CultureInfo.InvariantCulture);
                    context.Response.ReasonPhrase = exceptionToHttpErrorMapper.GetReasonPhrase(exp);
                    await context.Response.WriteAsync(exceptionToHttpErrorMapper.GetMessage(exp), context.Request.CallCancelled);
                }
                throw;
            }
        }
        public async Task Invoke(HttpContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IScopeStatusManager scopeStatusManager = context.RequestServices.GetRequiredService <IScopeStatusManager>();

            ILogger logger = context.RequestServices.GetRequiredService <ILogger>();

            try
            {
                string?xCorrelationId = context.RequestServices.GetRequiredService <IRequestInformationProvider>().XCorrelationId;

                context.Response.OnStarting(() =>
                {
                    // See OnSendingHeaders of OwinExceptionHandlerMiddleware for more info.
                    string?reasonPhrase = context.Features.Get <IHttpResponseFeature>().ReasonPhrase;

                    bool responseIsOk = GetResponseStatus(context).responseIsOk;

                    if (!responseIsOk)
                    {
                        if (string.IsNullOrEmpty(reasonPhrase))
                        {
                            reasonPhrase = BitMetadataBuilder.UnknownError;
                        }
                        else if (!string.Equals(reasonPhrase, BitMetadataBuilder.KnownError, StringComparison.InvariantCultureIgnoreCase) && !string.Equals(reasonPhrase, BitMetadataBuilder.UnknownError, StringComparison.InvariantCultureIgnoreCase))
                        {
                            reasonPhrase = $"{BitMetadataBuilder.UnknownError}:{reasonPhrase}";
                        }
                    }
                    if (!responseIsOk)
                    {
                        context.Features.Get <IHttpResponseFeature>().ReasonPhrase = reasonPhrase;
                        if (!context.Response.Headers.ContainsKey("Reason-Phrase"))
                        {
                            context.Response.Headers.Add("Reason-Phrase", new[] { reasonPhrase });
                        }
                    }

                    if (!context.Response.Headers.ContainsKey("X-Correlation-ID"))
                    {
                        context.Response.Headers.Add("X-Correlation-ID", xCorrelationId);
                    }

                    return(Task.CompletedTask);
                });

                await _next.Invoke(context).ConfigureAwait(false);

                var status = GetResponseStatus(context);
                if (status.responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason ||
                    status.responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason)
                {
                    string?reasonPhrase = context.Features.Get <IHttpResponseFeature>().ReasonPhrase;

                    scopeStatusManager.MarkAsFailed(reasonPhrase);

                    logger.AddLogData("ResponseStatusCode", context.Response.StatusCode);
                    logger.AddLogData("ResponseReasonPhrase", reasonPhrase);

                    if (status.responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason || reasonPhrase == BitMetadataBuilder.KnownError)
                    {
                        await logger.LogWarningAsync("Response has failed status code because of some client side reason").ConfigureAwait(false);
                    }
                    else if (status.responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason)
                    {
                        await logger.LogFatalAsync("Response has failed status code because of some server side reason").ConfigureAwait(false);
                    }
                }
                else if (!scopeStatusManager.WasSucceeded())
                {
                    await logger.LogFatalAsync($"Scope was failed: {scopeStatusManager.FailureReason}").ConfigureAwait(false);
                }
                else
                {
                    scopeStatusManager.MarkAsSucceeded();

                    if (logger.Policy == LogPolicy.Always)
                    {
                        await logger.LogInformationAsync("Response succeded.").ConfigureAwait(false);
                    }
                }
            }
            catch (Exception exp)
            {
                if (scopeStatusManager.WasSucceeded())
                {
                    scopeStatusManager.MarkAsFailed(exp.Message);
                }
                await logger.LogExceptionAsync(exp, "Request-Execution-Exception").ConfigureAwait(false);

                string statusCode = context.Response.StatusCode.ToString(CultureInfo.InvariantCulture);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason = statusCode.StartsWith("5", StringComparison.InvariantCultureIgnoreCase);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason = statusCode.StartsWith("4", StringComparison.InvariantCultureIgnoreCase);
                if (responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason == false && responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason == false)
                {
                    IExceptionToHttpErrorMapper exceptionToHttpErrorMapper = context.RequestServices.GetRequiredService <IExceptionToHttpErrorMapper>();
                    context.Response.StatusCode = Convert.ToInt32(exceptionToHttpErrorMapper.GetStatusCode(exp), CultureInfo.InvariantCulture);
                    context.Features.Get <IHttpResponseFeature>().ReasonPhrase = exceptionToHttpErrorMapper.GetReasonPhrase(exp);
                    await context.Response.WriteAsync(exceptionToHttpErrorMapper.GetMessage(exp), context.RequestAborted).ConfigureAwait(false);
                }
                throw;
            }
        }
Пример #15
0
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            ILogger logger = dependencyResolver.Resolve<ILogger>();

            IRequestInformationProvider requestInformationProvider =
                dependencyResolver.Resolve<IRequestInformationProvider>();

            logger.AddLogData(nameof(IRequestInformationProvider.HttpMethod), requestInformationProvider.HttpMethod);
            logger.AddLogData(nameof(IRequestInformationProvider.RequestUri), requestInformationProvider.RequestUri);

            if (requestInformationProvider.ClientAppVersion != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientAppVersion), requestInformationProvider.ClientAppVersion);

            if (requestInformationProvider.SystemLanguage != null)
                logger.AddLogData(nameof(IRequestInformationProvider.SystemLanguage), requestInformationProvider.SystemLanguage);

            if (requestInformationProvider.ClientCulture != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientCulture), requestInformationProvider.ClientCulture);

            if (requestInformationProvider.ClientType != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientType), requestInformationProvider.ClientType);

            if (requestInformationProvider.ClientDateTime != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientDateTime), requestInformationProvider.ClientDateTime);

            if (requestInformationProvider.ClientDebugMode != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientDebugMode), requestInformationProvider.ClientDebugMode);

            if (requestInformationProvider.ClientScreenSize != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientScreenSize), requestInformationProvider.ClientScreenSize);

            if (requestInformationProvider.ContentType != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ContentType), requestInformationProvider.ContentType);

            if (requestInformationProvider.Origin != null)
                logger.AddLogData(nameof(IRequestInformationProvider.Origin), requestInformationProvider.Origin);

            if (requestInformationProvider.Referer != null)
                logger.AddLogData(nameof(IRequestInformationProvider.Referer), requestInformationProvider.Referer);

            logger.AddLogData(nameof(IRequestInformationProvider.ClientIp), requestInformationProvider.ClientIp);

            if (requestInformationProvider.ClientPlatform != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientPlatform), requestInformationProvider.ClientPlatform);

            if (requestInformationProvider.ClientRoute != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientRoute), requestInformationProvider.ClientRoute);

            if (requestInformationProvider.ClientSysLanguage != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientSysLanguage), requestInformationProvider.ClientSysLanguage);

            if (requestInformationProvider.ClientTheme != null)
                logger.AddLogData(nameof(IRequestInformationProvider.ClientTheme), requestInformationProvider.ClientTheme);

            if (requestInformationProvider.UserAgent != null)
                logger.AddLogData(nameof(IRequestInformationProvider.UserAgent), requestInformationProvider.UserAgent);

            if (requestInformationProvider.CorrelationId != null)
                logger.AddLogData(nameof(IRequestInformationProvider.CorrelationId), requestInformationProvider.CorrelationId);

            await Next.Invoke(context);
        }
Пример #16
0
        public static void LogRequest(ILogger logger, IRequestInformationProvider requestInformationProvider)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (requestInformationProvider == null)
            {
                throw new ArgumentNullException(nameof(requestInformationProvider));
            }

            logger.AddLogData(nameof(IRequestInformationProvider.HttpMethod), requestInformationProvider.HttpMethod);
            logger.AddLogData(nameof(IRequestInformationProvider.DisplayUrl), requestInformationProvider.DisplayUrl);

            if (requestInformationProvider.ClientAppVersion != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientAppVersion), requestInformationProvider.ClientAppVersion);
            }

            if (requestInformationProvider.SystemLanguage != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.SystemLanguage), requestInformationProvider.SystemLanguage);
            }

            if (requestInformationProvider.ClientCulture != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientCulture), requestInformationProvider.ClientCulture);
            }

            if (requestInformationProvider.ClientType != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientType), requestInformationProvider.ClientType);
            }

            if (requestInformationProvider.BitClientType != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.BitClientType), requestInformationProvider.BitClientType);
            }

            if (requestInformationProvider.ClientDateTime != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientDateTime), requestInformationProvider.ClientDateTime);
            }

            if (requestInformationProvider.ClientDebugMode != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientDebugMode), requestInformationProvider.ClientDebugMode);
            }

            if (requestInformationProvider.ClientScreenSize != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientScreenSize), requestInformationProvider.ClientScreenSize);
            }

            if (requestInformationProvider.ContentType != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ContentType), requestInformationProvider.ContentType);
            }

            if (requestInformationProvider.Origin != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.Origin), requestInformationProvider.Origin);
            }

            if (requestInformationProvider.Referer != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.Referer), requestInformationProvider.Referer);
            }

            logger.AddLogData(nameof(IRequestInformationProvider.ClientIp), requestInformationProvider.ClientIp);

            if (requestInformationProvider.ClientPlatform != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientPlatform), requestInformationProvider.ClientPlatform);
            }

            if (requestInformationProvider.ClientRoute != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientRoute), requestInformationProvider.ClientRoute);
            }

            if (requestInformationProvider.ClientSysLanguage != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientSysLanguage), requestInformationProvider.ClientSysLanguage);
            }

            if (requestInformationProvider.ClientTheme != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientTheme), requestInformationProvider.ClientTheme);
            }

            if (requestInformationProvider.UserAgent != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.UserAgent), requestInformationProvider.UserAgent);
            }

            logger.AddLogData("X-Correlation-ID", requestInformationProvider.XCorrelationId);
        }
Пример #17
0
        public static void LogRequest(ILogger logger, IRequestInformationProvider requestInformationProvider)
        {
            logger.AddLogData(nameof(IRequestInformationProvider.HttpMethod), requestInformationProvider.HttpMethod);
            logger.AddLogData(nameof(IRequestInformationProvider.RequestUri), requestInformationProvider.RequestUri);

            if (requestInformationProvider.ClientAppVersion != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientAppVersion), requestInformationProvider.ClientAppVersion);
            }

            if (requestInformationProvider.SystemLanguage != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.SystemLanguage), requestInformationProvider.SystemLanguage);
            }

            if (requestInformationProvider.ClientCulture != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientCulture), requestInformationProvider.ClientCulture);
            }

            if (requestInformationProvider.ClientType != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientType), requestInformationProvider.ClientType);
            }

            if (requestInformationProvider.ClientDateTime != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientDateTime), requestInformationProvider.ClientDateTime);
            }

            if (requestInformationProvider.ClientDebugMode != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientDebugMode), requestInformationProvider.ClientDebugMode);
            }

            if (requestInformationProvider.ClientScreenSize != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientScreenSize), requestInformationProvider.ClientScreenSize);
            }

            if (requestInformationProvider.ContentType != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ContentType), requestInformationProvider.ContentType);
            }

            if (requestInformationProvider.Origin != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.Origin), requestInformationProvider.Origin);
            }

            if (requestInformationProvider.Referer != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.Referer), requestInformationProvider.Referer);
            }

            logger.AddLogData(nameof(IRequestInformationProvider.ClientIp), requestInformationProvider.ClientIp);

            if (requestInformationProvider.ClientPlatform != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientPlatform), requestInformationProvider.ClientPlatform);
            }

            if (requestInformationProvider.ClientRoute != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientRoute), requestInformationProvider.ClientRoute);
            }

            if (requestInformationProvider.ClientSysLanguage != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientSysLanguage), requestInformationProvider.ClientSysLanguage);
            }

            if (requestInformationProvider.ClientTheme != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.ClientTheme), requestInformationProvider.ClientTheme);
            }

            if (requestInformationProvider.UserAgent != null)
            {
                logger.AddLogData(nameof(IRequestInformationProvider.UserAgent), requestInformationProvider.UserAgent);
            }

            if (requestInformationProvider.CorrelationId != null)
            {
                logger.AddLogData("X-CorrelationId", requestInformationProvider.CorrelationId);
            }
        }
        public override async Task Invoke(IOwinContext context)
        {
            IDependencyResolver dependencyResolver = context.GetDependencyResolver();

            IScopeStatusManager scopeStatusManager = dependencyResolver.Resolve <IScopeStatusManager>();

            ILogger logger = dependencyResolver.Resolve <ILogger>();

            try
            {
                await Next.Invoke(context);

                string statusCode = context.Response.StatusCode.ToString(CultureInfo.InvariantCulture);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason = statusCode.StartsWith("5", StringComparison.InvariantCultureIgnoreCase);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason = statusCode.StartsWith("4", StringComparison.InvariantCultureIgnoreCase);
                if (responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason ||
                    responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason)
                {
                    string reasonPhrase = context.Response.ReasonPhrase ?? "UnknownReasonPhrase";

                    scopeStatusManager.MarkAsFailed(reasonPhrase);

                    logger.AddLogData("ResponseStatusCode", statusCode);
                    logger.AddLogData("ResponseReasonPhrase", reasonPhrase);

                    if (responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason || reasonPhrase == BitMetadataBuilder.KnownError)
                    {
                        await logger.LogWarningAsync("Response has failed status code because of some client side reason");
                    }
                    else if (responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason)
                    {
                        await logger.LogFatalAsync("Response has failed status code because of some server side reason");
                    }
                }
                else if (!scopeStatusManager.WasSucceeded())
                {
                    await logger.LogFatalAsync($"Scope was failed: {scopeStatusManager.FailureReason}");
                }
                else
                {
                    scopeStatusManager.MarkAsSucceeded();
                }
            }
            catch (Exception exp)
            {
                if (scopeStatusManager.WasSucceeded())
                {
                    scopeStatusManager.MarkAsFailed(exp.Message);
                }
                await logger.LogExceptionAsync(exp, "Request-Execution-Exception");

                string statusCode = context.Response.StatusCode.ToString(CultureInfo.InvariantCulture);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason = statusCode.StartsWith("5", StringComparison.InvariantCultureIgnoreCase);
                bool   responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason = statusCode.StartsWith("4", StringComparison.InvariantCultureIgnoreCase);
                if (responseStatusCodeIsErrorCodeBecauseOfSomeClientBasedReason == false && responseStatusCodeIsErrorCodeBecauseOfSomeServerBasedReason == false)
                {
                    IExceptionToHttpErrorMapper exceptionToHttpErrorMapper = dependencyResolver.Resolve <IExceptionToHttpErrorMapper>();
                    context.Response.StatusCode = Convert.ToInt32(exceptionToHttpErrorMapper.GetStatusCode(exp), CultureInfo.InvariantCulture);
                    await context.Response.WriteAsync(exceptionToHttpErrorMapper.GetMessage(exp), context.Request.CallCancelled);

                    context.Response.ReasonPhrase = exceptionToHttpErrorMapper.GetReasonPhrase(exp);
                }
                throw;
            }
        }