aws / aws-xray-sdk-dotnet

The official AWS X-Ray SDK for .NET.
Apache License 2.0
109 stars 64 forks source link

Entity doesn't exist in HTTP Context #292

Open linxiaoxin opened 9 months ago

linxiaoxin commented 9 months ago

Hi,

I am tracing the logs from .NET web form client to WCF service with trace of MSSQL queries.
Tracing header is passed from call to WCF service was able to traced and linked parent segment in XRAY. However, wasn't able to add sql trace to the XRay logs with the below error

"Failed to start subsegment because the parent segment is not available" "Failed to set namespace because of subsegment is not available" "Failed to add sql information because segment is not available in trace context." "Entity doesn't exist in HTTPContext"

Done the below to add tracing to WCF calls:

object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)

{ AWSXRayRecorder.Instance.BeginSubsegment(request.Headers.Action);

HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
string traceheader;
string rootId = AWSXRayRecorder.Instance.GetEntity().RootSegment.TraceId;
string parentId = AWSXRayRecorder.Instance.GetEntity().Id;
if (AWSXRayRecorder.Instance.GetEntity().Sampled == Amazon.XRay.Recorder.Core.Sampling.SampleDecision.Sampled)
{
    traceheader = $"Root={rootId};Parent={parentId};Sampled=1";
}
else if (AWSXRayRecorder.Instance.GetEntity().Sampled == Amazon.XRay.Recorder.Core.Sampling.SampleDecision.NotSampled)
{
    traceheader = $"Root={rootId};Parent={parentId};Sampled=0";
}
else
{
    traceheader = $"Root={rootId};Parent={parentId}";
}
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
    httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
    if (string.IsNullOrEmpty(httpRequestMessage.Headers["X-Amzn-Trace-Id"]))
    {
        ESEN2SharedLib.Common.ExceptionHandler.LogInfo($"Adding Trace header: {traceheader}");
        httpRequestMessage.Headers["X-Amzn-Trace-Id"] = traceheader;
    }
}
else
{
    httpRequestMessage = new HttpRequestMessageProperty();
    httpRequestMessage.Headers["X-Amzn-Trace-Id"] = traceheader;
    request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
return null;

} void IClientMessageInspector.AfterReceiveReply(ref Message reply, object correlationState) { AWSXRayRecorder.Instance.EndSubsegment(); }