17

I'm using the interface ILogger to log events inside my Azure functions. I can publish it in Azure and connect it to Application Insights in Azure.

I want to see my logs inside Application Insights in my Visual Studio during development. In here I can see this is possible in a ASP.NET Core Web Application putting some code in Startup.cs. Is something similar possible with Azure Functions using the new project template from the tooling in VS 2017?

I'm using VS 2017 and Azure Function CLI 1.0.0-beta-100.

milkersarac
  • 3,399
  • 3
  • 31
  • 31
gabomgp
  • 769
  • 1
  • 10
  • 23
  • As far as I know, if you want to log information to the Application Insights. I suggest you could consider using Microsoft.ApplicationInsights package and create the TelemetryClient with InstrumentationKey. More details, you could refer to this [article](https://cmatskas.com/azure-functions-custom-logging-with-appinsights/). – Brando Zhang Aug 07 '17 at 09:50
  • 2
    The referenced article says itself is obsolete because Azure Functions already have integration with Application Insights. But that integration doesn't work in Visual Studio, to see the logs in VS and not the portal. – gabomgp Aug 08 '17 at 15:28

4 Answers4

27

Adding Application Insights (AI) telemetry to Azure Functions is simple and straightforward.

You just need these two steps from the official docs;

  1. Create an Application Insights instance.
    • Application type should be set to General
    • Grab the instrumentation key
  2. Update your Function App’s settings
    • Add App Setting – APPINSIGHTS_INSTRUMENTATIONKEY = {Instrumentation Key}

However what is not (so) obvious is how to capture AI telemetry data while developing a functions app locally, just before letting it go to the clouds. First you need to prepare your local dev environment for Azure Functions. Then you are almost ready. You just need to repeat the second step above on your local.settings.json file. So your file should look something like this;

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_EXTENSION_VERSION": "beta",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true",
    "HOST_NAME": "localhost:7072",
    "APPINSIGHTS_INSTRUMENTATIONKEY": "11111111-2222-3333-4444-555555555555"
  },
  "Host": {
    "LocalHttpPort": 7072
  }
}

In my case I have 2 AI instances, the APPINSIGHTS_INSTRUMENTATIONKEYvalues in my Azure Portal and in my local dev env (local.settings.json) is different so that I would not confuse prod and dev telemetries.

np_6
  • 514
  • 1
  • 6
  • 19
milkersarac
  • 3,399
  • 3
  • 31
  • 31
  • Worked for me under runtime 2.0.12427.0 – Migg May 03 '19 at 04:04
  • 11
    The key point: there must be `"APPINSIGHTS_INSTRUMENTATIONKEY": "dummy_key"` in `local.settings.json` for AppInsights to work locally. – Monsignor Mar 24 '20 at 10:10
  • Adding `AzureWebJobsStorage` and `AzureWebJobsDashboard` were key for me. – jrap Apr 16 '21 at 20:09
  • this no longer works, at least not with functions runtime v4 and VS2022 – chumtoadafuq Feb 24 '22 at 09:15
  • @chumtoadafuq were you able to find a workaround? – zane Apr 29 '22 at 08:25
  • @Mehnaz nope... gave up in the end and just accepted using AI when running in Azure for prod – chumtoadafuq Apr 29 '22 at 12:30
  • @milkersarac is there any option that we can give different key name for APPINSIGHTS_INSTRUMENTATIONKEY instead and configure application insights for Function App. – cva Jul 07 '22 at 14:16
  • I am not sure @cva, it has been a while and I am not familiar with AzureFunctions anymore. But it seems like you still need to use the exact key name you mentioned. I think the key's value is no longer critical since a magic nuget package is handling the stuff behind the stage. – milkersarac Jul 08 '22 at 07:34
  • @milkersarac Thanks for reply, basically i want to deploy in k8s, so multiple functions need to have their own application insights key. So i am curious to configure different key name defining each function app instead of existing APPINSIGHTS_INSTRUMENTATIONKEY. anyhow thanks for confirmation from your end – cva Jul 11 '22 at 06:49
21

So, apparently due to the changes being done to the libraries, every now and then it will stop working. So this is what helped me to make it work in April 2019. Hopefully it will help others.

I haven't added any log or anything specific to my function app, right now for me it's pretty much printing all the console data to the Trace logs in my app insights (locally, not needing yet to configure anything in Azure). Also, my test scenario is running on TargetFramework netstandard2.0 and AzureFunctionsVersion 2.

