Search code examples
azure-application-insightsazure-function-app

resultCode is 0 for all requests in Application Insights


I have a function app connected with an application insights instance. When I look at the requests on application insights, all entries have a resultCode of 0, regardless of whether it was successful or not. How can I have the resultCode showing properly?

If I get it correctly, my function app is running at the version "3.0.14916.0".

Here is my startup:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddLogging(loggingBuilder =>
        {
            var key = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
            loggingBuilder.AddApplicationInsights(key);
        });
        builder.Services.AddSingleton(sp =>
        {
            var key = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
            return new TelemetryConfiguration(key);
        });

        (...)
    }
}

Edit 1:

In the comments it was asked why I am adding logging in Startup. I do it because, as far as I could verify, ILogger < MyClass > only logs to AI if I add logging in Startup. Following is an example of an injected class. Note that this class is also used in other projects.

public class CosmosDbService : ICosmosDbService
{
    private readonly IDocumentClient _documentClient;
    private readonly ILogger _logger;

    public CosmosDbService(IDocumentClient documentClient, ILogger<CosmosDbService> logger)
    {
        _logger = logger;
        _documentClient = documentClient;
    }

    public async Task<UserData> GetUserAsync()
    {
        try
        {
            // Getting user here
            // (...)
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error fetching user.");
            throw;
        }
    }
}

This class is injected as:

builder.Services.AddSingleton<IDocumentClient>(sp =>
{
    // This does not really matter for this question
    var configuration = sp.GetService<IConfiguration>();
    var connectionString = configuration.GetValue<string>("COSMOS_DB_CONNECTION");
    var cosmosDbConnectionString = new CosmosDbConnectionString(connectionString);
    return new DocumentClient(cosmosDbConnectionString.ServiceEndpoint, cosmosDbConnectionString.AuthKey);
});
builder.Services.AddSingleton<ICosmosDbService, CosmosDbService>();

Solution

  • This answer from @PeterBons helped me fixing the wrong resultCode as well.

    Basically I was importing the wrong package: Microsoft.Extensions.Logging.ApplicationInsights

    I changed it to Microsoft.Azure.WebJobs.Logging.ApplicationInsights and removed the code in Startup. Now I got the resultCode properly filled in again.