Azure / Azure/azure-functions-core-tools
Register an unconfigured TelemetryConfiguration when App Insights instrumentation key is not present
- Dominant language
- C#
- Stars
- 1.5k
- Forks
- 498
- Avg merge
- 5d 4h
- Merged PRs (30d)
- 15
Description
#### What problem would the feature you're requesting solve? Please describe.
[Log custom telemetry in C# functions](https://docs.microsoft.com/en-us/azure/azure-functions/functions-monitoring?tabs=cmd#log-custom-telemetry-in-c-functions) recommends to inject `TelemetryConfiguration` in order to be able to emit custom telemetry. The runtime registers `TelemetryConfiguration` only when an Application Insights instrumentation key is present in the Function settings ([code responsible for the registration](https://github.com/Azure/azure-functions-host/blob/7d9cd7fc69b282b2f6ce2c2ee1574a236bc69202/src/WebJobs.Script/ScriptHostBuilderExtensions.cs#L368-L372)).
When running locally developers rarely configure Application Insights which leads to the below exception when the runtime attempts to instantiate a Function taking `TelemetryConfiguration` as a dependency:
> Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration' while attempting to activate [...].
#### Describe the solution you'd like
When no Application Insights instrumentation key is present, the runtime could register an unconfigured `TelemetryConfiguration` (e.g. without an instrumentation key):
```csharp
builder.Services.AddSingleton(new TelemetryConfiguration());
```
Every `TelemetryClient` instantiated using this unconfigured `TelemetryConfiguration` will in essence be a no-op. The SDK will not attempt to send the telemetry and no exception will be thrown when attempting to resolve `TelemetryConfiguration`.
#### Describe alternatives you've considered
There are several ways to workaround this issue.
_Use an instrumentation key when running locally_. This is what I wanted to avoid in the first place. Telemetry will be sent to an Application Insights instance and extra-cost might be incurred.
_Use a placeholder instrumentation key_. The SDK only verifies that a non-empty string is present. This results in the telemetry being sent and the ingestion point returning `400` Bad Request. This is unnecessary `HTTP` traffic.
_Register an unconfigured `TelemetryConfiguration` in the `Startup` class_. This is the solution I'm currently using but it feels like a hack:
```csharp
builder.Services.TryAddSingleton(new TelemetryConfiguration());
```
As the `Startup.Configure` method runs after the runtime registers Application Insights, the unconfigured `TelemetryConfiguration` will only be added if it has not been added before.
#### Additional context
I don't have any additional context, please let me know if you have any question.
Contributor guide
Assessment
This issue has not been assessed yet.