Enabling OpenCensus Tracing with Django and Google Cloud Run

marjoripomarole

Marjori Pomarole

Posted on September 9, 2021

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

💖 💪 🙅 🚩
marjoripomarole
Marjori Pomarole

Posted on September 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024