|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using Microsoft.ApplicationInsights.Channel; |
| 4 | +using Microsoft.ApplicationInsights.DataContracts; |
| 5 | +using Microsoft.ApplicationInsights.Extensibility; |
| 6 | +using Microsoft.Extensions.Configuration; |
| 7 | + |
| 8 | +namespace XtremeIdiots.Portal.Web; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Filters out successful, fast dependency calls for configured dependency types |
| 12 | +/// to reduce telemetry volume. Failed calls and calls exceeding the duration |
| 13 | +/// threshold are always retained. |
| 14 | +/// </summary> |
| 15 | +public sealed class DependencyFilterTelemetryProcessor : ITelemetryProcessor |
| 16 | +{ |
| 17 | + private readonly ITelemetryProcessor next; |
| 18 | + private readonly IConfiguration configuration; |
| 19 | + |
| 20 | + public DependencyFilterTelemetryProcessor(ITelemetryProcessor next, IConfiguration configuration) |
| 21 | + { |
| 22 | + ArgumentNullException.ThrowIfNull(next); |
| 23 | + ArgumentNullException.ThrowIfNull(configuration); |
| 24 | + |
| 25 | + this.next = next; |
| 26 | + this.configuration = configuration; |
| 27 | + } |
| 28 | + |
| 29 | + public void Process(ITelemetry item) |
| 30 | + { |
| 31 | + if (item is DependencyTelemetry dependency && ShouldFilter(dependency)) |
| 32 | + return; |
| 33 | + |
| 34 | + next.Process(item); |
| 35 | + } |
| 36 | + |
| 37 | + private bool ShouldFilter(DependencyTelemetry dependency) |
| 38 | + { |
| 39 | + if (string.IsNullOrEmpty(dependency.Type)) |
| 40 | + return false; |
| 41 | + |
| 42 | + var excludedTypes = configuration["ApplicationInsights:DependencyFilter:ExcludedTypes"]? |
| 43 | + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); |
| 44 | + var excludedPrefixes = configuration["ApplicationInsights:DependencyFilter:ExcludedTypePrefixes"]? |
| 45 | + .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); |
| 46 | + |
| 47 | + var typeMatches = |
| 48 | + (excludedTypes?.Any(t => string.Equals(dependency.Type, t, StringComparison.OrdinalIgnoreCase)) == true) || |
| 49 | + (excludedPrefixes?.Any(p => dependency.Type.StartsWith(p, StringComparison.OrdinalIgnoreCase)) == true); |
| 50 | + |
| 51 | + if (!typeMatches) |
| 52 | + return false; |
| 53 | + |
| 54 | + if (dependency.Success != true) |
| 55 | + return false; |
| 56 | + |
| 57 | + var thresholdMs = double.TryParse( |
| 58 | + configuration["ApplicationInsights:DependencyFilter:DurationThresholdMs"], out var t) ? t : 1000; |
| 59 | + if (dependency.Duration.TotalMilliseconds > thresholdMs) |
| 60 | + return false; |
| 61 | + |
| 62 | + return true; |
| 63 | + } |
| 64 | +} |
0 commit comments