Search code examples
node.jsexpressgoogle-cloud-platformgoogle-cloud-stackdrivergoogle-cloud-trace

Google Cloud trace Custom trace only works a few times


I have activated Google Cloud Tracer with nodejs & express, works well in automatic mode, registers calls to the api correctly.

I try to create a trace manually, to know the execution time of intermediate steps.

controller (req, res) {

    tracer.runInRootSpan({ name: 'dnd-task' }, (rootSpan) => {

      //promise
      myPromise(rootSpan)
        .then((data) => {
          rootSpan.endSpan()
          res.ok(data)
        })
        .catch((err)=>{
          rootSpan.endSpan()
          res.send(err)
        })
    })

}

but Google Cloud Trace only lists 1 or 2 calls, while automatically generated calls show thousands of API calls.

I also read the documentation to try to get the context of express.js middleware, but I didn't find a way to get the context.

from: google-cloud-trace

a root span is automatically started whenever an incoming request is received (in other words, all middleware already runs within a root span).

Update base on @kjin comment:

inside a controller in express you only need

tracer.createChildSpan({name: 'name'})


Solution

  • If you have automatic tracing enabled and also generate root spans within a request listener using the custom span API, then the root span will be ignored because it was created within a pre-existing root span (the one that was automatically started for this request). This is my guess based on the code presented here, but you should be able to accomplish what you want by instead creating a child span. (Custom root spans are meant for work that occur outside of a request's lifecycle -- such as periodic work.)

    Re: Express.js middleware context -- I am not exactly sure what you mean here, but the Trace Agent doesn't store any of the request listener arguments in the trace context.

    As an additional note -- you'll get a quicker response time if you report an issue directly to the GitHub repository to which you linked.

    Hope this helps!