Created
August 12, 2018 20:05
-
-
Save hiraldesai/239b83c736707cdcb809d85aa5bf2d95 to your computer and use it in GitHub Desktop.
Application Insights Telemetry Initializer to capture responses from outbound http calls (dependencies)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DependencyResponseInitializer : ITelemetryInitializer | |
{ | |
private readonly bool _dependencyResponseCaptureDisabled; | |
public DependencyResponseInitializer(IConfiguration configuration) | |
{ | |
bool.TryParse(configuration[Constants.ConfigKeys.DependencyResponseCapturingDisabled], out _dependencyResponseCaptureDisabled); | |
} | |
public void Initialize(ITelemetry telemetry) | |
{ | |
if(_dependencyResponseCaptureDisabled) | |
return; | |
if (!(telemetry is DependencyTelemetry dependencyTelemetry) || | |
!dependencyTelemetry.TryGetOperationDetail("HttpResponse", out var reponseObject)) return; | |
if (!(reponseObject is HttpResponseMessage response)) | |
return; | |
foreach (var header in response.Headers) | |
dependencyTelemetry.Properties.Add($"ResponseHeader-{header.Key}", string.Join(", ", header.Value)); | |
if (response.Content == null) | |
return; | |
foreach (var header in response.Content.Headers) | |
dependencyTelemetry.Properties.Add($"ContentHeader-{header.Key}", string.Join(", ", header.Value)); | |
if (!(response.Content is StringContent) | |
&& !IsTextBasedContentType(response.Headers) | |
&& !IsTextBasedContentType(response.Content.Headers)) | |
return; | |
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); | |
dependencyTelemetry.Properties.Add("ResponseContent", content); | |
} | |
private static bool IsTextBasedContentType(HttpHeaders headers) | |
{ | |
if (!headers.TryGetValues("Content-Type", out var values)) | |
return false; | |
var header = string.Join(" ", values).ToLowerInvariant(); | |
var textBasedTypes = new [] { "html", "text", "xml", "json", "txt", "x-www-form-urlencoded" }; | |
return textBasedTypes.Any(t => header.Contains(t)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment