If you are new to Datadog serverless monitoring, launch the Datadog CLI in interactive mode to guide your first installation for a quick start.
datadog-ci cloud-run instrument -i
To set up the Datadog sidecar for your applications, run the instrument command after your normal deployment. You can specify multiple services to instrument by passing multiple --service flags.
If you don’t already have Terraform set up, install Terraform, create a new directory, and make a file called main.tf.
Then, add the following to your Terraform configuration, updating it as necessary based on your needs:
variable"datadog_api_key"{description="Your Datadog API key"type=stringsensitive=true}module"my-cloud-run-app"{source="DataDog/cloud-run-datadog/google"version="~> 1.0"project="my-gcp-project"name="my-cloud-run-app"location="us-central1"datadog_api_key=var.datadog_api_keydatadog_service="test-service" // your application service
datadog_version="0.0.0" // your code version
datadog_env="prod" // your application environment
datadog_enable_logging=truedeletion_protection=falsetemplate={containers=[{name="main"image="us-docker.pkg.dev/cloudrun/container/hello"resources={limits={cpu="1"memory="512Mi"}}ports={container_port=8080}env=[{ name="DD_TRACE_ENABLED", value="true"},]},]}}
See the Environment Variables for more information on the configuration options available through the env.
Ensure the container port for the main container is the same as the one exposed in your Dockerfile/service.
If you haven’t already, initialize your Terraform project:
terraform init
To deploy your app, run:
terraform apply
Create a YAML file that contains your configuration. You can use the following example and adapt it to your needs:
apiVersion:serving.knative.dev/v1kind:Servicemetadata:name:'<SERVICE_NAME>'labels:cloud.googleapis.com/location:'<LOCATION>'service:'<SERVICE_NAME>'spec:template:metadata:labels:service:'<SERVICE_NAME>'annotations:# The maximum number of instances that can be created for this service.# https://cloud.google.com/run/docs/reference/rest/v1/RevisionTemplateautoscaling.knative.dev/maxScale:'100'# The startup CPU boost feature for revisions provides additional CPU during# instance startup time and for 10 seconds after the instance has started.# https://cloud.google.com/run/docs/configuring/services/cpu#startup-boostrun.googleapis.com/startup-cpu-boost:'true'spec:containers:- env:- name:DD_SERVICEvalue:'<SERVICE_NAME>'- name:DD_LOGS_INJECTIONvalue:'true'image:'<CONTAINER_IMAGE>'name:run-sidecar-1ports:- containerPort:8080name:http1resources:limits:cpu:1000mmemory:512MistartupProbe:failureThreshold:1periodSeconds:240tcpSocket:port:8080timeoutSeconds:240volumeMounts:- mountPath:/shared-volumename:shared-volume- env:- name:DD_SERVERLESS_LOG_PATHvalue:shared-volume/logs/*.log- name:DD_SITEvalue:'<DATADOG_SITE>'- name:DD_ENVvalue:'<ENV>'- name:DD_API_KEYvalue:'<API_KEY>'- name:DD_SERVICEvalue:'<SERVICE_NAME>'- name:DD_VERSIONvalue:'<VERSION>'- name:DD_LOG_LEVELvalue:debug- name:DD_SOURCEvalue:'python'- name:DD_HEALTH_PORTvalue:'12345'image:gcr.io/datadoghq/serverless-init:<YOUR_TAG>name:serverless-init-1resources:limits:cpu:1000mmemory:512MistartupProbe:failureThreshold:3periodSeconds:10tcpSocket:port:12345timeoutSeconds:1volumeMounts:- mountPath:/shared-volumename:shared-volumevolumes:- emptyDir:medium:MemorysizeLimit:512Miname:shared-volumetraffic:- latestRevision:truepercent:100
This example uses the latest version of serverless-init. See the latest releases on Docker Hub to pin a specific version.
In this example, the environment variables, startup health check, and volume mount are already added. If you don’t want to enable logs, remove the shared volume.
Ensure the container port for the main container is the same as the one exposed in your Dockerfile/service.
To deploy your container, run:
gcloud run services replace <FILENAME>.yaml
After deploying your Cloud Run app, you can manually modify your app’s settings to enable Datadog monitoring.
Create a Volume with In-Memory volume type.
Add a new container with image URL: gcr.io/datadoghq/serverless-init:<YOUR_TAG>. See the latest releases on Docker Hub to pin a specific version.
Add the volume mount to every container in your application. Choose a path such as /shared-volume, and remember it for the next step.
Add the following environment variables to your serverless-init sidecar container:
DD_SERVICE: A name for your service. For example, gcr-sidecar-test.
DD_ENV: A name for your environment. For example, dev.
DD_SERVERLESS_LOG_PATH: Your log path. For example, /shared-volume/logs/*.log. The path must begin with the mount path you defined in the previous step.
For a list of all environment variables, including additional tags, see Environment variables.
Configurez les logs.
À l’étape précédente, vous avez créé un volume partagé. Vous avez peut-être également défini la variable d’environnement DD_SERVERLESS_LOG_PATH, dont la valeur par défaut est /shared-volume/logs/app.log.
À cette étape, configurez votre bibliothèque de journalisation pour écrire les logs dans le fichier défini dans DD_SERVERLESS_LOG_PATH. Vous pouvez également définir un format personnalisé pour la corrélation log/trace et d’autres fonctionnalités. Datadog recommande de définir les variables d’environnement suivantes :
ENV PYTHONUNBUFFERED=1 : Dans votre conteneur principal. Assurez-vous que les sorties Python apparaissent immédiatement dans les logs du conteneur au lieu d’être mises en mémoire tampon.
ENV DD_LOGS_INJECTION=true : Dans votre conteneur principal. Activez la corrélation log/trace pour les loggers pris en charge.
DD_SOURCE=python : Dans votre conteneur sidecar. Activez le parsing avancé des logs Datadog.
Ensuite, mettez à jour votre bibliothèque de journalisation. Par exemple, vous pouvez utiliser la bibliothèque native logging de Python :
Set the log source to enable a Log Pipeline for advanced parsing. To automatically apply language-specific parsing rules, set to python, or use your custom pipeline. Defaults to cloudrun.
Sidecar container
DD_TAGS
Add custom tags to your logs, metrics, and traces. Tags should be comma separated in key/value format (for example: key1:value1,key2:value2).
Sidecar container
Do not set the following environment variables in your serverless environment. They should only be set in non-serverless environments.
DD_AGENT_HOST
DD_TRACE_AGENT_URL
Traçage distribué avec Pub/Sub
Définissez DD_TRACE_INFERRED_PROXY_SERVICES_ENABLED=true dans le conteneur d’application. Cela crée un span gcp.pubsub.receive inféré pour la requête push.
Le tracing des abonnements push Google Cloud Pub/Sub nécessite la version 4.8.0 ou ultérieure de ddtrace.
To get end-to-end distributed traces between Pub/Sub producers and Cloud Run, configure your push subscriptions with the --push-no-wrapper and --push-no-wrapper-write-metadata flags. This moves message attributes from the JSON body to HTTP headers, allowing Datadog to extract producer trace context and create span links.
Eventarc Pub/Sub triggers use push subscriptions as the underlying delivery mechanism. When you create an Eventarc trigger, GCP automatically creates a managed push subscription. However, Eventarc does not expose --push-no-wrapper-write-metadata as a trigger creation parameter, so you must manually update the auto-created subscription.
This integration depends on your runtime having a full SSL implementation. If you are using a slim image, you may need to add the following command to your Dockerfile to include certificates:
RUN apt-get update && apt-get install -y ca-certificates
To have your Cloud Run services appear in the software catalog, you must set the DD_SERVICE, DD_VERSION, and DD_ENV environment variables.
Pour aller plus loin
Documentation, liens et articles supplémentaires utiles: