Skip to content

Commit a4df919

Browse files
authored
Add initializer sample which reads data from HttpContext
This useful functionality is hidden away in some StackOverflow posts and some official telemetry initializers, for example [here](https://github.com/microsoft/ApplicationInsights-aspnetcore/blob/a135f1f7d9da7beb11f9bcf20a30f7e779b739f2/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/TelemetryInitializerBase.cs).
1 parent f6a4ca7 commit a4df919

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

articles/azure-monitor/app/api-filtering-sampling.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -485,13 +485,41 @@ The following sample initializer sets cloud role name to every tracked telemetry
485485
```csharp
486486
public void Initialize(ITelemetry telemetry)
487487
{
488-
if(string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName))
488+
if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName))
489489
{
490490
telemetry.Context.Cloud.RoleName = "MyCloudRoleName";
491491
}
492492
}
493493
```
494494

495+
#### Add information from HttpContext
496+
497+
The following sample initializer reads data from the [`HttpContext`](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-3.1) and appends it to a `RequestTelemetry` instance.
498+
499+
```csharp
500+
public class HttpContextRequestTelemetryInitializer : ITelemetryInitializer
501+
{
502+
private readonly IHttpContextAccessor httpContextAccessor;
503+
504+
public HttpContextRequestTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
505+
{
506+
this.httpContextAccessor =
507+
httpContextAccessor ??
508+
throw new ArgumentNullException(nameof(httpContextAccessor));
509+
}
510+
511+
public void Initialize(ITelemetry telemetry)
512+
{
513+
var requestTelemetry = telemetry as RequestTelemetry;
514+
if (requestTelemetry == null) return;
515+
516+
var claims = this.httpContextAccessor.HttpContext.User.Claims;
517+
Claim oidClaim = claims.FirstOrDefault(claim => claim.Type == "oid");
518+
requestTelemetry.Properties.Add("UserOid", oidClaim?.Value);
519+
}
520+
}
521+
```
522+
495523
## ITelemetryProcessor and ITelemetryInitializer
496524

497525
What's the difference between telemetry processors and telemetry initializers?

0 commit comments

Comments
 (0)