Versions Compared

Key

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

...

  1. Getting Started with Microsoft Azure Insights Integration

  2. A Step-by-Step Guide to Azure Insights Integration with .NET Core API

  3. Streamlining Microsoft Azure Insights Integration with Angular

  4. Log Request Payloads Using Custom Events in Microsoft Azure Insights (You’re here!)

  5. Tracking Response Exceptions via Custom Event Logging in Azure Insights

In this fourth part, we will cover how to log request payloads using custom events in Microsoft Azure Insights to enhance monitoring and troubleshooting.

...

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;

                    ListList<LogRequest> <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);
        }
    }

...