Example #1
0
        public static void UseTracing(this IApplicationBuilder app, string serviceName,
                                      Func <HttpContext, string> getRpc = null)
        {
            getRpc = getRpc ?? (context => context.Request.Method);
            var extractor = Propagations.B3String.Extractor <IHeaderDictionary>((carrier, key) => carrier[key]);

            app.Use(async(context, next) =>
            {
                var request      = context.Request;
                var traceContext = extractor.Extract(request.Headers);

                var trace     = traceContext == null ? Trace.Create() : Trace.CreateFromId(traceContext);
                Trace.Current = trace;
                using (var serverTrace = new ServerTrace(serviceName, getRpc(context)))
                {
                    if (request.Host.HasValue)
                    {
                        trace.Record(Annotations.Tag("http.host", request.Host.ToString()));
                    }
                    trace.Record(Annotations.Tag("http.uri", UriHelper.GetDisplayUrl(request)));
                    trace.Record(Annotations.Tag("http.path", request.Path));
                    await serverTrace.TracedActionAsync(next());
                }
            });
        }
Example #2
0
        public void TraceIdHighIsNotGeneratedIf128BitsDeactivated()
        {
            TraceManager.Trace128Bits = false;
            var trace = Trace.Create();

            Assert.AreEqual(SpanState.NoTraceIdHigh, trace.CurrentSpan.TraceIdHigh);
        }
Example #3
0
        public void ShouldLogAnnotation()
        {
            // Arrange
            dispatcher
            .Setup(h => h.Dispatch(It.IsAny <Record>()))
            .Returns(true);

            var trace = Trace.Create();

            trace.ForceSampled();
            Trace.Current = trace;
            var baseStandardTrace = new BaseStandardTrace
            {
                Trace = trace
            };

            // Act
            baseStandardTrace.AddAnnotation(Annotations.WireSend());

            // Assert
            dispatcher
            .Verify(h =>
                    h.Dispatch(It.Is <Record>(m =>
                                              m.Annotation is WireSend)));
        }
Example #4
0
        public void ExceptionThrownInTracedActionAsyncShouldAddErrorTagAndRethrow()
        {
            var trace = Trace.Create();

            trace.ForceSampled();
            Trace.Current = trace;
            var baseStandardTrace = new BaseStandardTrace
            {
                Trace = trace
            };
            var  ex   = new Exception("something bad happened");
            Task task = Task.Run(() =>
            {
                try
                {
                    return;
                }
                finally
                {
                    throw ex;
                }
            });

            Assert.ThrowsAsync <Exception>(() => baseStandardTrace.TracedActionAsync(task));

            VerifyDispatcherRecordedAnnotation(new TagAnnotation("error", ex.Message));
        }
Example #5
0
        private static Trace CreateSampledTrace()
        {
            var trace = Trace.Create();

            trace.ForceSampled();
            return(trace);
        }
        public IEnumerable <WeatherForecast> Get()
        {
            var rng = new Random();

            var trace = Trace.Create();

            trace.Record(Annotations.ServerRecv());
            trace.Record(Annotations.ServiceName("WeatherForecast"));
            trace.Record(Annotations.Rpc("GET"));
            trace.Record(Annotations.Event("GET/ WeatherForecast"));
            Thread.Sleep(15);
            trace.Record(Annotations.Event("Waited for 15ms"));
            Thread.Sleep(20);
            trace.Record(Annotations.Event("Waited for 20ms"));
            trace.Record(Annotations.ServerSend());
            trace.Record(Annotations.Tag("http.url", "<url>"));

            var result = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date         = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary      = Summaries[rng.Next(Summaries.Length)]
            })
                         .ToArray();

            return(result);
        }
        /// <summary>
        /// 注册服务
        /// </summary>
        public static void RegisterService(Func <HttpContext, string> getRpc = null)
        {
            getRpc = getRpc ?? (c => c.Request.Method);
            var extractor = Propagations.B3String.Extractor <IHeaderDictionary>((carrier, key) => carrier[key]);

            var request      = ZipkinServiceHttpContext.Current.Request;
            var traceContext = extractor.Extract(request.Headers);

            var trace = traceContext == null?Trace.Create() : Trace.CreateFromId(traceContext);

            Trace.Current = trace;

            using (var serverTrace = new ServerTrace(ServiceName, getRpc(ZipkinServiceHttpContext.Current)))
            {
                if (request.Host.HasValue)
                {
                    trace.Record(Annotations.Tag("http.host", request.Host.ToString()));
                }
                trace.Record(Annotations.Tag("http.uri", UriHelper.GetDisplayUrl(request)));
                trace.Record(Annotations.Tag("http.path", request.Path));
                trace.Record(Annotations.Tag("Execute.Time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")));
                trace.Record(Annotations.Tag("Request.Body", JSONHelper.SerializeObject(request.Body)));
                serverTrace.AddAnnotation(Annotations.ServiceName(ServiceName));
            }
        }
