Enabling OpenCensus Tracing with Django and Google Cloud Run
Marjori Pomarole
Posted on September 9, 2021
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}"
...
}
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
...
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()',
}
}
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.
Posted on September 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.