python-3.xstackdrivergoogle-cloud-stackdriveropencensus

Opencensus Stackdriver traces from Python app not appearing in the Trace list in GCP


I'm comparing different tracing backend using OpenCensus. I already have the simple OpenCensus.io python samples running fine using Zipkin and Azure Monitor.

Now I'm trying to test using GCP's Stackdriver...

I have set up the test code from Opencensus https://opencensus.io/exporters/supported-exporters/python/stackdriver/ as follows:

#!/usr/bin/env python

import os

from opencensus.common.transports.async_ import AsyncTransport
from opencensus.ext.stackdriver.trace_exporter import StackdriverExporter
from opencensus.trace.tracer import Tracer

def main():
    sde = StackdriverExporter(
        project_id=os.environ.get("GCP_PROJECT_ID"),
        transport=AsyncTransport)

    tracer = Tracer(exporter=sde)
    with tracer.span(name="doingWork") as span:
        for i in range(10):
            pass

if __name__ == "__main__":
    main()

I have set the environment variable for GCP_PROJECT_ID and also have my key file path for my service account JSON file set in GOOGLE_APPLICATION_CREDENTIALS.

The service account has the "Cloud trace agent" role.

My code runs through with no errors but I can't see any info appearing in the GCP console under traces or in the monitoring dashboard.

Am I missing something?

Environment notes: I'm testing this from my local Windows machine using Python 3.7.2


Solution

  • One thing which is not very clear in the doc is that by default, traces are sampled (see source file here), so every call is properly logged, but only 1e-4 trace is stored. It helps to reduce costs but it is a major pain point during debug.

    If you want to log all traces, you can use AlwaysOnSampler and pass it to the tracer :

    import os
    
    from opencensus.common.transports.async_ import AsyncTransport
    from opencensus.ext.stackdriver.trace_exporter import StackdriverExporter
    from opencensus.trace.tracer import Tracer
    from opencensus.trace.samplers import AlwaysOnSampler
    
    def main():
        sde = StackdriverExporter(
            project_id=os.environ.get("GCP_PROJECT_ID"),
            transport=AsyncTransport)
    
        tracer = Tracer(exporter=sde, sampler=AlwaysOnSampler())
        with tracer.span(name="doingWork") as span:
            for i in range(10):
                pass
    
    if __name__ == "__main__":
        main()
    

    Hope it fixes your issue !