セットアップ

サンプルアプリケーションは GitHub で入手可能です。
  1. Datadog Python SDK をインストールします。

    requirements.txt または pyproject.toml に ddtrace を追加します。最新バージョンは、PyPI から入手できます。

    requirements.txt

    ddtrace==<VERSION>

    または、Dockerfile に SDK をインストールできます。

    Dockerfile

    RUN pip install ddtrace

    次に、開始コマンドを ddtrace-run でラップします。

    Dockerfile

    CMD ["ddtrace-run", "python", "app.py"]

    詳細については、Python アプリケーションのトレース を参照してください。

  2. serverless-init をインストールします。

    Datadog publishes new releases of the serverless-init container image to Google’s gcr.io, AWS’s ECR, and on Docker Hub:

    hub.docker.comgcr.iopublic.ecr.aws
    datadog/serverless-initgcr.io/datadoghq/serverless-initpublic.ecr.aws/datadog/serverless-init

    Images are tagged based on semantic versioning, with each new version receiving three relevant tags:

    • 1, 1-alpine: use these to track the latest minor releases, without breaking changes
    • 1.x.x, 1.x.x-alpine: use these to pin to a precise version of the library
    • latest, latest-alpine: use these to follow the latest version release, which may include breaking changes

    Add the following instructions and arguments to your Dockerfile.

    COPY --from=datadog/serverless-init:<YOUR_TAG> /datadog-init /app/datadog-init
    ENTRYPOINT ["/app/datadog-init"]
    CMD ["ddtrace-run", "python", "path/to/your/python/app.py"]
    

    Datadog expects serverless-init to be the top-level application, with the rest of your app’s command line passed in for serverless-init to execute.

    If you already have an entrypoint defined inside your Dockerfile, you can instead modify the CMD argument.

    CMD ["/app/datadog-init", "ddtrace-run", "python", "path/to/your/python/app.py"]
    

    If you require your entrypoint to be instrumented as well, you can instead swap your entrypoint and CMD arguments.

    ENTRYPOINT ["/app/datadog-init"]
    CMD ["/your_entrypoint.sh", "ddtrace-run", "python", "path/to/your/python/app.py"]
    

    As long as your command to run is passed as an argument to datadog-init, you will receive full instrumentation.


  3. ログを設定します。

    ロギングを有効にするには、環境変数 DD_LOGS_ENABLED=true を設定します。これにより、serverless-init が標準出力と標準エラーからログを読み取ることができます。

    Datadog では、次の環境変数も推奨しています。

    • ENV PYTHONUNBUFFERED=1: Python の出力がバッファリングされずに、コンテナログにすぐ表示されるようにします。
    • ENV DD_LOGS_INJECTION=true: サポートされているロガーのログ/トレース相関を有効にします。
    • ENV DD_SOURCE=python: 高度な Datadog ログパースを有効にします。

    複数行のログを 1 つのログメッセージとして保持する場合は、JSON 形式でログを記述することをお勧めします。たとえば、structlog のようなサードパーティのロギングライブラリを使用できます。

    import structlog
    
    def tracer_injection(logger, log_method, event_dict):
        event_dict.update(tracer.get_log_correlation_context())
        return event_dict
    
    structlog.configure(
        processors=[
            tracer_injection,
            structlog.processors.EventRenamer("msg"),
            structlog.processors.JSONRenderer()
        ],
        logger_factory=structlog.WriteLoggerFactory(file=sys.stdout),
    )
    
    logger = structlog.get_logger()
    
    logger.info("Hello world!")

    詳細については、Python ログとトレースの相関付け を参照してください。

  4. アプリケーションを構成します。

    After the container is built and pushed to your registry, set the required environment variables for the Datadog Agent:

    • DD_API_KEY: Your Datadog API key, used to send data to your Datadog account. For privacy and safety, configure this API key as a Google Cloud Secret.
    • DD_SITE: Your Datadog site. For example, datadoghq.com.

    For more environment variables, see the Environment variables section on this page.

    The following command deploys the service and allows any external connection to reach it. In this example, your service listening is set to port 8080. Ensure that this port number matches the exposed port inside of your Dockerfile.

    gcloud run deploy <APP_NAME>
      --image=gcr.io/<YOUR_PROJECT>/<APP_NAME> \
      --port=8080 \
      --update-env-vars=DD_API_KEY=$DD_API_KEY \
      --update-env-vars=DD_SITE=$DD_SITE \
    
  1. Add a service label in Google Cloud. In your Cloud Run service’s info panel, add a label with the following key and value:

    KeyValue
    serviceThe name of your service. Matches the value provided as the DD_SERVICE environment variable.

    See Configure labels for services in the Cloud Run documentation for instructions.

  1. カスタムメトリクスを送信します。

    カスタムメトリクスを送信するには、DogStatsD クライアントをインストール し、コード例を参照 してください。サーバーレスでは、ディストリビューションメトリクスタイプのみがサポートされます。

  2. プロファイリングを有効にします (プレビュー)。

    Continuous Profiler を有効にするには、環境変数 DD_PROFILING_ENABLED=true を設定します。

    Datadog の Continuous Profiler は、Google Cloud Run サービス向けにプレビュー版で利用可能です。

