Skip to content

Instantly share code, notes, and snippets.

@lmolkova
Last active May 23, 2018 01:01
Show Gist options
  • Save lmolkova/ca0ac9d68ad7e3dc93760913cda5abc3 to your computer and use it in GitHub Desktop.
Save lmolkova/ca0ac9d68ad7e3dc93760913cda5abc3 to your computer and use it in GitHub Desktop.
Demo/prototype for preventing certain dependency calls based on the scope
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DependencyCollector;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
namespace filtering
{
class MyTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
if (Program.myMonitor.Value == null)
{
telemetry.Context.Properties["block"] = "true";
}
}
}
class MyTelemetryFilter : ITelemetryProcessor
{
private readonly ITelemetryProcessor next;
public int ProcessedTelemtryItems { get; set; }
public MyTelemetryFilter(ITelemetryProcessor next)
{
this.next = next;
}
public void Process(ITelemetry item)
{
if (item.Context.Properties.ContainsKey("block"))
return;
ProcessedTelemtryItems++;
this.next.Process(item);
}
}
class Program
{
public static AsyncLocal<object> myMonitor = new AsyncLocal<object>();
private static CloudQueue _queue;
static void Main(string[] args)
{
MyTelemetryFilter filter = null;
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
builder.Use(next => { return filter = new MyTelemetryFilter(next); });
builder.Build();
DependencyTrackingTelemetryModule module = new DependencyTrackingTelemetryModule();
module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("http://127.0.0.1");
module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
module.Initialize(TelemetryConfiguration.Active);
// will be tracked
myMonitor.Value = new object();
SetupQueue();
Task.Run(async () =>
{
for (int i = 0; i < 50; i++)
{
await _queue.AddMessageAsync(new CloudQueueMessage("hello"));
}
}).Wait();
myMonitor.Value = null;
Console.WriteLine($"Tracking enabled: tracked {filter.ProcessedTelemtryItems} items");
filter.ProcessedTelemtryItems = 0;
// won't be tracked
Task.Run(async () =>
{
for (int i = 0; i < 50; i++)
{
await _queue.AddMessageAsync(new CloudQueueMessage("hello"));
}
}).Wait();
Console.WriteLine($"Tracking disabled: tracked {filter.ProcessedTelemtryItems} items");
Console.ReadKey();
}
private static void SetupQueue()
{
string connString = "UseDevelopmentStorage=true";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connString);
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
_queue = queueClient.GetQueueReference("asynclocal");
_queue.CreateIfNotExistsAsync().Wait();
}
}
}
@lmolkova
Copy link
Author

lmolkova commented May 23, 2018

or even better example that demonstrates that calls done under myMonitor.Value != null are tracked

            MyTelemetryFilter filter = null;
            TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
            var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
            builder.Use(next => { return filter = new MyTelemetryFilter(next); });
            builder.Build();

            DependencyTrackingTelemetryModule module = new DependencyTrackingTelemetryModule();
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("http://127.0.0.1");
            module.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("core.windows.net");
            module.Initialize(TelemetryConfiguration.Active);

            HttpClient hc = new HttpClient();
            var task1 = Task.Run(async () =>
            {
                // will be tracked
                myMonitor.Value = new object();

                for (int i = 0; i < 50; i++)
                {
                    await hc.GetAsync($"http://microsoft.com?q={i}tracked");
                }
                myMonitor.Value = null;
            });

            var task2 = Task.Run(async () =>
            {
                // won't be tracked
                for (int i = 0; i < 50; i++)
                {
                    await hc.GetAsync($"http://microsoft.com?q={i}nottracked");
                }
            });

            Task.WhenAll(task1, task2).Wait();

            Console.ReadKey();

...

    class MyTelemetryFilter : ITelemetryProcessor
    {
        private readonly ITelemetryProcessor next;
        public int ProcessedTelemtryItems { get; set; }

        public MyTelemetryFilter(ITelemetryProcessor next)
        {
            this.next = next;
        }

        public void Process(ITelemetry item)
        {
            if (item.Context.Properties.ContainsKey("block"))
                return;

            ProcessedTelemtryItems++;
            Console.WriteLine($"tracking {(item as DependencyTelemetry).Data}");

            this.next.Process(item);
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment