Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
breakoutModefull-width
languagec#
    public class AzureInsightsMiddleware(
        RequestDelegate next,
        TelemetryClient telemetryClient,
        IConfiguration configuration
    )
    {
        public async Task Invoke(HttpContext context)
        {
            bool applicationInsightsEnabled = false;

            try
            {
                applicationInsightsEnabled = configuration.GetValue <bool>GetValue<bool> (
                    "ApplicationInsights:TelemetryFeatureEnabled"
                );
                int payLoadLoggingOption = configuration.GetValue <int> GetValue<int>("PayLoad:LoggingOption");

                if (applicationInsightsEnabled && payLoadLoggingOption != -1)
                {
                    PathString requestPath = context.Request.Path;
                    string requestMethod = context.Request.Method;

                    List <LogRequest> logRequests =
                        configuration.GetSection("PayLoad:LogRequests").Get <List<LogRequest>> Get<List<LogRequest>>() ?? [];

                    bool shouldLog = (logRequests.Any(
                        logRequest =>
                        requestMethod.Equals(
                            logRequest.Method,
                            StringComparison.OrdinalIgnoreCase
                        ) && requestPath.StartsWithSegments(logRequest.Path)
                    ) && payLoadLoggingOption == 0) || payLoadLoggingOption == 1;

                    if (shouldLog)
                    {
                        string[] logDisabledDatabases = configuration.GetSection("PayLoad:DisabledDatabaseList").Get <stringGet<string[]> () ?? [];
                        int minimumPayloadSize = configuration.GetSection("PayLoad:MinimumSize").Get <intGet<int?> () ?? 5;

                        context.Request.EnableBuffering();
                        string bodyAsText = string.Empty;

                        if (context.Request.ContentLength == null || context.Request.ContentLength > minimumPayloadSize * 1024 * 1024)
                        {
                            bodyAsText = "Request body is too large to process.";
                        }
                        else
                        {
                            using(StreamReader reader = new(context.Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true))
                            {
                                bodyAsText = await reader.ReadToEndAsync();
                                context.Request.Body.Position = 0;
                            }
                            context.Request.Body.Seek(0, SeekOrigin.Begin);
                        }

                        Dictionary <stringDictionary<string, string> customMetaData = new()
                        {
                            {
                                "payload",
                                bodyAsText
                            },
                            {
                                "content_type",
                                context.Request.ContentType
                            },
                        };

                        if (context.User.Claims.Any())
                        {
                            string userDatabase = context.User.Claims.FirstOrDefault(c => c.Type == "Database")?.Value ?? string.Empty;

                            if (!logDisabledDatabases.Contains(userDatabase))
                            {
                                customMetaData.Add("organization", userDatabase);
                            }
                        }
                        else
                        {
                            customMetaData.Add("organization", "not-specified");
                        }

                        telemetryClient.TrackEvent($ "Request PayLoad", customMetaData);
                    }
                }
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
            }

            await next(context);
        }
    }

...