'What is the easiest way to add custom dimensions to default Request Telemetry for App service?
I just leverage default Application Insights logging to log the request telemetry without ANY custom code. The request telemetry looks like this:
timestamp [UTC] 2019-12-19T00:22:10.2563938Z
id |a758472d124b6e4688a33b2ad9755f33.b3979544_
name GET MyMethod [type]
url https://xxxx
success True
resultCode 200
duration 153.2676
performanceBucket <250ms
itemType request
customDimensions
AppId xxxx-xxxx-xxxx-xxxx-xxxxxx
AspNetCoreEnvironment: west us
_MS.ProcessedByMetricExtractors (Name:'Requests', Ver:'1.1')
Now I want to add a new property to customDimensions in Request telemetry, say, correlationId. What is the easiest way to to it? I just want to expend the existing request telemetry, don't want to create new event.
Solution 1:[1]
If you're interested in massaging data (i.e. modify based on what's available in telemetry item itself) then Ivan's answer is the right one.
If you'd like to add something to existing request then you need to do a few things:
1) Use Activity.Tags property bag while in a request
Activity.Current?.AddTag("TagName", "TagValue");
2) Have Telemetry initializer which puts tags as custom dimensions (in next versions we might add it as default initializer and this step will no longer be required)
/// <summary>
/// Helper class to workaround AI SDK not collecting activity tags by default.
/// This initializer allows the business logic to have no AI references.
/// </summary>
public class ActivityTagsTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
var activity = Activity.Current;
var requestTelemetry = telemetry as ISupportProperties;
if (requestTelemetry == null || activity == null) return;
foreach (var tag in activity.Tags)
{
requestTelemetry.Properties[tag.Key] = tag.Value;
}
}
}
3) Register in Startup
services.AddSingleton<ITelemetryInitializer, ActivityTagsTelemetryInitializer>();
Solution 2:[2]
You don't need to create your own TelemetryInitializer but can just do this from anywhere you can reference the httpContext:
var requestTelemetry = httpContext.Features.Get<RequestTelemetry>();
if (requestTelemetry != null)
{
requestTelemetry.Properties["YourCustomDimension"] = someValue;
}
Properties added in this way will be added to the requests table in Application Insights.
To add for the dependencies and traces tables you can use
System.Diagnostics.Activity.Current.AddBaggage("YourCustomDimension" someValue);
To add to traces when you write a log entry just pass in objects to the LogXXX method with a placeholder in the log message, e.g.
_logger.LogWarning("hello {YourCustomDimension}", someValue);
someValue will be serialized to json so can be a complex object if you like.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ZakiMa |
| Solution 2 | Rory |
