Setting up StackDriver logging for Django on GCP

Ertan Dogrultan
Google Cloud - Community
1 min readMar 20, 2018

There is some official documentation out there on this topic, but I didn’t find it particularly clear, so I decided to share my setup.

The production.py should roughly look like this:

from google.cloud import logging# StackDriver setup
client = logging.Client()
# Connects the logger to the root logging handler; by default
# this captures all logs at INFO level and higher
client.setup_logging()
LOGGING = {
'handlers': {
'stackdriver': {
'class': 'google.cloud.logging.handlers.CloudLoggingHandler',
'client': client
}
},
'loggers': {
'': {
'handlers': ['stackdriver'],
'level': 'INFO'
}
},
}

Lastly, make sure that your service account has Logs Writer role (roles/logging.logWriter). Otherwise, you’ll get 403 errors.

You will see your structured logs here.

Update:

If you have multiple environments that are running on GCP such as staging, prod etc, and you want to separate these logs you can use the name field in the configuration.

from google.cloud import logging# StackDriver setup
client = logging.Client()
# Connects the logger to the root logging handler; by default
# this captures all logs at INFO level and higher
client.setup_logging()
LOGGING = {
'handlers': {
'stackdriver': {
'class': 'google.cloud.logging.handlers.CloudLoggingHandler',
'client': client
}
},
'loggers': {
'': {
'handlers': ['stackdriver'],
'level': 'INFO',
'name': os.getenv('ENVIRONMENT_NAME')
}
},
}

After adding the name parameter, you can use logName="projects/<project_id>/logs/<name>" constraint on StackDriver logging interface to filter by name. You can also find these name options in the dropdown filter in the UI.

--

--