Skip to content

Instantly share code, notes, and snippets.

@andrewleader
Created January 17, 2020 22:01
Show Gist options
  • Save andrewleader/a523dafb6fbfae2493002d0b983c0b84 to your computer and use it in GitHub Desktop.
Save andrewleader/a523dafb6fbfae2493002d0b983c0b84 to your computer and use it in GitHub Desktop.
Disable Dependency tracking in Azure Functions
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]
namespace MyNamespace
{
// Disable logging dependencies in Application Insights: https://github.com/Azure/Azure-Functions/issues/693#issuecomment-460798121
// Dependencies cost SO MUCH MONEY in Application Insights, they eat up the gigabytes.
// There potentially are some config options in host.json, however any changes I made to host.json weren't getting applied for some reason.
// In a newly deployed function, host.json was working, but not in my existing functions... Doing this in code gives me more control anyways.
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var configDescriptor = builder.Services.SingleOrDefault(tc => tc.ServiceType == typeof(TelemetryConfiguration));
if (configDescriptor?.ImplementationFactory == null)
{
return;
}
var implFactory = configDescriptor.ImplementationFactory;
builder.Services.Remove(configDescriptor);
builder.Services.AddSingleton(provider =>
{
if (!(implFactory.Invoke(provider) is TelemetryConfiguration config))
return null;
config.TelemetryProcessorChainBuilder.Use(next => new DependencyErrorFilteringProcessor(next));
config.TelemetryProcessorChainBuilder.Build();
return config;
});
}
}
internal class DependencyErrorFilteringProcessor : ITelemetryProcessor
{
private readonly ITelemetryProcessor _next;
public DependencyErrorFilteringProcessor(ITelemetryProcessor next)
{
_next = next;
}
public void Process(ITelemetry item)
{
// Ignore successful dependencies
if (IsOkToSend(item))
{
_next.Process(item);
}
}
private bool IsOkToSend(ITelemetry item)
{
if (item is DependencyTelemetry dependency)
{
// Only send failed dependencies
return dependency.Success.HasValue && dependency.Success.Value == false;
}
// Ignore traces and requests
if (item is TraceTelemetry
|| item is RequestTelemetry)
{
return false;
}
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment