-
Notifications
You must be signed in to change notification settings - Fork 280
/
OperationCorrelationTelemetryInitializer.cs
45 lines (41 loc) · 1.84 KB
/
OperationCorrelationTelemetryInitializer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
namespace Microsoft.ApplicationInsights.Extensibility
{
using Implementation;
using Microsoft.ApplicationInsights.Channel;
/// <summary>
/// Telemetry initializer that populates OperationContext for the telemetry item based on context stored in AsyncLocal variable.
/// </summary>
public class OperationCorrelationTelemetryInitializer : ITelemetryInitializer
{
/// <summary>
/// Initializes/Adds operation id to the existing telemetry item.
/// </summary>
/// <param name="telemetryItem">Target telemetry item to add operation id.</param>
public void Initialize(ITelemetry telemetryItem)
{
var itemContext = telemetryItem.Context.Operation;
if (string.IsNullOrEmpty(itemContext.ParentId) || string.IsNullOrEmpty(itemContext.Id) || string.IsNullOrEmpty(itemContext.Name))
{
var parentContext = AsyncLocalHelpers.GetCurrentOperationContext();
if (parentContext != null)
{
if (string.IsNullOrEmpty(itemContext.ParentId)
&& !string.IsNullOrEmpty(parentContext.ParentOperationId))
{
itemContext.ParentId = parentContext.ParentOperationId;
}
if (string.IsNullOrEmpty(itemContext.Id)
&& !string.IsNullOrEmpty(parentContext.RootOperationId))
{
itemContext.Id = parentContext.RootOperationId;
}
if (string.IsNullOrEmpty(itemContext.Name)
&& !string.IsNullOrEmpty(parentContext.RootOperationName))
{
itemContext.Name = parentContext.RootOperationName;
}
}
}
}
}
}