Application Insights with Azure Functions is a bit tricky, when the Function Host runs inside a container instead of being hosted as by Azure directly. This is mainly due to the fact that Azure Functions have Application Insights Functionality built-in and that integration has not been built for Container primarily as it seems.
What we need to understand first is the difference between a Function and a Function App. A Function App can host multiple Azure Functions that share the same runtime and resources. It the the unit that gets scaled up and down and manages its different Functions, which can have different triggers and purposes. Usually, the Functions don't interact with the Function App directly. This Azure Function App is what gets containerized when putting Azure Functions inside a Container and this Azure Function App has Application Insights built in.
Enable Application Insights
Enabling Application Insights for Azure Functions happens on a host level, not for individual Functions. The easiest way to enable it, is to provide an Instrumentation Key as the
APPINSIGHTS_INSTRUMENTATIONKEY environment variable for the container.
More detailed Application Insights Settings can be done by editing the
host.json file, that comes with every Function App project. You can find the configuration details here.
Set a Cloud Role Name
This was a lot tricker to figure out. In Application Insights, the Cloud Role Name is a unique identifier for a service, that shares the same Instrumentation Key with other services, which is best practice when developing micro services. Without a Cloud Role Name, Application Insights does not differentiate between the services and it would look like they were calling themselves all the time in the Application Map.
When passing such a Cloud Role Name to Application Insights, it can differentiate between services that are using the same Instrumentation Key.
Usually, applications like ASP.NET Core Services set their Cloud Role Name through a custom Telemetry Initializer. As Azure Functions have Application Insights built-in on a host level, adding such a Telemetry Initializer in the Function code has no effect. Instead, we can set it again via an environment variable for the container called