Azure / azure-webjobs-sdk

Azure WebJobs SDK
MIT License
738 stars 358 forks source link

application insights integration - ITelemetryInitializer doesn't have any effects #1416

Open soorena776 opened 6 years ago

soorena776 commented 6 years ago

I'm integrating application insights with my App service which has a WebJobs project, following these instructions.

Things are working smoothly except that the cloud_RoleName and cloud_RoleInstanceName in ai portal are not meaningful (random numeric values, and seem to be changing over time). I used a custom TelemetryInitializer in the api role, and it is changing those values as desired. However the webjob project doesn't seem to be picking up the role names assigned in custom initializer. When debugging locally, the code does execute the custom initializer overriden values, but it seems that it is being changed when the log is being sent to ai.

Here is the custom initializer that I use: public class AppInsightsTelemetryInitializer : ITelemetryInitializer { public void Initialize(ITelemetry telemetry) { telemetry.Context.Cloud.RoleName = ConfigurationManager.AppSettings["EnvironmentName"]; telemetry.Context.Cloud.RoleInstance = $"webjob-{ConfigurationManager.AppSettings["InstanceId"]}"; } }

And it's hooked in WebJobs' Program.cs:

... ApplicationInsights.Extensibility.TelemetryConfiguration.Active.TelemetryInitializers.Add(new AppInsightsTelemetryInitializer()); ...

How can I change these values?

brettsam commented 6 years ago

You need to override the ITelemetryClientFactory that we use to create the TelemetryClient -- we don't use the global one available via TelemetryConfiguration.Active. You can do this by using the AddApplicationInsights extension method that takes an ITelemetryClientFactory: https://github.com/Azure/azure-webjobs-sdk/blob/v2.x/src/Microsoft.Azure.WebJobs.Logging.ApplicationInsights/ApplicationInsightsLoggerExtensions.cs#L43-L45

Here's the one we use by default: https://github.com/Azure/azure-webjobs-sdk/blob/v2.x/src/Microsoft.Azure.WebJobs.Logging.ApplicationInsights/DefaultTelemetryClientFactory.cs. Feel free to grab that code and modify whatever you need, or craft your own from scratch. If there's a hook point that you wish was there let me know and we can improve it.

FYI -- cloud_RoleName should be the name of your site. And cloud_RoleInstanceName is the WEBSITE_INSTANCE_ID, which uniquely identifies the machine. It can change because you're running on different physical machines.