Azure Functions preview + Application Insights

Hey there,

I’m using the preview for NServiceBus with Azure Functions.
I want to use some custom metrics with Application Insights.

This website states that if you want to use Azure Functions with Application Insights, you shouldn’t use AddApplicationInsightsTelemetry(), which is available from the ApplicationInsights package. Instead, Azure Functions will inject TelemetryConfiguration. You can create your own TelemetryClient from there.

However, when using NServiceBus preview with Azure Functions, your classes will be static. As the function endpoint is static as well.

I’m not able to inject the TelemetryConfiguration now, is there a workaround for this?

As stated, all I want to do is track some Application Insights metrics.

Hi Rob,

instead of using a static field, you can register FunctionEndpoint as a singleton in the startup class. At that point, you can resolve TelemetryConfiguration instance from the ServiceProvider and register it in the endpoints container like:

 public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton(sp => new FunctionEndpoint(executionContext =>
            {
                // endpoint name, logger, and connection strings are automatically derived from FunctionName and QueueTrigger attributes
                var configuration = StorageQueueTriggeredEndpointConfiguration.FromAttributes();

                configuration.UseSerialization<NewtonsoftSerializer>();

                // optional: log startup diagnostics using Functions provided logger
                configuration.LogDiagnostics();

                // Disable persistence requirement
                configuration.Transport.DisablePublishing();

                //resolve telemetry configuration
                var telemetryConfiguration = sp.GetRequiredService<TelemetryConfiguration>();

                //register in the endpoints container
                configuration.AdvancedConfiguration.RegisterComponents(cc => cc.RegisterSingleton(telemetryConfiguration));
                
                return configuration;
            }));
        }
    }

Cheers,
Tomek

1 Like

Hey Tomek,

Thank you for this idea, it works. It took me some time to figure out why it still didn’t resolve, but it turned out that the APPINSIGHTS_INSTRUMENTATIONKEY in the local settings was required for locally running and resolving this dependency…

Thanks!

Best regards,
Rob