コード例 #1
0
        public async Task TraceSingleAsync(Func <IHostBuilder> createHostBuilder)
        {
            IHost host = null;

            try
            {
                host = createHostBuilder().Build();
                await host.StartAsync();

                ITraceContext  traceContext  = new SimpleTraceContext(null, null, true);
                var            tracerFactory = host.Services.GetRequiredService <Func <ITraceContext, IManagedTracer> >();
                IManagedTracer tracer        = tracerFactory(traceContext);
                ContextTracerManager.SetCurrentTracer(tracer);

                using (tracer.StartSpan(_testId))
                {
                    IManagedTracer currentTracer = host.Services.GetRequiredService <IManagedTracer>();
                    currentTracer.RunInSpan(
                        () => Console.WriteLine("Using Cloud Trace from a non ASP.NET Core app"),
                        "testing_tracing");
                }

                var trace = TraceEntryPolling.Default.GetTrace(_testId, _startTime);
                TraceEntryVerifiers.AssertParentChildSpan(trace, _testId, "testing_tracing");
            }
            finally
            {
                if (host is object)
                {
                    await host.StopAsync();
                }
            }
        }
コード例 #2
0
            // End sample

            // Sample: UseTracerRunIn
            /// <summary>
            /// The <see cref="IManagedTracer"/> is populated by dependency injection.
            /// </summary>
            public void TraceHelloWorldRunIn(IManagedTracer tracer)
            {
                // Manually trace a specific Action or Func<T>.
                tracer.RunInSpan(
                    () => Console.Out.WriteLine("Hello, World!"),
                    nameof(TraceHelloWorldRunIn));
            }
コード例 #3
0
 public StorageController(IStorageLogic storageLogic,
                          IManagedTracer tracer, ILogger <StorageController> logger)
 {
     _storageLogic = storageLogic ?? throw new ArgumentNullException(nameof(storageLogic));
     _tracer       = tracer ?? throw new ArgumentNullException(nameof(tracer));
     _logger       = logger ?? throw new ArgumentNullException(nameof(logger));
 }
コード例 #4
0
        /// <summary>
        /// Invokes the next <see cref="RequestDelegate"/> and trace the time
        /// taken for the next delegate to run, reporting the results to the
        /// Stackdriver Trace API.
        /// </summary>
        public async Task Invoke(HttpContext httpContext, IManagedTracer tracer)
        {
            GaxPreconditions.CheckNotNull(tracer, nameof(tracer));

            if (tracer.GetCurrentTraceId() == null)
            {
                await _next(httpContext);
            }
            else
            {
                // Trace the delegate and annotate it with information from the current
                // http context.
                tracer.StartSpan(httpContext.Request.Path);
                try
                {
                    await _next(httpContext);
                }
                catch (Exception e)
                {
                    StackTrace stackTrace = new StackTrace(e, true);
                    tracer.SetStackTrace(stackTrace);
                    throw;
                }
                finally
                {
                    tracer.AnnotateSpan(Labels.AgentLabel);
                    tracer.AnnotateSpan(Labels.FromHttpContext(httpContext));
                    tracer.EndSpan();
                }
            }
        }
コード例 #5
0
            // End sample

            // Sample: UseTracer
            /// <summary>
            /// The <see cref="IManagedTracer"/> is populated by dependency injection.
            /// </summary>
            public void TraceHelloWorld(IManagedTracer tracer)
            {
                // Manually trace a specific operation.
                tracer.StartSpan(nameof(TraceHelloWorld));
                Console.Out.WriteLine("Hello, World!");
                tracer.EndSpan();
            }
コード例 #6
0
 /// <summary>
 /// Consructor for Conversation controller.
 /// </summary>
 /// <param name="exceptionLogger">Exception logger</param>
 /// <param name="logger">Regular logger</param>
 /// <param name="tracer">Tracer</param>
 public ConversationController(
     IExceptionLogger exceptionLogger,
     ILogger <ConversationController> logger,
     IManagedTracer tracer)
 {
     _dialogFlowApp = new DialogflowApp(exceptionLogger, logger, tracer);
 }
コード例 #7
0
        private void BeginRequest(object sender, EventArgs e)
        {
            TraceHeaderContext headerContext = TraceHeaderContext.FromRequest(HttpContext.Current.Request);
            TraceOptions       headerOptions = _headerFactory.CreateOptions(headerContext);

            // If the trace header says to trace or if the rate limiter allows tracing continue.
            if (!headerOptions.ShouldTrace)
            {
                TraceOptions options = _rateFactory.CreateOptions();
                if (!options.ShouldTrace)
                {
                    return;
                }
            }

            // Create and set the tracer for the request.
            TraceProto trace = new TraceProto
            {
                ProjectId = _projectId,
                TraceId   = headerContext.TraceId ?? _traceIdfactory.NextId(),
            };
            IManagedTracer tracer = SimpleManagedTracer.Create(_consumer, trace, headerContext.SpanId);

            TracerManager.SetCurrentTracer(tracer);

            // Start the span and annotate it with information from the current request.
            tracer.StartSpan(HttpContext.Current.Request.Path);
            tracer.AnnotateSpan(Labels.FromHttpRequest(HttpContext.Current.Request));
        }
コード例 #8
0
        public async Task RunInSpanAsync_CorrectSpan()
        {
            const string traceId        = "trace-id";
            const string projectId      = "project-id";
            const string traceName      = "trace-name";
            const int    delayInSeconds = 1;

            TraceProto actualTraceProto = null;

            Mock <IConsumer <TraceProto> > mockConsumer = new Mock <IConsumer <TraceProto> >();

            mockConsumer.Setup(x => x.Receive(It.IsAny <IEnumerable <TraceProto> >()))
            .Callback <IEnumerable <TraceProto> >(arg => actualTraceProto = arg?.FirstOrDefault());

            IManagedTracer simpleTracer     = SimpleManagedTracer.Create(mockConsumer.Object, projectId, traceId);
            IManagedTracer delegatingTracer = new DelegatingTracer(() => simpleTracer);

            var stopwatch = Stopwatch.StartNew();
            await delegatingTracer.RunInSpanAsync(async() =>
            {
                await Task.Delay(TimeSpan.FromSeconds(delayInSeconds));
                return(0);
            }, traceName);

            stopwatch.Stop();

            Assert.NotNull(actualTraceProto);
            Assert.InRange(SpanInSeconds(actualTraceProto), delayInSeconds, stopwatch.Elapsed.Seconds);
        }
コード例 #9
0
        public PropagationController([FromServices] IManagedTracer tracer, [FromServices] IServiceProvider serviceProvider)
        {
            _tracer = tracer;
            var propagatingHandlerFactory = serviceProvider.GetRequiredService <OutgoingGoogleTraceHandlerFactory>();

            _propagatingHandler = propagatingHandlerFactory.Create(serviceProvider, labelsProvider: null);
        }
コード例 #10
0
 /// <summary>
 /// Sets the current <see cref="IManagedTracer"/>.  This is called in <see cref="CloudTraceMiddleware"/>
 /// for each new request.
 /// </summary>
 public static void SetCurrentTracer(IHttpContextAccessor accessor, IManagedTracer tracer)
 {
     if (accessor?.HttpContext?.Items != null)
     {
         accessor.HttpContext.Items[TraceKey] = tracer;
     }
 }
コード例 #11
0
 public IActionResult About([FromServices] IManagedTracer tracer)
 {
     tracer.StartSpan(nameof(About));
     ViewData["Message"] = "Your application description page.";
     tracer.EndSpan();
     return(View());
 }
コード例 #12
0
 public TagsController(ILogger <TagsController> logger, ITagBL tagBL, ITagManager tagManager,
                       IManagedTracer managedTracer)
 {
     _logger        = logger;
     _tagBL         = tagBL;
     _tagManager    = tagManager;
     _managedTracer = managedTracer;
 }