Example #8
0
        public void TraceIdHighIsGeneratedIf128BitsActivated()
        {
            TraceManager.Trace128Bits = true;
            var trace = Trace.Create();

            Assert.AreNotEqual(SpanState.NoTraceIdHigh, trace.CurrentSpan.TraceIdHigh);
        }
        public TraceAs(string serviceName, string message, OperationType operationType, Dictionary <string, string> tags = null, bool hasInnerTrace = false)
        {
            try
            {
                _hasInnerTrace   = hasInnerTrace;
                zipkinAnnotation = ZipkinAnnotationFactory.GetAnnotationObject(operationType);

                trace = Trace.Current == null?Trace.Create() : Trace.Current.Child();

                trace.Record(Annotations.ServiceName(serviceName));
                trace.Record(zipkinAnnotation.AnnotationStart(message));
                trace.Record(Annotations.Rpc(message));
                if (tags != null)
                {
                    foreach (var key in tags.Keys)
                    {
                        trace.Record(Annotations.Tag(key, tags[key]));
                    }
                }

                if (hasInnerTrace)
                {
                    Trace.Current = trace;
                }
            }
            catch (Exception e)
            {
            }
        }
Example #10
0
        public void ContextIsPassedToCreatedThreads()
        {
            var trace = Trace.Create();

            TraceContext.Set(trace);

            Trace threadTrace  = null;
            Trace threadTrace2 = null;

            var thread = new Thread(() =>
            {
                threadTrace = TraceContext.Get();
            });

            thread.Start();

            TraceContext.Clear();

            var thread2 = new Thread(() =>
            {
                threadTrace2 = TraceContext.Get();
            });

            thread2.Start();

            thread.Join();
            thread2.Join();

            Assert.AreEqual(trace, threadTrace);
            Assert.IsNull(threadTrace2);
        }
Example #11
0
        public static void UseMyTracingMiddlewareOfAspNetCore(
            this MicropartOfCallChainAsZipkinBuilder micropartOfCallChainAsZipkinBuilder,
            IApplicationBuilder app)
        {
            var extractor = new ZipkinHttpTraceExtractor();

            app.Use(async(context, next) =>
            {
                var request           = context.Request;
                var httpRequestFilter = app.ApplicationServices.GetService <IMicroserviceFilterManager <HttpRequestFilter, HttpRequest> >();
                if (httpRequestFilter.ShouldBeFiltered(request))
                {
                    return;
                }

                if (!extractor.TryExtract(request.Headers, (c, key) => c[key], out var trace))
                {
                    trace = Trace.Create();
                }
                Trace.Current = trace;
                using (var serverTrace = new ServerTrace(AppInfoProvider.Service.Name, $"{request.Path}/{request.Method}"))
                {
                    trace.Record(Annotations.Tag("http.host", request.Host.ToString()));
                    trace.Record(Annotations.Tag("http.uri", UriHelper.GetDisplayUrl(request)));
                    trace.Record(Annotations.Tag("http.path", request.Path));
                    await serverTrace.TracedActionAsync(next());
                }
            });
        }
Example #12
0
        public void StatisticsAreUpdatedForSent()
        {
            var trace = Trace.Create();

            Record(trace, Annotations.ServerSend());

            _reporter.Verify(r => r.Report(It.IsAny <Span>()), Times.Once());
        }
