Skip to content

Commit be04357

Browse files
authored
Merge pull request #52415 from ahelwer/patch-2
Add initializer sample which reads data from HttpContext
2 parents 291be76 + e1f46c7 commit be04357

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/aspnet/core/fundamentals/http-context?view=aspnetcore-3.1) and appends it to a `RequestTelemetry` instance. The `IHttpContextAccessor` is automatically provided through constructor dependency injection.
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)