コード例 #1
0
        public async Task Invoke(HttpContext context, ILoggingService loggingService)
        {
            try
            {
                var stopwatch = new Stopwatch();

                StringValues contextId = GetContextId(context);

                StringValues correlationId = GetCorrelationId(context, contextId);

                StringValues applicationId = GetApplicationId(context);


                ConcurrentDictionary <string, object> dict = GetDictionary(contextId, correlationId, applicationId);

                if (context.Request.Path.HasValue)
                {
                    dict.TryAdd(Constants.Headers.ROUTE, context.Request.Path.Value);
                }

                string ipV4Address = context.Connection?.RemoteIpAddress?.MapToIPv4().ToString();

                using (loggingService.ConfigureLoggingAsync(dict))
                {
                    stopwatch.Start();

                    var logger = loggingService.GetLogger <LoggingMiddleware>(nameof(LoggingMiddleware));

                    using (logger.BeginScope(new Dictionary <string, object> {
                        ["clientIpAddress"] = ipV4Address
                    }))
                    {
                        logger.LogInformation($"Processing Http request from URL: {context.Request.Path.Value}");
                    }

                    await next(context).ConfigureAwait(false);

                    stopwatch.Stop();

                    logger.LogInformation("Finished processing Http request to URL: {URL}. HttpMethod: {HttpMethod}. Duration: {RequestDuration}",
                                          context.Request.Path.Value, context.Request.Method, stopwatch.ElapsedMilliseconds);
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }