DEV Community

Marjori Pomarole
Marjori Pomarole

Posted on

Enabling OpenCensus Tracing with Django and Google Cloud Run

Make sure the service worker you have set up on your Cloud Run service has IAM roles cloudtrace.agent. if you are using terraform, it will be set up as such:

resource "google_project_iam_binding" "service_permissions" {
  for_each = toset([
    "logging.logWriter",
    "cloudsql.client",
    "clouddebugger.agent",
    "cloudtrace.agent"
  ])

  role       = "roles/${each.key}"
  ...
}
Enter fullscreen mode Exit fullscreen mode

Screen Shot 2021-09-09 at 18.21.06

Install the required pip packages from OpenCensus and google-cloud-trace. Which is the new hotness that merged OpenTracing and OpenMetrics into one beautiful package. I have added these to my requirements.txt file.

...
opencensus-ext-django==0.7.5
opencensus-ext-stackdriver==0.8.0
opencensus==0.7.13
...
Enter fullscreen mode Exit fullscreen mode

Then pip install -r requirements.txt

Now we simply have to configure django settings to include the opencensus middleware and tell the package to export it in StackDriver (now Google Cloud Operations/Monitoring) format.

On my core settings file /core/settings/base.py, we have:

MIDDLEWARE = [
    ...
    'opencensus.ext.django.middleware.OpencensusMiddleware',
]

OPENCENSUS = {
    'TRACE': {
        'EXPORTER': 'opencensus.ext.stackdriver.trace_exporter.StackdriverExporter()',
        'PROPAGATOR': 'opencensus.trace.propagation.google_cloud_format.GoogleCloudFormatPropagator()',
    }
}
Enter fullscreen mode Exit fullscreen mode

And let's build the new image with gcloud builds submit or by using a Cloud Trigger. And we are done! Now you can check the Google Trace console to see your traces in action.

Screen Shot 2021-09-09 at 22.28.43

Top comments (0)