Example #13
0
        /// <summary>
        ///
        /// <para>On_FromGatewayToService_Sent:</para>
        ///
        /// <para>Check <seealso cref="IBTracingServiceInterface.On_FromGatewayToService_Sent"/> for detailed documentation</para>
        ///
        /// </summary>
        public void On_FromGatewayToService_Sent(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            var TraceContext = TraceExtractor.Extract(_Context.Request.Headers);
            var CreatedTrace = TraceContext == null?Trace.Create() : Trace.CreateFromId(TraceContext).Child();

            CommonHttpTraceAnnotations(CreatedTrace, _Context);
            CreatedTrace.Record(Annotations.LocalOperationStop());
        }
Example #14
0
        /// <summary>
        ///
        /// <para>On_FromServiceToGateway_Received:</para>
        ///
        /// <para>Check <seealso cref="IBTracingServiceInterface.On_FromGatewayToService_Received"/> for detailed documentation</para>
        ///
        /// </summary>
        public void On_FromServiceToGateway_Received(HttpListenerContext _Context, Action <string> _ErrorMessageAction = null)
        {
            var TraceContext = TraceExtractor.Extract(_Context.Request.Headers);
            var CreatedTrace = TraceContext == null?Trace.Create() : Trace.CreateFromId(TraceContext).Child();

            CommonHttpTraceAnnotations(CreatedTrace, _Context);
            CreatedTrace.Record(Annotations.LocalOperationStart(ProgramUniqueID + "->" + _Context.Request.Url.AbsolutePath));
        }
Example #15
0
        public void StatisticsAreUpdatedForRecord()
        {
            var trace = Trace.Create();

            Record(trace, Annotations.ServerRecv());

            _statistics.Verify(s => s.UpdateRecordProcessed(), Times.Once());
        }
Example #16
0
        private static Trace ExtractTracing(Message message)
        {
            var extractor = Propagations.B3String.Extractor <IReadOnlyDictionary <string, byte[]> >((carrier, key) => carrier.TryGetValue(key, out var value) ? Encoding.UTF8.GetString(value) : null);

            var traceContext = extractor.Extract(message.Headers);

            return(traceContext == null?Trace.Create() : Trace.CreateFromId(traceContext));
        }
Example #17
0
        public void SpansAreLoggedAfterEndAnnotationServerSend()
        {
            var trace = Trace.Create();

            Record(trace, Annotations.ServerRecv());
            Record(trace, Annotations.ServerSend());

            _reporter.Verify(r => r.Report(It.IsAny <Span>()), Times.Once());
        }
Example #18
0
        public void EmittingToConsoleDoesNotThrow()
        {
            var span = new Span(Trace.Create().CurrentSpan, DateTime.Now);

            SpanEmitHub.Instance.RegisterDispatcher(new ConsoleDispatcher());
            SpanEmitHub.Instance.Emit(span);

            Thread.Sleep(1000);
        }
Example #19
0
        public void StatisticsAreUpdatedForSent()
        {
            var trace = Trace.Create();

            Record(trace, Annotations.ServerSend());

            _statistics.Verify(s => s.UpdateSpanSent(), Times.Once());
            _statistics.Verify(s => s.UpdateSpanSentBytes(It.IsAny <int>()), Times.Once());
        }
Example #20
0
        public void StatisticsAreUpdatedForRecord()
        {
            var statistics = new Mock <IStatistics>();
            var tracer     = new ZipkinTracer(Mock.Of <IZipkinSender>(), Mock.Of <ISpanSerializer>(), statistics.Object);
            var trace      = Trace.Create();

            Record(tracer, trace, Annotations.ServerRecv());

            statistics.Verify(s => s.UpdateRecordProcessed(), Times.Once());
        }
        public void WhenHasCurrentTraceNoErrThenRecordNoError()
        {
            tracer.Records.Clear();
            var mockContext = new Mock <AspectContext>();

            Trace.Current = Trace.Create();
            mockContext.SetupGet(i => i.ServiceMethod).Returns(typeof(DataAccessZipkinTrace).GetMethods().First());
            sut.Record(DateTime.Now, DateTime.Now, mockContext.Object, null);
            CheckDataAccessRecords();
        }
