Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikegoatly/2d3437d34165321ac93a3fa97fb313c4 to your computer and use it in GitHub Desktop.
Save mikegoatly/2d3437d34165321ac93a3fa97fb313c4 to your computer and use it in GitHub Desktop.
Application Insights dependency header logging

Registering this telemetry initializer with your service collection will get any headers present in HTTP dependencies to be logged with the dependency telemetry. Each header will be logged as a separate property in the form HEADER_{name}.

Health warning: I strongly recommend against using this in production because it will log sensitive information. It can however be very useful diagnosing scenarios such as authentication issues while developing locally.

public static class ServiceCollectionExtensions
{
public static IServiceCollection AddExtendedDependencyTelemetry(this IServiceCollection services)
{
services.AddSingleton<ITelemetryInitializer, ExtendedDependencyTelemetryInitializer>();
return services;
}
}
public class ExtendedDependencyTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
var dependencyTelemetry = telemetry as DependencyTelemetry;
if (dependencyTelemetry == null) return;
if (dependencyTelemetry.TryGetOperationDetail("HttpRequest", out object request)
&& request is HttpRequestMessage httpRequest)
{
foreach (var item in httpRequest.Headers)
{
var key = $"HEADER_{item.Key}";
if (!dependencyTelemetry.Properties.ContainsKey(key))
{
dependencyTelemetry.Properties.Add(key, string.Join(Environment.NewLine, item.Value));
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment