public void WithSpan_NoopOnBrokenScope(bool stopSpan, bool recordEvents) { var spanContext = new SpanContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), recordEvents ? ActivityTraceFlags.Recorded : ActivityTraceFlags.None); var parentSpan = tracer.StartSpan("parent", spanContext); var parentScope = CurrentSpanUtils.WithSpan(parentSpan, stopSpan); var childSpan = (Span)tracer.StartSpan("child", parentSpan); var childActivity = childSpan.Activity; Assert.Same(parentSpan, CurrentSpanUtils.CurrentSpan); var childScope = CurrentSpanUtils.WithSpan(childSpan, stopSpan); parentScope.Dispose(); Assert.Same(childSpan, CurrentSpanUtils.CurrentSpan); Assert.Equal(childActivity, Activity.Current); }
public void WithSpan_WrongActivity(bool stopSpan, bool recordEvents) { var spanContext = new SpanContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), recordEvents ? ActivityTraceFlags.Recorded : ActivityTraceFlags.None); var span = (Span)tracer.StartSpan("foo", spanContext); Assert.Same(BlankSpan.Instance, CurrentSpanUtils.CurrentSpan); using (CurrentSpanUtils.WithSpan(span, stopSpan)) { Assert.Same(span.Activity, Activity.Current); Assert.Same(span, CurrentSpanUtils.CurrentSpan); var anotherActivity = new Activity("foo").Start(); } Assert.Same(BlankSpan.Instance, CurrentSpanUtils.CurrentSpan); Assert.NotSame(span.Activity, Activity.Current); Assert.NotNull(Activity.Current); }
public void HttpDependencyNameIsActivityDisplayNameByDefault() { using ActivitySource activitySource = new ActivitySource(ActivitySourceName); using var activity = activitySource.StartActivity( ActivityName, ActivityKind.Client, parentContext: new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded), startTime: DateTime.UtcNow); activity.SetTag(SemanticConventions.AttributeHttpMethod, "GET"); activity.DisplayName = "HTTP GET"; var monitorTags = TraceHelper.EnumerateActivityTags(activity); var remoteDependencyDataName = new RemoteDependencyData(2, activity, ref monitorTags).Name; Assert.Equal(activity.DisplayName, remoteDependencyDataName); }
public void BasicActivityTracking() { var healthReporter = new Mock <IHealthReporter>(); var observer = new TestObserver(); var ActivityName = GetRandomName(); var sources = new List <ActivitySourceConfiguration>(new[] { new ActivitySourceConfiguration { ActivitySourceName = SourceOneName, ActivityName = ActivityName, CapturedData = ActivitySamplingResult.AllData, CapturedEvents = CapturedActivityEvents.Both } }); using (var input = new ActivitySourceInput(new ActivitySourceInputConfiguration { Sources = sources }, healthReporter.Object)) { input.Subscribe(observer); var ctx = new ActivityContext( ActivityTraceId.CreateFromString(WellKnownTraceId), ActivitySpanId.CreateFromString(SpanIdOne), ActivityTraceFlags.None); var activity = SourceOne.StartActivity(ActivityName, ActivityKind.Internal, ctx); activity.Stop(); } healthReporter.VerifyNoOtherCalls(); Assert.Equal(2, observer.Data.Count); Assert.True(observer.Completed); Assert.Null(observer.Error); Assert.True(observer.Data.TryDequeue(out EventData e)); VerifyActivityEvent(e, ActivityName, SourceOneName, CapturedActivityEvents.Start, WellKnownTraceId, SpanIdOne); Assert.True(observer.Data.TryDequeue(out e)); VerifyActivityEvent(e, ActivityName, SourceOneName, CapturedActivityEvents.Stop, WellKnownTraceId, SpanIdOne); }
public async Task CustomTextFormat() { var spanProcessor = new Mock<ActivityProcessor>(); var expectedTraceId = ActivityTraceId.CreateRandom(); var expectedSpanId = ActivitySpanId.CreateRandom(); var textFormat = new Mock<ITextFormatActivity>(); textFormat.Setup(m => m.Extract<HttpRequest>(It.IsAny<HttpRequest>(), It.IsAny<Func<HttpRequest, string, IEnumerable<string>>>())).Returns(new ActivityContext( expectedTraceId, expectedSpanId, ActivityTraceFlags.Recorded)); // Arrange using (var testFactory = this.factory .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => { this.openTelemetrySdk = OpenTelemetrySdk.EnableOpenTelemetry( (builder) => builder.AddRequestInstrumentation((opt) => opt.TextFormat = textFormat.Object) .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object))); }))) { using var client = testFactory.CreateClient(); var response = await client.GetAsync("/api/values/2"); response.EnsureSuccessStatusCode(); // Status Code 200-299 WaitForProcessorInvocations(spanProcessor, 4); } // begin and end was called once each. Assert.Equal(2, spanProcessor.Invocations.Count); var span = (Activity)spanProcessor.Invocations[1].Arguments[0]; Assert.Equal(ActivityKind.Server, span.Kind); Assert.True(span.Duration != TimeSpan.Zero); Assert.Equal("api/Values/{id}", span.DisplayName); Assert.Equal("/api/values/2", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.HttpPathKey).Value); Assert.Equal(expectedTraceId, span.Context.TraceId); Assert.Equal(expectedSpanId, span.ParentSpanId); }
public async Task TestW3CHeadersTraceStateAndCorrelationContext() { try { using (var eventRecords = new EventObserverAndRecorder()) { var parent = new Activity("w3c activity"); parent.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom()); parent.TraceStateString = "some=state"; parent.AddBaggage("k", "v"); parent.Start(); // Send a random Http request to generate some events using (var client = new HttpClient()) { (await client.GetAsync(Configuration.Http.RemoteEchoServer)).Dispose(); } parent.Stop(); // Check to make sure: The first record must be a request, the next record must be a response. Assert.True(eventRecords.Records.TryDequeue(out var evnt)); Assert.Equal("System.Net.Http.Desktop.HttpRequestOut.Start", evnt.Key); HttpWebRequest startRequest = ReadPublicProperty <HttpWebRequest>(evnt.Value, "Request"); Assert.NotNull(startRequest); var traceparent = startRequest.Headers["traceparent"]; var tracestate = startRequest.Headers["tracestate"]; var correlationContext = startRequest.Headers["Correlation-Context"]; Assert.NotNull(traceparent); Assert.Equal("some=state", tracestate); Assert.Equal("k=v", correlationContext); Assert.True(traceparent.StartsWith($"00-{parent.TraceId.ToHexString()}-")); Assert.True(Regex.IsMatch(traceparent, "^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$")); Assert.Null(startRequest.Headers["Request-Id"]); } } finally { CleanUp(); } }
public void ValidateHttpRequestDataResponseCode(string httpStatusCode) { using ActivitySource activitySource = new ActivitySource(ActivitySourceName); using var activity = activitySource.StartActivity( ActivityName, ActivityKind.Server, parentContext: new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded), startTime: DateTime.UtcNow); var httpResponseCode = httpStatusCode ?? "0"; activity.SetTag(SemanticConventions.AttributeHttpUrl, "https://www.foo.bar/search"); activity.SetTag(SemanticConventions.AttributeHttpStatusCode, httpStatusCode); var monitorTags = AzureMonitorConverter.EnumerateActivityTags(activity); var requestData = TelemetryPartB.GetRequestData(activity, ref monitorTags); Assert.Equal(httpResponseCode, requestData.ResponseCode); }
public void StartSpanLastParentWins7() { var spanContext = new SpanContext( ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None); var activity = new Activity("foo") .SetIdFormat(ActivityIdFormat.W3C) .Start(); var childSpan = (Span) new SpanBuilder(SpanName, spanProcessor, alwaysSampleTracerConfiguration, Resource.Empty) .SetCreateChild(false) .SetParent(spanContext) .StartSpan(); Assert.True(childSpan.Context.IsValid); Assert.Equal(spanContext.TraceId, childSpan.Context.TraceId); Assert.Equal(spanContext.SpanId, childSpan.ParentSpanId); }
public void StartSpanLastParentWins5() { var spanContext = SpanContext.Create( ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, Tracestate.Empty); var activity = new Activity("foo") .SetIdFormat(ActivityIdFormat.W3C) .Start(); var childSpan = (Span) new SpanBuilder(SpanName, spanProcessor, alwaysSampleTraceConfig) .SetParent(spanContext) .SetParent(activity) .StartSpan(); Assert.True(childSpan.Context.IsValid); Assert.Equal(activity.TraceId, childSpan.Context.TraceId); Assert.Equal(activity.SpanId, childSpan.ParentSpanId); }
public void StartSpanLastParentWins7() { var spanContext = SpanContext.Create( ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, Tracestate.Empty); var activity = new Activity("foo") .SetIdFormat(ActivityIdFormat.W3C) .Start(); var childSpan = (Span) new SpanBuilder(SpanName, spanBuilderOptions) .SetCreateChild(false) .SetParent(spanContext) .StartSpan(); Assert.True(childSpan.Context.IsValid); Assert.Equal(spanContext.TraceId, childSpan.Context.TraceId); Assert.Equal(spanContext.SpanId, childSpan.ParentSpanId); }
public void GeneratePartAEnvelope_Activity_WithParentSpanId() { using ActivitySource activitySource = new ActivitySource(ActivitySourceName); using var activity = activitySource.StartActivity( ActivityName, ActivityKind.Client, parentContext: new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded), startTime: DateTime.UtcNow); var resource = CreateTestResource(); var telemetryItem = TelemetryPartA.GetTelemetryItem(activity, resource, null); Assert.Equal("RemoteDependency", telemetryItem.Name); Assert.Equal(TelemetryPartA.FormatUtcTimestamp(activity.StartTimeUtc), telemetryItem.Time); Assert.StartsWith("unknown_service", telemetryItem.Tags[ContextTagKeys.AiCloudRole.ToString()]); Assert.Null(telemetryItem.Tags[ContextTagKeys.AiCloudRoleInstance.ToString()]); Assert.NotNull(telemetryItem.Tags[ContextTagKeys.AiOperationId.ToString()]); Assert.NotNull(telemetryItem.Tags[ContextTagKeys.AiInternalSdkVersion.ToString()]); Assert.Equal(activity.ParentSpanId.ToHexString(), telemetryItem.Tags[ContextTagKeys.AiOperationParentId.ToString()]); }
public async Task SuccessfulTemplateControllerCallUsesParentContext() { var spanProcessor = new Mock <SpanProcessor>(); var expectedTraceId = ActivityTraceId.CreateRandom(); var expectedSpanId = ActivitySpanId.CreateRandom(); // Arrange using (var testFactory = this.factory .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => { services.AddSingleton <TracerFactory>(_ => TracerFactory.Create(b => b .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor.Object)) .AddRequestCollector())); }))) using (var client = testFactory.CreateClient()) { var request = new HttpRequestMessage(HttpMethod.Get, "/api/values/2"); request.Headers.Add("traceparent", $"00-{expectedTraceId}-{expectedSpanId}-01"); // Act var response = await client.SendAsync(request); // Assert response.EnsureSuccessStatusCode(); // Status Code 200-299 WaitForProcessorInvocations(spanProcessor, 2); } Assert.Equal(2, spanProcessor.Invocations.Count); // begin and end was called var span = (SpanData)spanProcessor.Invocations[1].Arguments[0]; Assert.Equal(SpanKind.Server, span.Kind); Assert.Equal("api/Values/{id}", span.Name); Assert.Equal("/api/values/2", span.Attributes.GetValue("http.path")); Assert.Equal(expectedTraceId, span.Context.TraceId); Assert.Equal(expectedSpanId, span.ParentSpanId); }
public void TestActivityCreationProperties() { RemoteExecutor.Invoke(() => { ActivitySource source = new ActivitySource("MultipleListenerSource"); using ActivityListener listener = new ActivityListener(); listener.ActivityStarted = activity => Assert.NotNull(activity); listener.ActivityStopped = activity => Assert.NotNull(activity); listener.ShouldListenTo = (activitySource) => true; listener.GetRequestedDataUsingParentId = (ref ActivityCreationOptions <string> activityOptions) => ActivityDataRequest.AllData; listener.GetRequestedDataUsingContext = (ref ActivityCreationOptions <ActivityContext> activityOptions) => ActivityDataRequest.AllData; ActivitySource.AddActivityListener(listener); ActivityContext ctx = new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded, "key0-value0"); List <ActivityLink> links = new List <ActivityLink>(); links.Add(new ActivityLink(new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, "key1-value1"))); links.Add(new ActivityLink(new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, "key2-value2"))); List <KeyValuePair <string, object> > attributes = new List <KeyValuePair <string, object> >(); attributes.Add(new KeyValuePair <string, object>("tag1", "tagValue1")); attributes.Add(new KeyValuePair <string, object>("tag2", "tagValue2")); attributes.Add(new KeyValuePair <string, object>("tag3", "tagValue3")); using (Activity activity = source.StartActivity("a1", ActivityKind.Client, ctx, attributes, links)) { Assert.NotNull(activity); Assert.Equal("a1", activity.OperationName); Assert.Equal("a1", activity.DisplayName); Assert.Equal(ActivityKind.Client, activity.Kind); Assert.Equal(ctx.TraceId, activity.TraceId); Assert.Equal(ctx.SpanId, activity.ParentSpanId); Assert.Equal(ctx.TraceFlags, activity.ActivityTraceFlags); Assert.Equal(ctx.TraceState, activity.TraceStateString); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); foreach (KeyValuePair <string, object> pair in attributes) { Assert.NotEqual(default, activity.Tags.FirstOrDefault((p) => pair.Key == p.Key && pair.Value == pair.Value));
public void BeginWebTrackingWithDesktopParentActivityReturnsOperationItemWithTelemetryItem() { var activity = new Activity("System.Net.Http.Desktop.HttpRequestOut"); activity.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None); activity.AddBaggage("k", "v"); activity.Start(); var telemetry = ClientServerDependencyTracker.BeginTracking(this.telemetryClient); Assert.AreEqual(activity.SpanId.ToHexString(), telemetry.Id); Assert.AreEqual(activity.TraceId.ToHexString(), telemetry.Context.Operation.Id); Assert.AreEqual(activity.ParentSpanId.ToHexString(), telemetry.Context.Operation.ParentId); var properties = telemetry.Properties; Assert.AreEqual(1, properties.Count); Assert.AreEqual("v", properties["k"]); activity.Stop(); }
private static Activity CopyFromCompatibleRoot(Activity from) { var copy = new Activity(from.OperationName); copy.SetParentId(ActivityTraceId.CreateFromString(from.RootId.AsSpan()), default(ActivitySpanId), from.ActivityTraceFlags); foreach (var tag in from.Tags) { copy.AddTag(tag.Key, tag.Value); } foreach (var baggage in from.Baggage) { copy.AddBaggage(baggage.Key, baggage.Value); } copy.TraceStateString = from.TraceStateString; return(copy); }
public static TraceParent CreateFromString(string traceparent) { if (string.IsNullOrWhiteSpace(traceparent)) { throw new ArgumentException("Invalid traceparent", nameof(traceparent)); } var vals = traceparent.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries); if (vals.Length != 4) { throw new ArgumentException("Invalid traceparent format: {traceparent}", traceparent); } var traceId = ActivityTraceId.CreateFromString(vals[1].AsSpan()); var spanId = ActivitySpanId.CreateFromString(vals[2].AsSpan()); var flags = vals[3] == "01" ? ActivityTraceFlags.Recorded : ActivityTraceFlags.None; // TODO: validate each item return(new TraceParent(traceId, spanId, flags, vals[0])); }
public void InjectExtract_TextMap_Ok() { var tracerMock = new Mock <Trace.Tracer>(); var carrier = new TextMapCarrier(); var spanContextShim = new SpanContextShim(new SpanContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None)); var format = new TraceContextFormat(); var tracer = TracerProvider.GetTracer(TracerName); var shim = new TracerShim(tracer, format); // first inject shim.Inject(spanContextShim, BuiltinFormats.TextMap, carrier); // then extract var extractedSpanContext = shim.Extract(BuiltinFormats.TextMap, carrier); AssertOpenTracerSpanContextEqual(spanContextShim, extractedSpanContext); }
public async Task TestTraceStateAndBaggage() { try { using var eventRecords = new ActivitySourceRecorder(); var parent = new Activity("w3c activity"); parent.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom()); parent.TraceStateString = "some=state"; parent.Start(); Baggage.SetBaggage("k", "v"); // Send a random Http request to generate some events using (var client = new HttpClient()) { (await client.GetAsync(this.BuildRequestUrl())).Dispose(); } parent.Stop(); Assert.Equal(2, eventRecords.Records.Count()); // Check to make sure: The first record must be a request, the next record must be a response. (Activity activity, HttpWebRequest startRequest) = AssertFirstEventWasStart(eventRecords); var traceparent = startRequest.Headers["traceparent"]; var tracestate = startRequest.Headers["tracestate"]; var baggage = startRequest.Headers["baggage"]; Assert.NotNull(traceparent); Assert.Equal("some=state", tracestate); Assert.Equal("k=v", baggage); Assert.StartsWith($"00-{parent.TraceId.ToHexString()}-", traceparent); Assert.Matches("^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$", traceparent); } finally { this.CleanUpActivity(); } }
public void CheckCacheIsFlushedProperly() { var connectionOptions = new ConfigurationOptions { AbortOnConnectFail = false, }; connectionOptions.EndPoints.Add("localhost:6379"); var connection = ConnectionMultiplexer.Connect(connectionOptions); using var instrumentation = new StackExchangeRedisCallsInstrumentation(connection, new StackExchangeRedisCallsInstrumentationOptions()); var profilerFactory = instrumentation.GetProfilerSessionsFactory(); // start a root level activity using Activity rootActivity = new Activity("Parent") .SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded) .Start(); Assert.NotNull(rootActivity.Id); // get an initial profiler from root activity Activity.Current = rootActivity; ProfilingSession profiler0 = profilerFactory(); // expect different result from synchronous child activity ProfilingSession profiler1; using (Activity.Current = new Activity("Child-Span-1").SetParentId(rootActivity.Id).Start()) { profiler1 = profilerFactory(); Assert.NotSame(profiler0, profiler1); } rootActivity.Stop(); rootActivity.Dispose(); instrumentation.Flush(); Assert.Empty(instrumentation.Cache); }
public async Task SuccessfulTemplateControllerCallUsesParentContext() { var activityProcessor = new Mock <ActivityProcessor>(); var expectedTraceId = ActivityTraceId.CreateRandom(); var expectedSpanId = ActivitySpanId.CreateRandom(); // Arrange using (var testFactory = this.factory .WithWebHostBuilder(builder => builder.ConfigureTestServices(services => { this.openTelemetrySdk = Sdk.CreateTracerProviderBuilder().AddAspNetCoreInstrumentation() .AddProcessor(activityProcessor.Object) .Build(); }))) { using var client = testFactory.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, "/api/values/2"); request.Headers.Add("traceparent", $"00-{expectedTraceId}-{expectedSpanId}-01"); // Act var response = await client.SendAsync(request); // Assert response.EnsureSuccessStatusCode(); // Status Code 200-299 WaitForProcessorInvocations(activityProcessor, 2); } Assert.Equal(2, activityProcessor.Invocations.Count); // begin and end was called var span = (Activity)activityProcessor.Invocations[1].Arguments[0]; Assert.Equal(ActivityKind.Server, span.Kind); Assert.Equal("api/Values/{id}", span.DisplayName); Assert.Equal("/api/values/2", span.Tags.FirstOrDefault(i => i.Key == SpanAttributeConstants.HttpPathKey).Value); Assert.Equal(expectedTraceId, span.Context.TraceId); Assert.Equal(expectedSpanId, span.ParentSpanId); }
public void DroppingLinksEnumerable() { var contextLink = new SpanContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None); var maxNumberOfLinks = 8; var traceConfig = new TracerConfiguration(32, 128, maxNumberOfLinks); var tracer = TracerFactory.Create(b => b .AddProcessorPipeline(p => p.AddProcessor(n => spanProcessor)) .SetTracerOptions(traceConfig) .SetSampler(new AlwaysSampleSampler())) .GetTracer(null); var overflowedLinks = new List <Link>(); var link = new Link(contextLink); for (var i = 0; i < 2 * maxNumberOfLinks; i++) { overflowedLinks.Add(link); } var span = (Span)tracer.StartSpan(SpanName, SpanKind.Client, new SpanCreationOptions { Links = overflowedLinks, }); Assert.Equal(maxNumberOfLinks, span.Links.Count()); foreach (var actualLink in span.Links) { Assert.Equal(link, actualLink); } span.End(); Assert.Equal(maxNumberOfLinks, span.Links.Count()); foreach (var actualLink in span.Links) { Assert.Equal(link, actualLink); } }
public void StartSpanFrom_NotRecorded_ParentSpan() { var tracer = tracerFactory.GetTracer(null); var grandParentContext = new SpanContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None); var parentSpan = (Span)tracer.StartSpan(SpanName, grandParentContext); var startTimestamp = PreciseTimestamp.GetUtcNow(); var span = (Span)tracer.StartSpan(SpanName, parentSpan); Assert.True(span.Context.IsValid); Assert.Equal(parentSpan.Context.TraceId, span.Context.TraceId); Assert.Equal(span.Activity.SpanId, span.Context.SpanId); Assert.Equal(parentSpan.Context.SpanId, span.ParentSpanId); Assert.Equal(parentSpan.Context.TraceOptions, span.Context.TraceOptions); Assert.Empty(span.Context.Tracestate); Assert.False(span.IsRecordingEvents); Assert.Equal(SpanKind.Internal, span.Kind); AssertApproxSameTimestamp(startTimestamp, span.StartTimestamp); Assert.Empty(span.Links); }
public void TraceContextFormatCanParseExampleFromSpec() { var headers = new Dictionary <string, string> { { TraceParent, $"00-{TraceId}-{SpanId}-01" }, { TraceState, $"congo=lZWRzIHRoNhcm5hbCBwbGVhc3VyZS4,rojo=00-{TraceId}-00f067aa0ba902b7-01" }, }; var f = new TraceContextFormatActivity(); var ctx = f.Extract(headers, Getter); Assert.Equal(ActivityTraceId.CreateFromString(TraceId.AsSpan()), ctx.TraceId); Assert.Equal(ActivitySpanId.CreateFromString(SpanId.AsSpan()), ctx.SpanId); // TODO: when ActivityContext supports IsRemote // Assert.True(ctx.IsRemote); Assert.True(ctx.IsValid()); Assert.True((ctx.TraceFlags & ActivityTraceFlags.Recorded) != 0); Assert.Equal($"congo=lZWRzIHRoNhcm5hbCBwbGVhc3VyZS4,rojo=00-{TraceId}-00f067aa0ba902b7-01", ctx.TraceState); }
public LinkTest() { this.spanContext = new SpanContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None); this.attributesMap.Add("MyAttributeKey0", "MyStringAttribute"); this.attributesMap.Add("MyAttributeKey1", 10L); this.attributesMap.Add("MyAttributeKey2", true); this.attributesMap.Add("MyAttributeKey3", 0.005); this.attributesMap.Add("MyAttributeKey4", new long[] { 1, 2 }); this.attributesMap.Add("MyAttributeKey5", new string[] { "a", "b" }); this.attributesMap.Add("MyAttributeKey6", new bool[] { true, false }); this.attributesMap.Add("MyAttributeKey7", new double[] { 0.1, -0.1 }); this.tags = new SpanAttributes(); this.tags.Add("MyAttributeKey0", "MyStringAttribute"); this.tags.Add("MyAttributeKey1", 10L); this.tags.Add("MyAttributeKey2", true); this.tags.Add("MyAttributeKey3", 0.005); this.tags.Add("MyAttributeKey4", new long[] { 1, 2 }); this.tags.Add("MyAttributeKey5", new string[] { "a", "b" }); this.tags.Add("MyAttributeKey6", new bool[] { true, false }); this.tags.Add("MyAttributeKey7", new double[] { 0.1, -0.1 }); }
public void ValidateSuccessForRequestAndRemoteDependency(string activityStatusCode, string activityStatusDescription) { using ActivitySource activitySource = new ActivitySource(ActivitySourceName); using var activity = activitySource.StartActivity( ActivityName, ActivityKind.Server, parentContext: new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded), startTime: DateTime.UtcNow); activity.SetTag("otel.status_code", activityStatusCode); activity.SetTag("otel.status_description", activityStatusDescription); activity.SetTag(SemanticConventions.AttributeHttpUrl, "https://www.foo.bar/search"); var monitorTags = AzureMonitorConverter.EnumerateActivityTags(activity); var requestData = TelemetryPartB.GetRequestData(activity, ref monitorTags); var remoteDependencyData = TelemetryPartB.GetRequestData(activity, ref monitorTags); Assert.Equal(activity.GetStatus().StatusCode != StatusCode.Error, requestData.Success); Assert.Equal(activity.GetStatus().StatusCode != StatusCode.Error, remoteDependencyData.Success); }
public void StartRemoteSpan() { var spanContext = SpanContext.Create( ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, Tracestate.Builder.Set("k1", "v1").Build()); var span = (Span) new SpanBuilder(SpanName, spanProcessor, alwaysSampleTraceConfig) .SetSpanKind(SpanKind.Internal) .SetParent(spanContext) .SetRecordEvents(true) .StartSpan(); Assert.True(span.Context.IsValid); Assert.Equal(spanContext.TraceId, span.Context.TraceId); Assert.True((span.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0); Assert.Equal(spanContext.SpanId, span.ParentSpanId); Assert.Equal("k1=v1", span.Context.Tracestate.ToString()); }
public void StartSpan_CurrentSpanParent() { var rootSpan = new SpanBuilder(SpanName, spanBuilderOptions) .SetParent( SpanContext.Create( ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None, Tracestate.Builder.Set("k1", "v1").Build())) .StartSpan(); using (tracer.WithSpan(rootSpan)) { var childSpan = (Span) new SpanBuilder(SpanName, spanBuilderOptions) .StartSpan(); Assert.True(childSpan.Context.IsValid); Assert.Equal(rootSpan.Context.TraceId, childSpan.Context.TraceId); Assert.Equal(rootSpan.Context.SpanId, childSpan.ParentSpanId); Assert.Equal("k1=v1", childSpan.Context.Tracestate.ToString()); } }
// Applies the given sampler to NUM_SAMPLE_TRIES random traceId/spanId pairs. private static void AssertSamplerSamplesWithProbability( ISampler sampler, SpanContext parent, List <ILink> links, double probability) { var count = 0; // Count of spans with sampling enabled for (var i = 0; i < NUM_SAMPLE_TRIES; i++) { if (sampler.ShouldSample( parent, ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), SPAN_NAME, links).IsSampled) { count++; } } var proportionSampled = (double)count / NUM_SAMPLE_TRIES; // Allow for a large amount of slop (+/- 10%) in number of sampled traces, to avoid flakiness. Assert.True(proportionSampled <probability + 0.1 && proportionSampled> probability - 0.1); }
public void DoNotCrash() { IDictionary <string, object> attributes = new Dictionary <string, object>(); attributes.Add( "MyStringAttributeKey", "MyStringAttributeValue"); IDictionary <string, object> multipleAttributes = new Dictionary <string, object>(); multipleAttributes.Add( "MyStringAttributeKey", "MyStringAttributeValue"); multipleAttributes.Add("MyBooleanAttributeKey", true); multipleAttributes.Add("MyLongAttributeKey", 123); multipleAttributes.Add("MyDoubleAttributeKey", 0.005); // Tests only that all the methods are not crashing/throwing errors. BlankSpan.Instance.SetAttribute( "MyStringAttributeKey2", "MyStringAttributeValue2"); foreach (var a in attributes) { BlankSpan.Instance.SetAttribute(a); } foreach (var a in multipleAttributes) { BlankSpan.Instance.SetAttribute(a); } BlankSpan.Instance.AddEvent("MyEvent"); BlankSpan.Instance.AddEvent("MyEvent", attributes); BlankSpan.Instance.AddEvent("MyEvent", multipleAttributes); BlankSpan.Instance.AddEvent(new Event("MyEvent")); BlankSpan.Instance.AddLink(new Link(new SpanContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None))); Assert.False(BlankSpan.Instance.Context.IsValid); Assert.False(BlankSpan.Instance.IsRecordingEvents); Assert.Equal(Status.Ok, BlankSpan.Instance.Status); BlankSpan.Instance.Status = Status.Ok; BlankSpan.Instance.End(); }
public void TelemetryPartBPropertiesContainsMSLinksWhenActivityHasLinks(string telemetryType) { using ActivitySource activitySource = new ActivitySource(ActivitySourceName); ActivityLink activityLink = new ActivityLink(new ActivityContext( ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None), null); List <ActivityLink> links = new List <ActivityLink>(); links.Add(activityLink); using var activity = activitySource.StartActivity( ActivityName, ActivityKind.Client, parentContext: default, null, links, startTime: DateTime.UtcNow); string expectedMSlinks = GetExpectedMSlinks(links); string actualMSlinks = null; var monitorTags = TraceHelper.EnumerateActivityTags(activity); if (telemetryType == "RequestData") { var telemetryPartBRequestData = new RequestData(2, activity, ref monitorTags); Assert.True(telemetryPartBRequestData.Properties.TryGetValue(msLinks, out actualMSlinks)); } if (telemetryType == "RemoteDependencyData") { var telemetryPartBRemoteDependencyData = new RemoteDependencyData(2, activity, ref monitorTags); Assert.True(telemetryPartBRemoteDependencyData.Properties.TryGetValue(msLinks, out actualMSlinks)); } Assert.Equal(expectedMSlinks, actualMSlinks); }