Example #22
0
        public void ContextCanBeSetThenGetAndCleared()
        {
            var trace = Trace.Create();

            TraceContext.Set(trace);
            Assert.AreEqual(trace, TraceContext.Get());

            TraceContext.Clear();
            Assert.IsNull(TraceContext.Get());
        }
Example #23
0
        public void SetOverridesPreviousTrace()
        {
            var firstTrace  = Trace.Create();
            var secondTrace = Trace.Create();

            TraceContext.Set(firstTrace);
            TraceContext.Set(secondTrace);

            Assert.AreEqual(secondTrace, TraceContext.Get());
        }
Example #24
0
        private static Span CreateLocalSpan()
        {
            var trace = Trace.Create();

            trace.Record(Annotations.LocalOperationStart("JDBCSpanStore"));
            trace.Record(Annotations.ServiceName("get-traces"));
            trace.Record(Annotations.Tag("request", "QueryRequest{serviceName=zipkin-server, spanName=null, annotations=[], binaryAnnotations={}, minDuration=null, maxDuration=null, endTs=1461750033209, lookback=604800000, limit=10}"));
            trace.Record(Annotations.LocalOperationStop());
            return(new Span(trace.CurrentSpan, new DateTime()));
        }
Example #25
0
        public void SpansAreLoggedAfterEndAnnotationServerSend()
        {
            var trace = Trace.Create();

            Record(trace, Annotations.ServerRecv());
            Record(trace, Annotations.ServerSend());

            _spanSerializer.Verify(s => s.SerializeTo(It.IsAny <Stream>(), It.IsAny <Span>()), Times.Once());
            _spanSender.Verify(sender => sender.Send(It.IsAny <byte[]>()), Times.Once());
        }
Example #26
0
        public static Trace ExtractIncomingTrace(IncomingWebRequestContext incomingRequest)
        {
            Trace trace;
            ZipkinHttpTraceExtractor zkExtractor = new ZipkinHttpTraceExtractor();

            if (!zkExtractor.TryExtract(incomingRequest.Headers, out trace))
            {
                trace = Trace.Create();
            }
            return(trace);
        }
 private void SetUpTracing()
 {
     trace         = Trace.Create();
     Trace.Current = trace;
     using (var serverTrace = new ServerTrace(serviceName, "TraceRestClient"))
     {
         trace.Record(Annotations.Tag("http.host", "http.url"));
         trace.Record(Annotations.Tag("http.url", "http.url"));
         trace.Record(Annotations.Tag("http.path", "http.url"));
     }
 }
        public void WhenHasCurrentTraceHasErrNotCommandThenRecordHasError()
        {
            tracer.Records.Clear();
            var mockContext = new Mock <AspectContext>();

            Trace.Current = Trace.Create();
            mockContext.SetupGet(i => i.ServiceMethod).Returns(typeof(DataAccessZipkinTrace).GetMethods().First());
            sut.Record(DateTime.Now, DateTime.Now, mockContext.Object, new Exception("test"));
            CheckDataAccessRecords();
            CheckError("System.Exception: test");
        }
Example #29
0
        public void ShouldCallChildWhenCurrentTraceNotNull()
        {
            var trace = Trace.Create();

            Trace.Current = trace;
            using (var client = new ClientTrace(serviceName, rpc))
            {
                Assert.AreEqual(trace.CurrentSpan.SpanId, client.Trace.CurrentSpan.ParentSpanId);
                Assert.AreEqual(trace.CurrentSpan.TraceId, client.Trace.CurrentSpan.TraceId);
            }
        }
Example #30
0
        private static Span CreateServerSpan()
        {
            var trace = Trace.Create();

            trace.Record(Annotations.ServerRecv());
            trace.Record(Annotations.Rpc("post"));
            trace.Record(Annotations.ServiceName("zipkin-server"));
            trace.Record(Annotations.Tag("srv/finagle.version", "6.34.0"));
            trace.Record(Annotations.Tag("http.path", "/api"));
            trace.Record(Annotations.ServerSend());
            return(new Span(trace.CurrentSpan, new DateTime()));
        }