Environment variables

VariableDescription
DD_API_KEYDatadog API key - Required
DD_SITEDatadog site - Required
DD_SERVICEDatadog Service name. Required
DD_LOGS_ENABLEDWhen true, send logs (stdout and stderr) to Datadog. Defaults to false.
DD_LOGS_INJECTIONWhen true, enrich all logs with trace data for supported loggers. See Correlate Logs and Traces for more information.
DD_VERSIONSee Unified Service Tagging.
DD_ENVSee Unified Service Tagging.
DD_SOURCESet 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.
DD_TAGSAdd custom tags to your logs, metrics, and traces. Tags should be comma separated in key/value format (for example: key1:value1,key2:value2).

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

Pub/Sub を使用した分散型トレーシング

DD_TRACE_INFERRED_PROXY_SERVICES_ENABLED=true を設定します。これにより、プッシュリクエストの推論 gcp.pubsub.receive スパンが作成されます。

Google Cloud Pub/Sub プッシュサブスクリプションのトレースには、ddtrace バージョン 4.8.0 以降が必要です。

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.

For more information, see Producer-aware tracing for Google Cloud Pub/Sub and Cloud Run and Payload unwrapping in the Google Cloud documentation.

Configure push subscriptions for full trace visibility

Create a new push subscription:

gcloud pubsub subscriptions create order-processor-sub \
  --topic=orders \
  --push-endpoint=https://order-processor-xyz.run.app/pubsub \
  --push-no-wrapper \
  --push-no-wrapper-write-metadata

Update an existing push subscription:

gcloud pubsub subscriptions update order-processor-sub \
  --push-no-wrapper \
  --push-no-wrapper-write-metadata

Configure Eventarc Pub/Sub triggers

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.

  1. Create the Eventarc trigger:

    gcloud eventarc triggers create order-processor-trigger \
      --destination-run-service=order-processor \
      --destination-run-region=us-central1 \
      --event-filters="type=google.cloud.pubsub.topic.v1.messagePublished" \
      --transport-topic=projects/my-project/topics/orders \
      --location=us-central1
    
  2. Find the auto-created subscription:

    gcloud pubsub subscriptions list \
      --filter="topic:projects/my-project/topics/orders" \
      --format="table(name,pushConfig.pushEndpoint)"
    

    Example output:

    NAME                                                          PUSH_ENDPOINT
    eventarc-us-central1-order-processor-trigger-abc-sub-def      https://order-processor-xyz.run.app
    
  3. Update the subscription for trace propagation:

    gcloud pubsub subscriptions update \
      eventarc-us-central1-order-processor-trigger-abc-sub-def \
      --push-no-wrapper \
      --push-no-wrapper-write-metadata
    

トラブルシューティング

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.

If you are using request-based billing for a Google Cloud Run application instrumented in-container, very short requests may lead to dropped logs during the post-request CPU throttling. You can control the speed at which logs are sent to Datadog using the DD_LOGS_CONFIG_BATCH_WAIT environment variable. Set DD_LOGS_CONFIG_BATCH_WAIT to a value shorter than your typical request duration to avoid dropped logs. Sidecar instrumentation also prevents this issue, as the sidecar is not affected by request-based CPU throttling.

参考資料