Skip to content

Instantly share code, notes, and snippets.

@stuartleeks
Created November 3, 2016 19:56
Show Gist options
  • Save stuartleeks/620aa7858f54f864b27803febc176811 to your computer and use it in GitHub Desktop.
Save stuartleeks/620aa7858f54f864b27803febc176811 to your computer and use it in GitHub Desktop.
Application Insights - Capture Headers
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using System.Collections.Generic;
using System.Web;
namespace AppInsightsHeaders
{
public class HeaderTelemetryInitializer : ITelemetryInitializer
{
public List<string> RequestHeaders { get; set; }
public List<string> ResponseHeaders { get; set; }
public HeaderTelemetryInitializer()
{
RequestHeaders = new List<string>();
ResponseHeaders = new List<string>();
}
public void Initialize(ITelemetry telemetry)
{
var context = HttpContext.Current;
if (context == null)
{
return;
}
if (context.Request != null)
{
foreach (var headerName in RequestHeaders)
{
var header = context.Request.Headers[headerName];
if (header != null)
{
telemetry.Context.Properties.Add($"request-{headerName}", header);
}
}
}
if (context.Response != null)
{
foreach (var headerName in ResponseHeaders)
{
var header = context.Response.Headers[headerName];
if (header != null)
{
telemetry.Context.Properties.Add($"response-{headerName}", header);
}
}
}
}
}
}
TelemetryConfiguration.Active.TelemetryInitializers.Add(
new HeaderTelemetryInitializer
{
RequestHeaders =
{
"Accept"
},
ResponseHeaders =
{
"Content-Type"
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment