Search code examples
azure-functions

Why am I unable to see Application Insights events in my Azure Functions app?


I have a v4 .NET 6 functions app and I want to record custom Application Insights events.

I've added the Microsoft.Azure.WebJobs.Logging.ApplicationInsights 3.0.30 NuGet package.

In Startup I've tried registering telemetry with

var telemetryConfiguration = new TelemetryConfiguration(VALID_INSTRUMENTATION_KEY_HERE);
builder.Services.AddSingleton(_ => new TelemetryClient(telemetryConfiguration));

and

builder.Services.AddApplicationInsightsTelemetry(VALID_INSTRUMENTATION_KEY_HERE);

In my function I've wired up the TelemetryClient using constructor injection however when I check the instance in a break point there is no Instrumentation Key set?

I've also tried calling TrackEvent by newing up a TelemetryClient in my code but I'm not seeing the event in the Application Insights Logs view

new TelemetryClient(new TelemetryConfiguration(VALID_INSTRUMENTATION_KEY_HERE)).TrackEvent(new EventTelemetry("AddSearchesToQueue"));

Does anyone know what I'm doing wrong here?


Solution

  • I have added the < PackageReference Include="Microsoft.Azure.WebJobs.Logging.ApplicationInsights" Version="3.0.30" /> package reference in our .NET 6 Azure function project

    And you need to initialize the Custom Telemetry in your function

    The workaround below

    Funciton1.cs

    [FunctionName("Function1")]
    
    public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post",Route = null)] HttpRequest req, ILogger log, ExecutionContext context)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(context.FunctionAppDirectory)
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();
        
        var connectionString = "ConnectionString";
        var tc = new Microsoft.ApplicationInsights.TelemetryClient(new TelemetryConfiguration()
            { ConnectionString = config[$"{connectionString}"]  }
            );
        
        tc.TrackEvent("Calling azure function", new Dictionary<string, string> { { "FunctionType", "Function action" } }, null);
        tc.TrackEvent("Processing task item", new Dictionary<string, string> { { "Item", "Your item" } }, null);
        tc.TrackEvent("Completed azure function");
        
        log.LogInformation("C# HTTP trigger function processed a request.");
        
        string name = req.Query["name"];
        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;
        string responseMessage = string.IsNullOrEmpty(name) ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.": $"Hello, {name}. This HTTP triggered function executed successfully.";
        
        tc.TrackEvent("Responsemessage:" + responseMessage);
        tc.Flush();
        
        return new OkObjectResult(responseMessage);
        
    }
    

    Local.settings.json

    {
        "IsEncrypted": false,
        "Values": { 
            "AzureWebJobsStorage": "UseDevelopmentStorage=true",
            "FUNCTIONS_WORKER_RUNTIME": "dotnet",
            "APPINSIGHTS_INSTRUMENTATIONKEY": "<App insights instrumentation key>",
            "ConnectionString": "<Your Connection stirng for app insghts>"
        }
    }
    

    enter image description here

    I could see the custom logs in Application insights

    enter image description here

    Refer Tracing and logging with Application Insights