First you need to add this NuGet package to the function app: https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Logging.ApplicationInsights/

Then you have to add an empty file to your project root: ApplicationInsights.config you don't need to copy it to output when building or anything, this is just something that has to be there or Application Insights won't work locally.

Then you need to add some value to your APPINSIGHTS_INSTRUMENTATIONKEY in local.settings.json. This is where it differs from regular console apps, where even if the instrumentation key is empty it will work locally. In function apps apparently you need to add some value there. It can be anything, I've done this and it worked fine:

"APPINSIGHTS_INSTRUMENTATIONKEY": "you-need-to-have-anything-at-all-here-so-it-will-work-locally"
Rafael Merlin
  • 2,517
  • 1
  • 25
  • 31
  • 2
    What documentation led you to this discovery? Is this information available online anywhere? If so please could you provide the link – Fola Oct 04 '19 at 11:43
  • Sorry, I haven't seen your comment before. I am pretty sure I found this by trial and error, can't recall any mention about this in the docs. – Rafael Merlin May 20 '20 at 05:13
  • 4
    This is crazy. It's 2021 and this is still the workaround for Azure Functions. I wasted a couple of hours figuring out why the telemetry data wouldn't show up locally after using VS gui to add Local Application Insights. Thanks for this work around! – Nicklas Møller Jepsen Apr 13 '21 at 07:05
2

As far as I know, currently we couldn't directly include the Application Insights in your local azure function project.

Here is a workaround:

You need implement it by yourself. After installed the Microsoft.ApplicationInsights from the Nuget package manager.

Then use TelemetryClient to send the logs to the azure.

More details, you could refer to below codes:

[FunctionName("HttpTriggerCSharp")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
{
    var appInsights = GetTelemetryClient();
    //track an event
    appInsights.TrackEvent("I am starting now. I'm timer triggered");
    // track a numeric value
    appInsights.TrackMetric("Ticks based on current time", DateTime.Now.Ticks);
    // track an exception
    appInsights.TrackException(new Exception($"Random exception at {DateTime.Now}"));

    // send data to azure
    appInsights.Flush();

    log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    name = name ?? data?.name;

    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}

private static TelemetryClient GetTelemetryClient()
{
    var telemetryClient = new TelemetryClient();
    telemetryClient.InstrumentationKey = "Your InstrumentationKey";
    return telemetryClient;
}

Result:

enter image description here

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
Brando Zhang
  • 22,586
  • 6
  • 37
  • 65
0

Here is a solution that works for me using Azure Function v4 .NET6 in isolated mode. Prior to finding this solution I tried many combinations of settings in host.json which seemed to do nothing. Now I am properly tracking Entity Framework Core dependencies (as well as SignalR) in both Live metrics, Transaction search, and Application Map within Application Insights.

Local data from a local debug session will show in both the Application Insights portal within Azure (Live and Historical Telemetry) and Visual Studio 2022's Application Insights Search Telemetry. Please note, it takes a few minutes for local data to start populating in the Search Telemetry feature. If you are not finding local debug data, remember that Visual Studio must be running the function in Debug mode and you might also need to connect to the online Application Insights service (instead of Debug session telemetry): enter image description here

Try changing the Debug session telemetry to the online instance of Application Insights within Azure. Click on "Debug session telemetry" to change the source of the data.

For reference, this github issue "Correct way to use Application Insights in v4 and .Net 6 #760" led met to this solution.

Add the package:

Install-Package Microsoft.Data.SqlClient -Version 5.0.0

Then in program.cs add:

services.AddApplicationInsightsTelemetryWorkerService();

For reference, a working host.json:

{
  "version": "2.0",  
  "logging": {
    "fileLoggingMode": "always",
    "logLevel": {
      "default": "Information",
      "Host": "Warning",
      "Microsoft": "Warning"
    },
    "applicationInsights": {
      "samplingSettings": {
        "maxTelemetryItemsPerSecond": 5,
        "isEnabled": true,
        "excludedTypes": "Request;Exception"
      },
      "enableLiveMetrics": true,
      "enableDependencyTracking": true,
      "DependencyTrackingOptions": { "enableSqlCommandTextInstrumentation": true },
      "enablePerformanceCountersCollection": true
    }
  }
}
jassent
  • 529
  • 3
  • 10