You could use the ILogger implementation to create a Scope with some properties that will be attached to all telemetry generated by calls to the logger:
using (_logger.BeginScope(new Dictionary<string, object>
{
{"CorrelationId", Guid.NewGuid()}
}))
{
_logger.LogWarning("Some Warning");
_logger.LogInformation("Some Info");
}
CorrelationId will be in the customDimensions field of the trace telemetry in Application Insights.
But, if you want to correlate also the dependency request you can use the TelemetryClient directly and explicitly create an operation that will be used to correlate all generated telemetry within the scope of that operation:
using (var operation = _telemetryClient.StartOperation<DependencyTelemetry>("Foo"))
{
_logger.LogDebug("Invoked API {ApiName}", new { ApiName = nameof(Foo), Data = data });
var requestContent = new StringContent(JsonSerializer.Serialize(data))
var httpResponse = await _httpClient.PostAsync(url, requestContent);
string responseStr = httpResponse.ReadAsStringAsync()
if (!httpResponse.IsSuccessStatusCode)
{
_logger.LogError("Failed API {ApiName}", new { ApiName = nameof(Foo), ResponseData = responseStr });
}
}
You can take this even further and set properties of the telemetry to reflect whether the call was succesful or not:
...
if (!httpResponse.IsSuccessStatusCode)
{
_logger.LogError("Failed API {ApiName}", new { ApiName = nameof(Foo), ResponseData = responseStr });
operation.Telemetry.Success = false;
}
...
But do mind that if you are building a .Net Web App there already might be an request operation in progress, and by looking up that request telemetry you might discover that the trace telemetry and dependencies are already associated by the request.