コード例 #13
0
        public void CreateTracer_SimpleManagedTracer()
        {
            IManagedTracer tracer = s_tracerFactoryNoLimit.CreateTracer(s_headerTrue);

            Assert.IsType(typeof(SimpleManagedTracer), tracer);
            Assert.Equal(tracer.GetCurrentTraceId(), TraceId);
            Assert.Equal(tracer.GetCurrentSpanId(), SpanId);
        }
コード例 #14
0
 public ActionResult Hello([FromServices] IManagedTracer tracer)
 {
     using (tracer.StartSpan(nameof(Hello)))
     {
         ViewData["text"] = "Hello, World!";
         return(View());
     }
 }
コード例 #15
0
        public TraceHeaderPropagatingHandlerTest()
        {
            _testId = IdGenerator.FromDateTime();

            _consumer = new GrpcTraceConsumer(TraceServiceClient.Create());
            _tracer   = SimpleManagedTracer.Create(_consumer, TestEnvironment.GetTestProjectId(), _traceIdFactory.NextId(), null);

            _startTime = DateTimeOffset.UtcNow;
        }
コード例 #16
0
        /// <summary>Traces a 10ms sleep.</summary>
        public string Trace(string id, [FromServices] IManagedTracer tracer)
        {
            string message = GetMessage(nameof(Trace), id);

            tracer.StartSpan(message);
            Thread.Sleep(10);
            tracer.EndSpan();
            return(message);
        }
コード例 #17
0
 /// <summary>
 /// Manually trace a set of operations.
 /// The <see cref="IManagedTracer"/> is populated by dependency injection
 /// thanks to the use of the <see cref="FromServicesAttribute"/> attribute.
 /// </summary>
 public void TraceHelloWorld(string id, [FromServices] IManagedTracer tracer)
 {
     // Change the name of the span to what makese sense in your context.
     using (tracer.StartSpan(id))
     {
         // The code whose execution is to be included in the span goes here.
         ViewData["Message"] = "Hello World.";
     }
 }
コード例 #18
0
            // End sample

            // Sample: TraceOutgoing
            public async Task <HttpResponseMessage> TraceOutgoing(IManagedTracer tracer)
            {
                // Add a handler to trace outgoing requests and to propagate the trace header.
                var traceHeaderHandler = TraceHeaderPropagatingHandler.Create(tracer);

                using (var httpClient = new HttpClient(traceHeaderHandler))
                {
                    return(await httpClient.GetAsync("https://weather.com/"));
                }
            }
コード例 #19
0
        /// <summary>Traces a 10ms sleep.</summary>
        public string Trace(string id, [FromServices] IManagedTracer tracer)
        {
            string message = EntryData.GetMessage(nameof(Trace), id);

            using (tracer.StartSpan(message))
            {
                Thread.Sleep(10);
            }
            return(message);
        }
コード例 #20
0
        public string Health([FromServices] IManagedTracer tracer)
        {
            string message = "/_ah/health";

            using (tracer.StartSpan(message))
            {
                Thread.Sleep(10);
            }
            return(message);
        }
コード例 #21
0
        /// <summary>Traces a 10ms sleep and throws an exception.</summary>
        public string ThrowException(string id, [FromServices] IManagedTracer tracer)
        {
            // Add a span with the test id to allow for the trace to be found.
            string message = GetMessage(nameof(ThrowException), id);

            tracer.StartSpan(message);
            Thread.Sleep(10);
            tracer.EndSpan();
            throw new DivideByZeroException();
        }
コード例 #22
0
 // This incoming HTTP request should be captured by Trace.
 public IActionResult Index([FromServices] IManagedTracer tracer)
 {
     using (tracer.StartSpan(nameof(Index)))
     {
         var traceHeaderHandler = new TraceHeaderPropagatingHandler(() => tracer);
         var response           = TraceOutgoing(traceHeaderHandler);
         ViewData["text"] = response.Result.ToString();
         return(View());
     }
 }
コード例 #23
0
        public async Task <string> TraceOutgoing(string id, [FromServices] IManagedTracer tracer, [FromServices] TraceHeaderPropagatingHandler propagatingHandler)
        {
            string message = EntryData.GetMessage(nameof(TraceOutgoing), id);

            using (tracer.StartSpan(message))
                using (var httpClient = new HttpClient(propagatingHandler))
                {
                    await httpClient.GetAsync("https://google.com/");
                }
            return(message);
        }
コード例 #24
0
        public async Task <string> TraceOutgoingClientFactory(string id, [FromServices] IManagedTracer tracer, [FromServices] IHttpClientFactory httpClientFactory)
        {
            string message = EntryData.GetMessage(nameof(TraceOutgoingClientFactory), id);

            using (tracer.StartSpan(message))
            {
                var httpClient = httpClientFactory.CreateClient("google");
                await httpClient.GetAsync("");
            }
            return(message);
        }
コード例 #25
0
 public DatastoreCounterSingleton(DatastoreDb datastore,
                                  IOptions <DatastoreCounterOptions> options,
                                  ILogger <DatastoreCounter> logger, IManagedTracer tracer)
 {
     _datastore       = datastore;
     _options         = options;
     _logger          = logger;
     _tracer          = tracer;
     _counter         = new DatastoreCounter(datastore, options, logger, tracer);
     _counterBirthday = DateTime.UtcNow;
 }
コード例 #26
0
        /// <summary>Traces a 10ms sleep and adds a stacktrace.</summary>
        public string TraceStackTrace(string id, [FromServices] IManagedTracer tracer)
        {
            string message = GetMessage(nameof(TraceStackTrace), id);

            using (tracer.StartSpan(message))
            {
                Thread.Sleep(10);
                tracer.SetStackTrace(CreateStackTrace());
            }
            return(message);
        }
コード例 #27
0
        // End sample

        // Sample: UseTracerRunIn
        /// <summary>
        /// Manually trace a specific Action or Func<T>.
        /// The <see cref="IManagedTracer"/> is populated by dependency injection
        /// thanks to the use of the <see cref="FromServicesAttribute"/> attribute.
        /// </summary>
        public void TraceHelloWorldRunIn(string id, [FromServices] IManagedTracer tracer)
        {
            tracer.RunInSpan(
                // The Action or Func<T> to be traced.
                () =>
            {
                // The code whose execution is to be included in the span goes here.
                ViewData["Message"] = "Hello World.";
            },
                // The name of the span.
                id);
        }
コード例 #28
0
        private void EndRequest(object sender, EventArgs e)
        {
            IManagedTracer tracer = Tracer;

            if (tracer.GetCurrentTraceId() == null)
            {
                return;
            }
            // End the span and annotate it with information from the current response.
            tracer.AnnotateSpan(Labels.FromHttpResponse(HttpContext.Current.Response));
            tracer.EndSpan();
        }
コード例 #29
0
        /// <summary>Traces a 10ms sleep and adds an annotation.</summary>
        public string TraceLabels(string id, [FromServices] IManagedTracer tracer)
        {
            string message = GetMessage(nameof(TraceLabels), id);

            tracer.StartSpan(message);
            Thread.Sleep(10);
            tracer.AnnotateSpan(new Dictionary <string, string> {
                { Label, LabelValue }
            });
            tracer.EndSpan();
            return(message);
        }
コード例 #30
0
        /// <summary>Traces a 10ms sleep and adds an annotation.</summary>
        public string TraceLabels(string id, [FromServices] IManagedTracer tracer)
        {
            string message = EntryData.GetMessage(nameof(TraceLabels), id);

            using (tracer.StartSpan(message))
            {
                Thread.Sleep(10);
                tracer.AnnotateSpan(new Dictionary <string, string> {
                    { TraceEntryData.TraceLabel, TraceEntryData.TraceLabelValue }
                });
                return(message);
            }
        }