Correlating Services in App Insights
When one service call another service it is important when troubleshooting latency issues to know how long each service is taking to process, it’s also important to see the stack of calls that happen across both services to help track down errors. To do this you can use a correlation id.
Microsoft App Insights provides a unique id for each request that comes into service. To access it via code you can do this:
System.Diagnostics.Activity.Current?.RootId;
Note: You may need to add the nuget package System.Diagnostics.DiagnosticSource
To pass this ID onto another service will depend on how you are calling that service. If its a REST API i would suggest adding a http header (say operation-id) containing this value.
The next step for the service to accept that id and use it. In your other service you will need to add a Telemetry Initializer to your App Insights setup code:
TelemetryConfiguration.Active.TelemetryInitializers.Add(new CorrelationInitializer());
Then create the class CorrelationInitializer.cs:
public class CorrelationInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
string operationId = HttpContext.Current.Request.Headers.Get("operation-id");
if (!string.IsNullOrEmpty(operationId))
{
telemetry.Context.Operation.Id = operationId;
}
}
}
Notice in this case we get the operation id from a http header.
Now, when service A calls service B the call will include the operationid from A and apply it to B and your application insights logs will look a lot better for it!