Tracking Request Body via Application Insights

Application Insights is a great monitoring tool combines tracing, monitoring and even logging via custom events in one place. For any application running on Azure, it is the native way of doing and especially for .NetCore applications (.NetFramework is still supported?) so much easier to integrate.

As most of the tracing tools in the market does, out of box support for tracking HTTP POST or PUT requests is not available. Most probably due to GDPR, Privacy and Security, this is not a best practice. Otherwise, it would be so much easier to slip user password or other personal information to tracing tool.

However, due to running in Microservices architecture, we would still need to monitor some payloads in order to understand the consumers of our services and how they integrate. For API versioning, bug fixing and integration health, I find this practice a valuable option. After running multiple trials, I ended up manually doing it to avoid running into Privacy and Security issues.

I strongly recommend putting this in practice with a good code review and manually just to the relevant places. Running this code as a Custom Middleware, Attribute or similar application wide practice would not be something I really recommend due to Privacy and Security.

Using following code piece, you can attach any arbitrary information to the request automatically tracked by Application Insights. I suggest putting this in the Controller Action to make sure the Request and its Context available. Otherwise, .NetCore 3.1 has breaking changes on the lifecycle of Request when you try this code in other places. I tried and failed on that 🙂

var httpContext = Request.HttpContext;
var payloadValue = JsonConvert.SerializeObject(payload);
var requestTelemetry = httpContext.Features.Get<RequestTelemetry>();
requestTelemetry?.Properties.Add("RequestBody", payloadValue);

When you search this request on Application Insights, you will be able to see RequestBody under Custom Properties

What do you think?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: