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(); } } }
// 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)); }
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)); }
/// <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(); } } }
// 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(); }
/// <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); }
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)); }
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); }
public PropagationController([FromServices] IManagedTracer tracer, [FromServices] IServiceProvider serviceProvider) { _tracer = tracer; var propagatingHandlerFactory = serviceProvider.GetRequiredService <OutgoingGoogleTraceHandlerFactory>(); _propagatingHandler = propagatingHandlerFactory.Create(serviceProvider, labelsProvider: null); }
/// <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; } }
public IActionResult About([FromServices] IManagedTracer tracer) { tracer.StartSpan(nameof(About)); ViewData["Message"] = "Your application description page."; tracer.EndSpan(); return(View()); }
public TagsController(ILogger <TagsController> logger, ITagBL tagBL, ITagManager tagManager, IManagedTracer managedTracer) { _logger = logger; _tagBL = tagBL; _tagManager = tagManager; _managedTracer = managedTracer; }
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); }
public ActionResult Hello([FromServices] IManagedTracer tracer) { using (tracer.StartSpan(nameof(Hello))) { ViewData["text"] = "Hello, World!"; return(View()); } }
public TraceHeaderPropagatingHandlerTest() { _testId = IdGenerator.FromDateTime(); _consumer = new GrpcTraceConsumer(TraceServiceClient.Create()); _tracer = SimpleManagedTracer.Create(_consumer, TestEnvironment.GetTestProjectId(), _traceIdFactory.NextId(), null); _startTime = DateTimeOffset.UtcNow; }
/// <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); }
/// <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."; } }
// 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/")); } }
/// <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); }
public string Health([FromServices] IManagedTracer tracer) { string message = "/_ah/health"; using (tracer.StartSpan(message)) { Thread.Sleep(10); } return(message); }
/// <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(); }
// 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()); } }
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); }
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); }
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; }
/// <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); }
// 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); }
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(); }
/// <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); }
/// <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); } }