# PHP instrumentation

Instrument a Symfony or plain PHP application with OpenTelemetry and send traces, logs, and metrics to Maple.

This guide sets up the OpenTelemetry PHP SDK so a Symfony or plain PHP application sends traces, logs and metrics to Maple. The `opentelemetry` extension adds auto-instrumentation for Symfony, PDO, PSR-15 handlers and PSR-18 clients. For Laravel, follow the [Laravel guide](/docs/guides/instrumentation-laravel) instead.

To have a coding agent do this setup, use the [maple-onboard](https://github.com/MapleTechLabs/maple/tree/main/skills/maple-onboard) skill. To check an existing setup, use [maple-audit](https://github.com/MapleTechLabs/maple/tree/main/skills/maple-audit).

## Prerequisites

- PHP 8.2+ (the version current releases of `open-telemetry/sdk` require)
- Composer
- An ingest key from **Settings → Ingestion** in Maple. Use the private key (`maple_sk_…`) for server applications.

## Install

Install the SDK, the OTLP exporter and a PSR-18 HTTP client for the exporter to send with:

```bash
composer require \
  open-telemetry/sdk \
  open-telemetry/exporter-otlp \
  php-http/guzzle7-adapter
```

Any package that provides `psr/http-client-implementation` works in place of `php-http/guzzle7-adapter`, for example `symfony/http-client` together with `nyholm/psr7`.

### The `opentelemetry` extension

Auto-instrumentation needs the `opentelemetry` PHP extension, which lets instrumentation packages hook into functions without code changes. Custom spans, logs and metrics work without it.

```bash
pecl install opentelemetry
# Docker images built on the official php image:
install-php-extensions opentelemetry
```

Enable it in `php.ini`:

```ini
[opentelemetry]
extension=opentelemetry.so
```

Check that it is loaded with `php --ri opentelemetry`. Building with `pecl` needs `gcc`, `make` and `autoconf`. Remi (RPM) also packages it as `php-pecl-opentelemetry`, and Alpine as `php<version>-pecl-opentelemetry` (for example `php83-pecl-opentelemetry`).

### `http/protobuf` or `http/json`

Maple accepts both encodings. The difference is on the PHP side:

- `http/protobuf` needs a protobuf implementation. The pure-PHP `google/protobuf` library, which Composer installs with the exporter, works but is slow. For production, install the protobuf C extension (`pecl install protobuf`, then `extension=protobuf.so`).
- `http/json` needs no extension. If protobuf export fails in your environment, set `OTEL_EXPORTER_OTLP_PROTOCOL=http/json`.

## Configure

With `OTEL_PHP_AUTOLOAD_ENABLED=true`, the SDK configures itself from the standard environment variables when Composer's autoloader loads, and registers itself globally before your code runs. Set the variables to Maple's ingest endpoint and your ingest key:

```bash
export OTEL_PHP_AUTOLOAD_ENABLED=true
export OTEL_SERVICE_NAME="my-php-app"

export OTEL_TRACES_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp

export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.maple.dev"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer%20YOUR_INGEST_KEY"
export OTEL_PROPAGATORS="baggage,tracecontext"

export OTEL_RESOURCE_ATTRIBUTES="deployment.environment.name=production,vcs.repository.url.full=https://github.com/acme/my-php-app"
```

For an EU organization, use `https://ingest.eu.maple.dev`. The endpoint is the base URL; the exporters append `/v1/traces`, `/v1/metrics` and `/v1/logs`. To send to [Maple Local](/docs/local-mode), set `OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318` and drop the headers.

PHP-FPM clears the environment of its workers by default, so variables exported in your shell or container may not reach PHP. Pass each one in the pool config (`env[OTEL_SERVICE_NAME] = my-php-app`), or add the same keys to `php.ini`, where the boolean is written in quotes: `OTEL_PHP_AUTOLOAD_ENABLED="true"`.

### Configure in code

To keep the configuration with your code instead, build the providers in a bootstrap file that every entry point (`public/index.php`, console scripts, workers) requires right after `vendor/autoload.php`. Leave `OTEL_PHP_AUTOLOAD_ENABLED` unset so the SDK does not configure itself a second time.

```php
<?php
// bootstrap/telemetry.php
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;
use OpenTelemetry\Contrib\Otlp\LogsExporter;
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\Contrib\Otlp\OtlpHttpTransportFactory;
use OpenTelemetry\Contrib\Otlp\SpanExporter;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Logs\LoggerProvider;
use OpenTelemetry\SDK\Logs\Processor\BatchLogRecordProcessor;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Resource\ResourceInfo;
use OpenTelemetry\SDK\Resource\ResourceInfoFactory;
use OpenTelemetry\SDK\Sdk;
use OpenTelemetry\SDK\Trace\Sampler\AlwaysOnSampler;
use OpenTelemetry\SDK\Trace\Sampler\ParentBased;
use OpenTelemetry\SDK\Trace\SpanProcessor\BatchSpanProcessorBuilder;
use OpenTelemetry\SDK\Trace\TracerProvider;

$endpoint = rtrim(getenv('OTEL_EXPORTER_OTLP_ENDPOINT') ?: 'https://ingest.maple.dev', '/'); // EU: https://ingest.eu.maple.dev
$headers = ['Authorization' => 'Bearer YOUR_INGEST_KEY'];
$transport = fn (string $path) => (new OtlpHttpTransportFactory())
    ->create($endpoint . $path, 'application/x-protobuf', $headers);

$resource = ResourceInfoFactory::defaultResource()->merge(ResourceInfo::create(Attributes::create([
    'service.name' => 'my-php-app',
    'deployment.environment.name' => getenv('DEPLOYMENT_ENV') ?: 'development',
    'vcs.repository.url.full' => 'https://github.com/acme/my-php-app',
])));

$meterProvider = MeterProvider::builder()
    ->setResource($resource)
    ->addReader(new ExportingReader(new MetricExporter($transport('/v1/metrics'))))
    ->build();

$tracerProvider = TracerProvider::builder()
    ->setResource($resource)
    ->setSampler(new ParentBased(new AlwaysOnSampler()))
    ->addSpanProcessor((new BatchSpanProcessorBuilder(new SpanExporter($transport('/v1/traces'))))->build())
    ->build();

$loggerProvider = LoggerProvider::builder()
    ->setResource($resource)
    ->addLogRecordProcessor(new BatchLogRecordProcessor(new LogsExporter($transport('/v1/logs')), Clock::getDefault()))
    ->build();

Sdk::builder()
    ->setTracerProvider($tracerProvider)
    ->setMeterProvider($meterProvider)
    ->setLoggerProvider($loggerProvider)
    ->setPropagator(TraceContextPropagator::getInstance())
    ->setAutoShutdown(true)
    ->buildAndRegisterGlobal();
```

The endpoint comes from `OTEL_EXPORTER_OTLP_ENDPOINT` when it is set, with Maple's cloud URL as the fallback, and the code appends each signal path, so the same variable switches it to [Maple Local](/docs/local-mode). Maple Local ignores the `Authorization` header unless you started it with an ingest key of its own.

The example puts the key in source. An ingest key can only write telemetry to your organization. It cannot read data or call the Maple API. Keeping it in source means the SDK always starts with a complete configuration, so a deploy that is missing an environment variable cannot silently turn telemetry off. That is fine for private code. In a public repository, read the key from an environment variable or your secret store instead.

## Symfony

With the extension loaded, add the Symfony instrumentation package:

```bash
composer require open-telemetry/opentelemetry-auto-symfony
```

It creates:

- **HTTP requests:** a root server span per request handled by the `HttpKernel`, continuing the trace from an incoming `traceparent` header. Once routing has run, the span is named after the method and the Symfony route name (for example `GET app_order_show`), which is also recorded as `http.route`
- **HTTP client:** a client span for each request made with Symfony's `HttpClient`, with the trace context propagated to the service you call
- **Messenger:** spans for messages dispatched on the bus and sent or received by a transport

For database spans, add `open-telemetry/opentelemetry-auto-pdo` (PDO, which Doctrine DBAL uses underneath) or `open-telemetry/opentelemetry-auto-doctrine`. No bundle or code change is needed: each package registers its hooks through Composer's autoloader. To turn one off without removing it, list it in `OTEL_PHP_DISABLED_INSTRUMENTATIONS`, for example `OTEL_PHP_DISABLED_INSTRUMENTATIONS=symfony`.

## Plain PHP

Without a framework, pick the instrumentation packages that match the libraries you use. Each one needs the extension:

| Library                                | Package                                    |
| -------------------------------------- | ------------------------------------------ |
| PSR-15 request handlers (Slim, Mezzio) | `open-telemetry/opentelemetry-auto-psr15`  |
| PSR-18 HTTP clients                    | `open-telemetry/opentelemetry-auto-psr18`  |
| Guzzle                                 | `open-telemetry/opentelemetry-auto-guzzle` |
| PDO                                    | `open-telemetry/opentelemetry-auto-pdo`    |

The full list is on [Packagist](https://packagist.org/search/?query=open-telemetry%2Fopentelemetry-auto). If your entry point is a plain `index.php` with no PSR-15 handler, nothing creates the request span for you; start one yourself as in [Custom spans](#custom-spans), with `SpanKind::KIND_SERVER`.

## Custom spans

Get a tracer from the global provider. A span only becomes the parent of spans created inside it once you activate it, and you must detach the scope and end the span yourself:

```php
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\StatusCode;

$tracer = Globals::tracerProvider()->getTracer('my-php-app');

$span = $tracer->spanBuilder('process-order')
    ->setAttribute('order.id', $orderId)
    ->setAttribute('payment.method', 'card')
    ->startSpan();
$scope = $span->activate();

try {
    return chargePayment($orderId);
} catch (\Throwable $e) {
    $span->recordException($e);
    $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());
    throw $e;
} finally {
    $scope->detach();
    $span->end();
}
```

Service map edges come from instrumented client spans that propagate `traceparent` to an instrumented callee, not from attributes such as `peer.service`. See [Service map](/docs/explore/service-map).

## Attributes Maple uses

Most attributes are optional. These unlock specific features.

### Commits and GitHub

Set `vcs.ref.head.revision` (the full 40-character commit SHA) and `vcs.repository.url.full` on the resource. `vcs.ref.head.revision` drives deploy markers and the **Recent deploys** panel on each service page. With the [GitHub integration](/docs/integrations/github), the two attributes also drive commit hover cards on traces. Read the SHA from your CI or host at build time, such as `GITHUB_SHA`, not from `git` at runtime:

```bash
export OTEL_RESOURCE_ATTRIBUTES="vcs.repository.url.full=https://github.com/acme/api,vcs.ref.head.revision=$GITHUB_SHA"
```

### Databases

The PDO and Doctrine instrumentations set the standard `db.*` attributes for you. `db.system.name` and `db.namespace` draw the database node on the [service map](/docs/explore/service-map), and `db.query.text` groups statements into query shapes. For a driver without instrumentation, set them on a span with `SpanKind::KIND_CLIENT`, and record the query with placeholders, not bound values. See [Database queries](/docs/concepts/otel-conventions#database-queries) for the full list.

## Logs

Send Monolog records to Maple with the OpenTelemetry Monolog handler:

```bash
composer require open-telemetry/opentelemetry-logger-monolog
```

```php
use Monolog\Logger;
use OpenTelemetry\API\Globals;
use OpenTelemetry\Contrib\Logs\Monolog\Handler;
use Psr\Log\LogLevel;

$handler = new Handler(Globals::loggerProvider(), LogLevel::INFO);
$logger = new Logger('app', [$handler]);

$logger->info('Processing order', ['order.id' => $orderId]);
```

Records written while a span is active carry its trace and span IDs, so Maple links each log line to its trace. Keep your existing handlers next to this one if you also want logs in files or stdout. A `Throwable` passed under the `exception` key is recorded as `exception.*` attributes.

In Symfony with MonologBundle, register the handler as a service and reference it from `config/packages/monolog.yaml`:

```yaml
# config/services.yaml
services:
  OpenTelemetry\Contrib\Logs\Monolog\Handler:
    arguments:
      $loggerProvider: '@opentelemetry.logger_provider'
      $level: 'info'
  opentelemetry.logger_provider:
    class: OpenTelemetry\API\Logs\LoggerProviderInterface
    factory: ['OpenTelemetry\API\Globals', 'loggerProvider']
```

```yaml
# config/packages/monolog.yaml
monolog:
  handlers:
    otel:
      type: service
      id: OpenTelemetry\Contrib\Logs\Monolog\Handler
```

## Metrics

Create instruments from the global meter provider:

```php
use OpenTelemetry\API\Globals;

$meter = Globals::meterProvider()->getMeter('my-php-app');
$orders = $meter->createCounter('orders.processed', 'orders', 'Orders processed');

$orders->add(1, ['payment.method' => 'card']);
```

Under PHP-FPM the SDK exports the metrics a request recorded when that request ends, as part of the shutdown flush described below.

## Sampling

The SDK keeps every trace by default. To keep a share of them, set a parent-based ratio sampler:

```bash
export OTEL_TRACES_SAMPLER=parentbased_traceidratio
export OTEL_TRACES_SAMPLER_ARG=0.1   # keep 10% of new traces
```

With [Configure in code](#configure-in-code), which does not read these variables, change the sampler there:

```php
use OpenTelemetry\SDK\Trace\Sampler\TraceIdRatioBasedSampler;

->setSampler(new ParentBased(new TraceIdRatioBasedSampler(0.1)))
```

The ratio applies to traces that start in this service. A request that arrives with a `traceparent` header follows the caller's decision, so a trace is kept or dropped as a whole across services. Sampling changes how Maple counts requests, so read [Sampling and throughput](/docs/concepts/sampling-throughput) before you lower the ratio.

## Shutdown and flush

Spans, log records and metrics are buffered and exported in batches. Both setups register PHP shutdown functions (autoloading does it for you, and `setAutoShutdown(true)` does it in code), so under PHP-FPM, `php -S` and CLI scripts the buffers are flushed when the request or script ends. You do not need to call anything.

Long-running workers, such as a Symfony Messenger consumer, RoadRunner or a custom loop, only reach the shutdown functions when they stop. Flush after each job or on an interval so data does not sit in memory:

```php
use OpenTelemetry\API\Globals;

foreach ([Globals::tracerProvider(), Globals::meterProvider(), Globals::loggerProvider()] as $provider) {
    // The SDK providers have forceFlush(); the no-op providers used when the SDK is off do not.
    if (method_exists($provider, 'forceFlush')) {
        $provider->forceFlush();
    }
}
```

Stop workers through their graceful stop mechanism, such as `messenger:stop-workers` for Symfony Messenger. A custom CLI worker should handle `SIGTERM` with `pcntl_signal()` and leave its loop normally so PHP runs the shutdown functions. An unhandled `SIGTERM`, a `SIGKILL` or a fatal error that ends PHP abruptly loses whatever was not flushed.

## Local mode and Docker

To send to [Maple Local](/docs/local-mode) on the same machine, set `OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318` and drop the `Authorization` header. Maple Local accepts OTLP over HTTP on port `4318`, as protobuf or JSON.

From a container, the exporter must reach back to the host. Maple Local binds `127.0.0.1` by default, which a container cannot reach, so start it with `maple start --host 0.0.0.0` and point the exporter at `http://host.docker.internal:4318`. A non-loopback bind exposes ingest, the UI and queries to your network unless you also set `MAPLE_LOCAL_INGEST_KEY` and `MAPLE_LOCAL_ACCESS_TOKEN` (each at least 16 characters). Set both, and send the ingest key in the exporter's `Authorization` header. See the [CLI reference](/docs/reference/cli#maple-start). On Linux hosts where `host.docker.internal` does not resolve, add `extra_hosts: ["host.docker.internal:host-gateway"]` to the service in `docker-compose.yml`.

## Verify

1. Start your application and send it a few requests.
2. In Maple, open **Explore → Traces**. If nothing appears after a minute, see [Troubleshooting](#troubleshooting).
3. With the Symfony or PSR-15 instrumentation, each request should show up as one trace with a single root server span (in Symfony, named after the method and route name, such as `GET app_order_show`), and child spans for the queries and outgoing calls it made.
4. If you added the Monolog handler, open **Explore → Logs** and check that log lines link to their traces.

Your service also appears on the **Services** page once its first spans arrive.

## Troubleshooting

- **`401` responses.** The key is wrong, was copied from the other region, or the header is malformed. `OTEL_EXPORTER_OTLP_HEADERS` takes `Authorization=Bearer%20YOUR_INGEST_KEY`. See [Ingest API status codes](/docs/reference/ingest#status-codes).
- **No spans from Symfony, PDO or other libraries.** Run `php --ri opentelemetry` with the same PHP binary and `php.ini` that serve your app (PHP-FPM often uses a different `php.ini` from the CLI). Without the extension, the instrumentation packages do nothing.
- **Nothing exported at all.** Check that `OTEL_PHP_AUTOLOAD_ENABLED=true` reaches PHP. Under PHP-FPM, set it in the pool config or `php.ini`, not only in the shell. Check that `OTEL_SDK_DISABLED` is not set to `true`.
- **Protocol.** Maple accepts OTLP over HTTP as protobuf or JSON. If exports fail with protobuf errors, switch to `http/json`, or install the protobuf extension. The gRPC transport is not needed; Maple Local does not accept it at all.
- **No HTTP client.** An error about a missing `psr/http-client-implementation` or a failed HTTP client discovery means no PSR-18 client is installed. Add `php-http/guzzle7-adapter`.
- **Network.** From the server or container, run `curl -i https://ingest.maple.dev/v1/traces -X POST`. Any HTTP status code means the host can reach Maple. A timeout or DNS error means a firewall or proxy is blocking outbound HTTPS.

## Next steps

- [Explore traces](/docs/explore/traces)
- [Track errors](/docs/errors/overview)
- [Create alert rules](/docs/alerting/alert-rules)
- [OpenTelemetry conventions](/docs/concepts/otel-conventions)
