If you are new to OpenTelemetry, start by reading Custom Instrumentation with the OpenTelemetry API to understand how OpenTelemetry integrates with Datadog.

Overview

There are a few reasons to manually instrument your applications with the OpenTelemetry API:

  • You are not using Datadog supported library instrumentation.
  • You want to extend the ddtrace library’s functionality.
  • You need finer control over instrumenting your applications.

The ddtrace library provides several techniques to help you achieve these goals. The following sections demonstrate how to use the OpenTelemetry API for custom instrumentation to use with Datadog.

Setup

To configure OpenTelemetry to use the Datadog trace provider:

  1. Install OpenTelemetry API packages.
composer require open-telemetry/sdk
  1. Add your desired manual OpenTelemetry instrumentation to your PHP code following the OpenTelemetry PHP Manual Instrumentation documentation.

  2. Install the Datadog PHP tracing library.

  3. Set DD_TRACE_OTEL_ENABLED to true.

Datadog combines these OpenTelemetry spans with other Datadog APM spans into a single trace of your application.

Adding span tags

You can add attributes at the exact moment as you are starting the span:

$span = $tracer->spanBuilder('mySpan')
    ->setAttribute('key', 'value')
    ->startSpan();

Or while the span is active:

$activeSpan = OpenTelemetry\API\Trace\Span::getCurrent();

$activeSpan->setAttribute('key', 'value');

Setting errors on a span

Exception information is captured and attached to a span if one is active when the exception is raised.

// Create a span
$span = $tracer->spanBuilder('mySpan')->startSpan();

throw new \Exception('Oops!');

// 'mySpan' will be flagged as erroneous and have 
// the stack trace and exception message attached as tags

Flagging a trace as erroneous can also be done manually:

use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\Context\Context;

// Can only be done after the setup steps, such as initializing the tracer.

try {
    throw new \Exception('Oops!');
} catch (\Exception $e) {
    $rootSpan = Span::fromContext(Context::getRoot());
    $rootSpan->recordException($e);
}

Adding spans

To add a span:

// Get a tracer or use an existing one
$tracerProvider = \OpenTelemetry\API\Globals::tracerProvider();
$tracer = $tracerProvider->getTracer('datadog')

// Create a span
$span = $tracer->spanBuilder('mySpan')->startSpan();

// ... do stuff

// Close the span
$span->end();

Accessing active spans

To access the currently active span:

$span = OpenTelemetry\API\Trace\Span::getCurrent();

Further Reading