Search by

keboola / opentelemetry-bundle

Keboola

Keboola OpenTelemetry Bundle

Package info

github.com/keboola/opentelemetry-bundle

Type:symfony-bundle

pkg:composer/keboola/opentelemetry-bundle

Statistics

Installs: 30

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

0.1.2 2026-12-03 08:07 UTC

README

One shared OpenTelemetry package for the PHP services of Keboola: web requests under Apache with mod_php, PHP-FPM, FrankenPHP (classic mode) and RoadRunner, Symfony Messenger consumers, console commands and command line scripts. The package sets up the OpenTelemetry SDK, redacts secrets, exports the spans at the end of each unit of work, links the spans of a Messenger message to its sender, and writes the trace ids into the logs. See Run modes.

Contents

Status

0.x: settings and API can change in a minor version. Require ^0.1.

What a service gets:

Installation

Do the steps in this order. Symfony Flex registers the bundle while composer require runs, and the container then needs app_name.

  1. Name the application. The name is the prefix of your custom attributes. Add the container parameter to config/services.yaml:

    parameters:
        app_name: my-app

    Use the parameter, not the bundle configuration. A config/packages/keboola_open_telemetry.yaml that exists before the bundle is registered fails the build of the container.

  2. In the image, install the PHP extensions before composer install. The package requires opentelemetry, so Composer refuses to install it without the extension:

    COPY --from=ghcr.io/mlocati/php-extension-installer:2.13.4 /usr/bin/install-php-extensions /usr/local/bin/
    RUN install-php-extensions @composer-2 opentelemetry protobuf apcu pcntl

    protobuf makes the export much cheaper. apcu is for Apache, PHP-FPM and FrankenPHP. pcntl is for commands and scripts. See Requirements.

  3. Tell Composer what to do with the two Composer plugins that the packages bring. This stops Composer from asking. The commands add to the allow-plugins that the skeleton already has, and Symfony Flex stays allowed:

    composer config allow-plugins.php-http/discovery false
    composer config allow-plugins.tbachert/spi true

    The package works whether tbachert/spi is allowed or not: it registers what it needs from the SDK itself.

  4. Require the package:

    composer require keboola/opentelemetry-bundle

    It brings everything the spans need: the instrumentations of Symfony, Guzzle and PDO, and Guzzle as the HTTP client of the export. Do not require open-telemetry/api or the instrumentations in the service: the package sets their versions (record 0034).

  5. Without Flex, register the bundle in config/bundles.php:

    Keboola\OpenTelemetryBundle\KeboolaOpenTelemetryBundle::class => ['all' => true],
  6. In the deployment, turn the SDK on and tell it where to send the spans and who the service is:

    OTEL_PHP_AUTOLOAD_ENABLED=true
    OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.example:4318
    OTEL_SERVICE_NAME=importer-api
    

    Set them in the environment of the PHP process or in php.ini. OTEL_PHP_AUTOLOAD_ENABLED in .env exports nothing and logs no warning: the SDK reads it while Composer loads, before Symfony reads .env. Set no other OTEL_* variable: the package has defaults. A web server also sets OTEL_PHP_EXCLUDED_URLS for its health checks. A daemon that is not a Messenger consumer goes into console.untraced_commands.

  7. Check it locally. With OTEL_TRACES_EXPORTER=console, a command prints its spans, redacted, on standard output:

    OTEL_PHP_AUTOLOAD_ENABLED=true OTEL_TRACES_EXPORTER=console bin/console about

    The console exporter does not send anything, so this does not prove that the collector receives the spans. bin/console cache:clear prints the warnings of the build.

After you add the bundle to an application that has a cached container, clear var/cache.

Requirements

  • PHP 8.2 or newer
  • Symfony 6.4.3 or newer 6.4, 7.4 or 8
  • Monolog 3.9 or newer
  • The PHP extension opentelemetry 1.5 or newer. The package cannot be installed without it (record 0026).
  • The PHP extension pdo, which open-telemetry/opentelemetry-auto-pdo needs.
  • Recommended PHP extensions: protobuf (makes the export much cheaper, see record 0024), apcu (web servers except RoadRunner: shares the pause of the export between requests), pcntl (commands: without it, a signal ends the process and its spans are lost).

Configuration

Symfony configuration

Every setting is read when the container is built. An environment variable cannot set one: the build fails with "keboola_open_telemetry. is read when the container is built". Only app_name is required, and the app_name container parameter gives it.

Setting Type Default Rule What it does
app_name string the container parameter app_name Lowercase letters, digits, _, . and -, starting with a letter. It must not start with a semantic-convention namespace, such as http, app or service. The prefix of custom attributes (Attr::app()) and the scope of the tracer keboola_open_telemetry.tracer. Without the parameter and without this setting, the build fails.
console.untraced_commands list of strings ['messenger:consume', 'cache:*', 'assets:*'] Names or shell patterns (*, ?, […]), matched against the whole name of the command, not an alias, and case sensitive. A list replaces the default. [] or ~ traces every command. The commands that get no root span while KBC_OTEL_TRACE_CLI is unset (console commands).
messenger.enabled bool true After each message of messenger:consume: detach the scopes that the message left and export its spans. With false, a worker exports at 2048 spans and when it ends.
messenger.propagation bool true Adds traceparent and tracestate to the messages of every transport, and continues the trace of the sender on the consumer. false turns it off for all transports.
logs.processor bool true Writes trace_id and span_id into extra of every log record of MonologBundle.
logs.decorate_json_formatter bool true Wraps each JsonFormatter of a handler, so the ids are at the root of the JSON line.
# config/packages/keboola_open_telemetry.yaml
keboola_open_telemetry:
    app_name: '%app_name%'          # the prefix of custom attributes, e.g. "my-app"
    console:
        untraced_commands: ['messenger:consume', 'cache:*', 'assets:*']   # no root span; the switch wins
    messenger:
        enabled: true               # export and scope reset after each message
        propagation: true           # the consumer continues the trace of the sender
    logs:
        processor: true             # trace ids in log records
        decorate_json_formatter: true   # trace ids at the root of the JSON line

The defaults are shown. The parameter app_name can take its value from an environment variable. Then leave app_name out of this file. The variable is read when the container is built: a container built in the image build keeps that value, and the build fails when the variable and its default are not set.

When the container is built, the package logs a warning if the PHP extension protobuf is missing, and if php.ini turns off #[WithSpan] while a service class uses it. These warnings do not depend on OTEL_PHP_AUTOLOAD_ENABLED, because the image build does not have the environment of the deployment (record 0024). The build reads the php.ini of the command line, which can differ from the one of the web server.

Environment and php.ini

Each name is read from the environment of the process or from php.ini. The names that are read while Composer loads cannot come from .env: Symfony reads it later. The names that are read later can, such as OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_SERVICE_NAME. The column Read says when.

Name Values Default Set by Read What it does
OTEL_PHP_AUTOLOAD_ENABLED true, false false the deployment when Composer loads Turns the SDK on. The on/off switch of a deployment (Turn it off).
OTEL_EXPORTER_OTLP_ENDPOINT URL http://localhost:4318 (SDK) the deployment when the SDK builds its exporter The collector.
OTEL_SERVICE_NAME string unknown_service:php (SDK) the deployment at the first span service.name of the resource. It is not app_name.
OTEL_PHP_EXCLUDED_URLS regular expressions, comma separated, matched against the request URI none the deployment of a web server when Composer loads Requests without the SDK, such as health checks. Example: /health-check$.
OTEL_SDK_DISABLED true, false false the deployment when Composer loads true turns off the SDK and the SDK layer of the package (Turn it off).
KBC_OTEL_TRACE_CLI boolean¹ unset the deployment of a command when each command starts Unset: console.untraced_commands decides. on: every command gets a root span. off: no command does (console commands).
KBC_OTEL_REDACTION boolean¹ on a developer once, when Composer loads² off exports secrets. Only for local debugging, never in a deployment. It logs a warning (redaction).
KBC_OTEL_EXPORT_BREAKER boolean¹ on the deployment once, when Composer loads² off: every export tries the collector, also after a failed one (export breaker).
KBC_OTEL_EXPORT_BREAKER_PAUSE whole number, 1 to 86400 30 the deployment once, when Composer loads² Seconds without export after a failed one. While OTEL_PHP_AUTOLOAD_ENABLED is on, another value warns and gives 30.
KBC_OTEL_PDO_DROP_HELPER_SPANS boolean¹ on the deployment at every export Drops the successful PDO::prepare and PDOStatement::fetchAll spans, in the otlp exporter only. It has no effect while OTEL_PHP_INSTRUMENTATION_PDO_DISTRIBUTE_STATEMENT_TO_LINKED_SPANS is false (record 0023).
OTEL_PROPAGATORS list tracecontext (SDK: tracecontext,baggage) the package when the SDK builds its providers Leave unset: a value in a deployment template hides the default of the package (record 0028).
OTEL_TRACES_SAMPLER sampler always_on (SDK: parentbased_always_on) the package the same Leave unset.
OTEL_EXPERIMENTAL_SPAN_SUPPRESSION_STRATEGY strategy spankind (SDK: none) the package the same Leave unset.
OTEL_BSP_SCHEDULE_DELAY milliseconds 600000 (SDK: 5000) the package the same Leave unset. Spans are exported at the end of a unit of work.
OTEL_BSP_MAX_QUEUE_SIZE number 2048 (SDK: 2048) the package the same Leave unset.
OTEL_BSP_MAX_EXPORT_BATCH_SIZE number 2048 (SDK: 512) the package the same Leave unset.
OTEL_METRICS_EXPORTER, OTEL_LOGS_EXPORTER exporter none (SDK: otlp) the package the same Leave unset. The package handles traces only.
OTEL_PHP_INSTRUMENTATION_PDO_DISTRIBUTE_STATEMENT_TO_LINKED_SPANS true, false true (SDK: false) the package the same Leave unset.
OTEL_EXPORTER_OTLP_TIMEOUT, OTEL_EXPORTER_OTLP_TRACES_TIMEOUT milliseconds 200 while neither is set (SDK: 10000) the package when the SDK builds its exporter The otlp span exporter waits at most this long and makes no retry. The retries cannot be changed. Leave both unset.
OTEL_EXPORTER_OTLP_PROTOCOL, OTEL_EXPORTER_OTLP_TRACES_PROTOCOL http/protobuf, http/json http/protobuf the deployment when the SDK builds its exporter The protocol of the otlp exporter. The package wraps the transport that it selects.
OTEL_TRACES_EXPORTER otlp, console, none otlp a developer when the SDK builds its exporter console prints the spans on standard output, redacted.
OTEL_PHP_LOG_DESTINATION default (PHP error_log()), error_log, stderr, stdout, none default a developer when the first warning is written Where the warnings of the SDK and of the package go (Troubleshooting).
OTEL_LOG_LEVEL debug to emergency, none info a developer when the first warning is written The lowest level of those warnings.
TRACEPARENT, TRACESTATE W3C trace context none whoever starts a command line script when the script starts ProcessSpan::start() continues that trace.
RR_MODE any none RoadRunner, for its workers and their child processes when each command starts No command there gets a root span.
opentelemetry.attr_hooks_enabled (php.ini only) On, Off turned on by the package while OTEL_PHP_AUTOLOAD_ENABLED is on the deployment when Composer loads #[WithSpan] and #[SpanAttribute]. Set it to Off with php_admin_value, or in php.ini, to turn them off; a php_value of Off is overridden.
opentelemetry.attr_pre_handler_function, opentelemetry.attr_post_handler_function (php.ini only) function names the handlers of the package, while the attributes are on nobody when Composer loads Leave them unset. When php.ini names one, the package sets neither (record 0011).

¹ true/false, on/off, 1/0, yes/no, in any case. While OTEL_PHP_AUTOLOAD_ENABLED is on, another value logs a warning, and the default is used. In php.ini, quote the word ("off") or write 0: php.ini makes an unquoted off empty, which counts as unset and logs a warning.

² A .env file and putenv() come too late. Not read while OTEL_SDK_DISABLED=true.

The OTEL_* settings accept only what the SDK accepts. A value that a framework loads from .env after Composer still wins over a default of the package, for the names that are read when the SDK builds its providers.

Not supported: the transaction span of the SDK (OTEL_PHP_TRANSACTION_SPAN_ENABLED, OTEL_PHP_TRANSACTION_SPAN_ENABLED_CLI and the deprecated OTEL_PHP_EXPERIMENTAL_AUTO_ROOT_SPAN) and OTEL_CONFIG_FILE. With them, spans can be exported without redaction. The package logs a warning while OTEL_PHP_AUTOLOAD_ENABLED is on.

Run modes

A unit of work is a request, a message or a process. The package exports at its end, with the same exporter, redaction and logs in every mode (record 0002, record 0012). Every mode starts with the installation; a command line script needs no bundle registration.

Mode Unit of work What the service adds
Apache with mod_php request apcu, excluded URLs
PHP-FPM request apcu, excluded URLs, process_control_timeout
FrankenPHP, classic mode request apcu, excluded URLs
RoadRunner request nothing
Symfony Messenger consumer message nothing
Console commands, such as cron jobs command SIGTERM as stop signal
Command line scripts process two calls in the script, SIGTERM as stop signal
A worker loop of your own, or another daemon what you mark units of work, and its command in console.untraced_commands where it is a console command

Apache with mod_php

You set up the installation, and in the image and the deployment:

  • Install the PHP extension apcu: the processes share the pause of the export.
  • Set OTEL_PHP_EXCLUDED_URLS for the URLs of health checks. For them the SDK is not set up.

You get one export for each request, at its end, in the process that served it (record 0029). Only a request with more than 2048 spans also exports during its work. A request that ends with a fatal error is exported with the status ERROR.

The export runs after the application is done, and the client usually waits for it, which takes milliseconds while the collector answers. The process takes its next request only after the export. Which responses reach the client before the export is in the record.

A graceful stop (SIGWINCH, the stop signal of the official image) finishes the requests in progress and exports them. SIGTERM loses them.

PHP-FPM

You set up the installation, and in the image and the deployment:

  • Install the PHP extension apcu, as under mod_php.
  • Set OTEL_PHP_EXCLUDED_URLS for the URLs of health checks.
  • Keep clear_env = no, as in the official image, or PHP does not see the OTEL_* variables.
  • Set process_control_timeout, which is 0 by default, or a graceful stop loses the requests in progress.

You get what mod_php gives, with two differences (record 0029):

  • A Symfony response reaches the client before the export: Response::send() ends the request of the client first. A script that only prints its response still waits. The process takes its next request only after the export.
  • A graceful stop is SIGQUIT, the stop signal of the official image.

FrankenPHP

FrankenPHP in classic mode (php_server without a worker script) starts a new script for every request, in threads of one process.

You set up the installation, and in the image and the deployment:

  • Install the PHP extensions in the FrankenPHP image, for example with its install-php-extensions. FrankenPHP uses a thread-safe (ZTS) PHP: opentelemetry 1.5.0, apcu 5.1.28 and protobuf 5.36.2 build and work there.
  • Install apcu: all threads share the pause of the export through it.
  • Set OTEL_PHP_EXCLUDED_URLS for the URLs of health checks.

You get one export for each request, at its end, as under mod_php, and the status ERROR after a fatal error (record 0029). Differences from mod_php:

  • A Symfony response reaches the client before the export, compressed or not, because FrankenPHP provides fastcgi_finish_request(), which Symfony calls. A script that only prints its response waits for the export.
  • A thread takes its next request only after the export. Count that time when you choose the number of threads.
  • php_ini of the Caddyfile counts as php.ini for the #[WithSpan] settings. There is no php_value.
  • SIGTERM and SIGINT finish the request in progress and export it. SIGQUIT loses it.

The worker mode of FrankenPHP is not supported (Limits). Commands of a FrankenPHP image run in its command line PHP, see Console commands.

RoadRunner

You set up nothing: you keep your runtime and runner. A RoadRunner worker needs no KBC_OTEL_TRACE_CLI.

You get one unit of work for each request. The package hooks the point where an HTTP worker of RoadRunner waits for a request, HttpWorkerInterface::waitRequest(), which PSR7Worker calls too: when the worker asks for the next request, the scopes that the last one left are detached and its spans are exported (record 0018). The package detaches the scopes also when the SDK is disabled.

A worker that runs as a console command needs no setup either: it gets no console root span.

Your runner:

  • calls $kernel->terminate() before it asks for the next request, also when sending the response failed. The span of a request ends there, and a span that is still open is not exported;
  • needs no export or scope reset of its own. A forceFlush() that it has costs nothing, because nothing is left to send then.

If your runner replaces another runtime, update the code that compares APP_RUNTIME with the class of the runtime, for example to choose a log handler.

The tested versions of spiral/roadrunner-http are in the record. The package cannot be installed with 5.0 or newer, which is not tested. The minimum versions in require-dev are for the tests of the package only.

An export takes place between two requests of a worker, so the next request of that worker can wait for it. A request with more than 2048 spans exports during the request too.

Symfony Messenger

You set up the installation. There is nothing else to set up: you keep your transports and serializers. messenger:consume is in the default list of commands without a root span.

You get one unit of work for each message. After each message of a messenger:consume worker, the scopes that the message left are detached and its spans are exported (record 0031). A worker loop of your own, without the Messenger worker, needs a unit of work.

The consumer continues the trace of the sender (record 0019):

  • The package wraps the serializer of every transport of framework.messenger.transports. It adds the W3C traceparent and tracestate of the sender to the headers of the message.
  • On the consumer, the CONSUME span of the instrumentation is a child of the span of the sender. Retries and the failure transport stay in the same trace.
  • A consumer without the package ignores the headers: deploy producers and consumers in any order, and roll back without losing messages.
  • A message without the headers starts a new trace, also when the command of the worker has a root span. The polling of the transport stays out of that span too, whatever the messenger settings say.
  • With the span suppression of the package, a first send has a DISPATCH span and no SEND span inside it.
  • The consumer also reads the context that a producer with dd-trace-php 1.5 or newer sends.

The limits of this mode are in Limits.

Console commands

You set up the installation, the stop signal of the container and, for each daemon that is not a Messenger consumer, its command in console.untraced_commands.

You get a root span of kind SERVER for every console command, named after the command, with its exit code (process.exit.code) and its exception. It is ERROR when the exit code is not 0, or when a signal stops the command (record 0017). After such a signal, the spans still open when the process ends are ERROR too.

Which commands get a root span is decided by the setting console.untraced_commands and the switch KBC_OTEL_TRACE_CLI. The switch wins:

KBC_OTEL_TRACE_CLI Root span
unset every command, except those of console.untraced_commands
on every command: the list is ignored
off no command

The list is a Symfony setting, read when the container is built. The switch is read when each command starts, so one image can run with different values. Prefer the list: it needs no setting of the deployment.

keboola_open_telemetry:
    console:
        untraced_commands: ['messenger:consume', 'cache:*', 'assets:*', 'app:worker-*']
The deployment runs Set
a cron job or another command that ends nothing
a Messenger consumer (messenger:consume) nothing
a worker or daemon with a loop of its own add its command to the list, or KBC_OTEL_TRACE_CLI=off for that deployment
every command traced, also those of the list KBC_OTEL_TRACE_CLI=on
a RoadRunner worker nothing

Keep every consumer and daemon out of the traced commands. Otherwise one span covers the whole life of the process, its work ends up in one trace, and the span is ERROR when a signal stops the process. Only the messages of a Messenger worker keep traces of their own even then, so KBC_OTEL_TRACE_CLI=on is safe for messenger:consume. For a command without a root span, a signal that stops it sets no status.

Also without a root, whatever the switch and the list say:

  • every command in a RoadRunner worker, which RoadRunner marks with the environment variable RR_MODE. A process that a worker starts inherits it, so its commands get no root either;
  • a command that runs while a span is already active, such as a command run by a command, or a process that started its own span. The outermost command then puts its exit code and status on the local root span, unless a contrib instrumentation created that span.

Stop signals

A container has to stop a command with SIGTERM. Symfony Console 6.4 handles SIGINT, SIGTERM, SIGUSR1 and SIGUSR2, and 7.4 and 8 also SIGQUIT and SIGALRM. Images built on the official PHP Apache images stop with SIGWINCH, which no version handles, and images built on the PHP-FPM images with SIGQUIT, which works from 7.4 on. The official FrankenPHP image names no stop signal, so its containers get SIGTERM. Set STOPSIGNAL SIGTERM in the image, or lifecycle.stopSignal in the pod where the cluster supports it. When the image also serves requests under Apache or PHP-FPM, set lifecycle.stopSignal: SIGTERM on the pods of the commands and jobs, not STOPSIGNAL in the image: SIGTERM loses the requests in progress. With a signal that nothing handles, a command that is killed exports no spans, or ends as if it had succeeded.

Command line scripts

You set up the installation except the registration of the bundle, the stop signal and the two calls below, in a script without Symfony Console or a job that runs in its own container. You get one root span for the process, exported when the process ends.

require __DIR__ . '/vendor/autoload.php';

use Keboola\OpenTelemetryBundle\Process\ProcessSpan;
use Keboola\OpenTelemetryBundle\Process\SignalExit;

SignalExit::install();
$span = ProcessSpan::start('import-data');
  • ProcessSpan::start() starts the root span of the process. It continues the trace of the environment variables TRACEPARENT and TRACESTATE, if whoever started the process set them. A second argument, such as ['traceparent' => $traceParent], wins over them. You do not end the span.
  • SignalExit::install() is only for scripts that handle no signals. On SIGTERM or SIGINT the script ends with the code 143 or 130, and its spans are exported with the status ERROR. finally blocks do not run. It needs the PHP extension pcntl. Without it, it returns false and logs a warning, and a signal loses the spans. Do not use it in Symfony Console commands or Messenger consumers.
  • A fatal error and an uncaught exception give the status ERROR. An exit code gives none, because PHP does not pass it on: set the status on $span before exit() where it matters.
  • Spans made in your shutdown functions belong to the process span.
  • Without the bundle, Attr::app() uses the prefix unknown_app.

Record 0030 has the reasons and the limits.

Units of work

A long running process, such as a worker with a loop of its own or a daemon, marks each request, message or job as a unit of work. If it runs as a console command, leave it without a root span, or all units join the trace of the command:

use Keboola\OpenTelemetryBundle\UnitBoundary;

while ($job = $queue->next()) {
    $unit = UnitBoundary::begin();
    try {
        $handler->handle($job);
    } finally {
        $unit->end();
    }
}

end():

  • detaches every scope attached since begin(), also scopes that other code forgot, so the next unit does not continue the trace of this one;
  • exports the finished spans;
  • ends no span. End your spans before it: a span that is still open stays open;
  • never throws. A second call does nothing.

End nested units in the reverse order of their start. Otherwise end() can detach scopes of the caller. It logs a warning when the scope on which the unit began is gone. For the requests of a RoadRunner HTTP worker and the messages of a Messenger worker the package does all this.

Spans of your code

Trace a unit of work or a step that matters, not a small method in a loop: a span costs about 10 µs plus its export. There are three ways: #[WithSpan], Spans::traceMethod() and a span that you start yourself.

#[WithSpan]

For code that you own. It makes a child of the current span, records an exception with the status ERROR and lets it continue, and needs no setting of the service (record 0011):

namespace App;

use OpenTelemetry\API\Instrumentation\SpanAttribute;
use OpenTelemetry\API\Instrumentation\WithSpan;
use OpenTelemetry\API\Trace\SpanKind;

class Importer
{
    #[WithSpan]                                                   // "App\Importer::import", INTERNAL
    public function import(#[SpanAttribute('my-app.job_id')] string $jobId): void
    {
    }

    #[WithSpan('send report', SpanKind::KIND_PRODUCER, ['my-app.target' => 'mail'])]
    public function send(): void
    {
    }
}
  • Start the keys with your app name. A bare #[SpanAttribute] uses the name of the parameter.
  • Do not mark a parameter that holds a secret. Redaction finds URLs and Keboola tokens under any key, SQL only under db.query.text and db.statement, and no password. Only strings, numbers, booleans and arrays are recorded, and only for arguments that the call passes. A variadic method records no argument at all, unless an interface declares it.
  • While OTEL_PHP_AUTOLOAD_ENABLED is on, the package turns opentelemetry.attr_hooks_enabled on. A service that sets up its own tracer provider without that variable turns the switch on in php.ini or with php_admin_value.
  • To turn the attributes off, set the switch to Off in php.ini, with php_admin_value (Apache, or an FPM pool) or with php_ini in the Caddyfile of FrankenPHP, which counts as php.ini. A php_value of Off is overridden.
  • Leave the two handler settings of php.ini unset (environment and php.ini): the handlers of the package make a marked call that throws end its span.

No span is made for:

  • a method or function that already has a hook, also through its class or interface: one of an instrumentation, such as request() of an HTTP client with opentelemetry-auto-symfony, or one of traceMethod();
  • an override without the attribute of a marked method of a parent class (a marked interface method covers its implementations);
  • a closure.

With either way, a generator gets one span for each time it runs up to a yield or its end.

Spans::traceMethod()

For code that you cannot mark, such as a method of a library, or for a name that depends on the call:

use Keboola\OpenTelemetryBundle\Naming\Attr;
use Keboola\OpenTelemetryBundle\Tracing\Spans;

// in boot() of your bundle or kernel
Spans::traceMethod(
    EventProcessor::class,
    'processEvent',
    // the name holds the event only once the registry knows it; null means no span
    onStart: static function ($processor, array $args) use ($registry): ?array {
        $event = $args[0];
        if (!$event instanceof Event || !$registry->has($event->getName())) {
            return null;
        }

        return [
            'name' => 'process ' . $event->getName(),
            'attributes' => [Attr::app('event') => $event->getName()],
        ];
    },
);
Argument What it does
onStart($object, $args) returns name, and optionally kind and attributes, or null for no span. $object is the class name for a static call
onEnd($span, $object, $args, $returnValue, $exception) adds to the span before it ends
flushOnEnd exports when the span has ended, for a unit of work of a loop
isError($exception) false leaves the status unset; the exception is still recorded
  • The class can be an interface or a parent class, and the method can be private.
  • Register while the application starts. After the first call of the method, a registration has no effect.
  • Only the first registration for a class and method counts.
  • A hook on a class runs around one on its interface, so on a method that an instrumentation hooks through an interface, your span on the class is the parent. On the same class or interface as the instrumentation, your span is its child.
  • A callback that throws does not disturb the method. The package logs one warning per method.

Your own span

The service keboola_open_telemetry.tracer is a tracer whose instrumentation scope is app_name. It has no autowiring alias, so inject it by its id. The package adds none, because an alias for TracerInterface would replace the one that an application wires itself:

namespace App;

use Keboola\OpenTelemetryBundle\Naming\Attr;
use Keboola\OpenTelemetryBundle\Naming\SpanName;
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\API\Trace\TracerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Throwable;

final class ReportSender
{
    private const FORMATS = ['csv', 'pdf'];

    public function __construct(
        #[Autowire(service: 'keboola_open_telemetry.tracer')]
        private readonly TracerInterface $tracer,
    ) {
    }

    public function send(string $reportId): void
    {
        // the span of the request or command belongs to its instrumentation: add attributes, do not rename it
        Span::getCurrent()->setAttribute(Attr::app('report.id'), $reportId);

        $span = $this->tracer->spanBuilder('send report')->startSpan();
        $scope = $span->activate();
        try {
            $format = $this->formatOf($reportId);
            // your own span: rename it once the code knows the value
            $span->updateName(SpanName::known('send report', $format, self::FORMATS));
            $span->setAttribute(Attr::app('report.format'), $format);
            // the work
        } catch (Throwable $e) {
            $span->recordException($e);
            $span->setStatus(StatusCode::STATUS_ERROR);
            throw $e;
        } finally {
            $scope->detach();
            $span->end();
        }
    }

    private function formatOf(string $reportId): string
    {
        return str_starts_with($reportId, 'pdf-') ? 'pdf' : 'html';
    }
}
  • Never rename a span that an instrumentation or the package made: the request, command, message, HTTP and database spans. Add attributes to it (record 0006).
  • Rename your own span only to a value that the code knows (SpanName::known()), never to raw input.
  • Detach the scope and end the span in finally.

The other services of the bundle, for autowiring (a definition of the application with the same id wins):

Service id What it is
OpenTelemetry\API\Trace\TracerProviderInterface Globals::tracerProvider()
OpenTelemetry\Context\Propagation\TextMapPropagatorInterface Globals::propagator()
keboola_open_telemetry.tracer a tracer whose instrumentation scope is app_name

Names and attributes

Custom attributes start with the app name, and a span name holds only values that the code knows (record 0006):

use Keboola\OpenTelemetryBundle\Naming\Attr;
use Keboola\OpenTelemetryBundle\Naming\SpanName;
use OpenTelemetry\API\Trace\Span;

$name = SpanName::known('process', $eventName, ['job.created', 'job.deleted']); // "process job.created" or "process"
Span::getCurrent()->setAttribute(Attr::app('event'), $eventName);            // "my-app.event"

Attr::app() uses the app_name once KeboolaOpenTelemetryBundle has booted. Before that, and in a script without the bundle, it uses the prefix unknown_app: it does not throw and does not log, so unit tests of classes built without a kernel need no setup. In a test, build the expected key with Attr::app() and not with a literal, as the name stays set after a kernel in the same process has booted. The prefix belongs to the code: it is not service.name, as one codebase can run as several services, and not service.namespace, the Kubernetes namespace. The rules for app_name are in the configuration table.

Add attributes to the span of a request, command or message and never rename it. Rename only your own span with updateName().

HTTP client and database spans

HTTP clients (record 0007):

  • Symfony HttpClient: spans and trace headers come with open-telemetry/opentelemetry-auto-symfony, which the package requires. There is nothing to add.
  • Guzzle: spans and trace headers come with open-telemetry/opentelemetry-auto-guzzle, which the package requires. There is nothing to add.
  • Other clients get no span. Composer refuses open-telemetry/opentelemetry-auto-curl and open-telemetry/opentelemetry-auto-psr18 next to the package (record 0008, record 0009). It refuses open-telemetry/symfony-sdk-bundle too (record 0010).
  • Every outgoing call sends traceparent and tracestate, also to third-party hosts. There is no allowlist (record 0005).
  • The span keeps only the scheme, host and port of the URL, and no exception message (redaction).
  • A service that wants no Guzzle or no PDO spans sets OTEL_PHP_DISABLED_INSTRUMENTATIONS=guzzle, pdo or guzzle,pdo. The packages stay installed.

Databases (record 0022):

  • open-telemetry/opentelemetry-auto-pdo, which the package requires, covers PDO, and with it Doctrine DBAL and ORM.
  • Composer refuses open-telemetry/opentelemetry-auto-doctrine next to the package.
  • The span of each execution carries the SQL, with its literals removed. The successful PDO::prepare and PDOStatement::fetchAll spans are dropped (KBC_OTEL_PDO_DROP_HELPER_SPANS).

Logs

A log record written inside a span gets the trace_id and span_id (hex) of that span, also when the span is not sampled. The package does this in two steps:

  1. A Monolog processor writes the ids into extra when the record is created. The package puts it on every logger of MonologBundle, so the processor needs no setup. MonologBundle must be enabled, as in every Symfony application that uses Monolog. Without it, no record gets the ids. The processor runs before any handler holds the record, so buffering handlers, such as fingers_crossed and buffer, keep the ids of the span in which the record was written, also when the buffer is written out later, in another span.
  2. A formatter writes them at the root of the JSON line. The package wraps your JSON formatter in it, so you change no configuration.

The package wraps every Monolog\Formatter\JsonFormatter or subclass of it that a service has through a setFormatter() call, which includes the handlers of MonologBundle. The wrapper is Keboola\OpenTelemetryBundle\Log\TraceContextFormatter. These stay as they are, and their ids stay under extra:

  • a formatter that is not a JsonFormatter, also the default LineFormatter of a handler without a formatter;
  • a formatter whose output is not a JSON object that ends in a closing brace;
  • a handler that is defined inline inside another service definition.

logs.decorate_json_formatter: false turns the wrapping off. How the wrapper decides, and what it does to a batch, is in record 0003.

Wrap the formatter yourself in a handler that the package does not reach, or when the wrapping is off:

use Keboola\OpenTelemetryBundle\Log\TraceContextFormatter;
use Monolog\Formatter\JsonFormatter;

$handler->setFormatter(new TraceContextFormatter(new JsonFormatter()));

In a service definition:

# config/services.yaml
services:
    app.log_formatter:
        class: Keboola\OpenTelemetryBundle\Log\TraceContextFormatter
        arguments: ['@monolog.formatter.json']

# config/packages/monolog.yaml
monolog:
    handlers:
        main:
            type: stream
            path: 'php://stderr'
            formatter: app.log_formatter

The package leaves a TraceContextFormatter as it is, so the ids are not written twice.

How it works

When Composer loads the package, it hooks the RoadRunner worker to make each request one unit of work. This one happens also with OTEL_SDK_DISABLED=true.

Unless OTEL_SDK_DISABLED=true, it also:

  • registers the span suppression strategies of the SDK, if the tbachert/spi plugin did not;
  • replaces the otlp span exporter of the SDK with one that redacts secrets (unless KBC_OTEL_REDACTION=off), makes one attempt of at most 200 ms, and pauses for 30 s after a failed export;
  • makes the console and otlp/stdout span exporters redact secrets too;
  • ends the spans that are still open when the process ends, with the status ERROR after a fatal error;
  • uses the wall clock for span times in command line processes;
  • gives #[WithSpan] handlers of its own and, while tracing is on, turns it on (spans of your code);
  • changes the defaults of the SDK.

The spans are exported at the end of each unit of work. Until a unit ends, a worker keeps them, and it exports during the unit only at 2048 spans.

Export breaker

After an export fails, the package skips every export for a pause of 30 seconds and then lets one export try again (record 0012). The spans of the skipped exports are dropped. Where APCu is on, the processes of a web server share the pause. Without it, each process keeps its own, and a collector that does not answer delays one request of each process in 30 s by 200 ms.

  • KBC_OTEL_EXPORT_BREAKER=off removes the breaker. Every export then tries the collector, and a collector that does not answer costs each unit of work one wait. The transport stays bounded either way: 200 ms, no retries.
  • KBC_OTEL_EXPORT_BREAKER_PAUSE is the pause in seconds.

Both are read once, when Composer loads the package, so they work in every run mode, a plain script too (environment and php.ini).

Redaction

Record 0027 has the rules. In short: URLs are reduced to their scheme, host and port (the URL of a received request keeps its path), SQL literals and the values that databases repeat in errors are removed, spans of outgoing HTTP calls keep no exception messages, and secret headers, secret query values and Keboola tokens are replaced: prefixed tokens (kbc_…), classic Storage API tokens (digits, a dash, digits, a dash, 40 letters or digits) and Manage API tokens (digits, a dash, 40 letters or digits). Tokens and URLs in the trace state that a caller sends are redacted in the export.

KBC_OTEL_REDACTION=off is for local debugging only, never for a deployment. It removes redaction from the otlp, console and otlp/stdout span exporters, resource and trace state included, and changes nothing else. Secrets in URLs, SQL, headers and error messages are then exported. The package logs a warning when it builds the exporter: once for each process, or once for each request under a web server. It is a log of OpenTelemetry, so OTEL_LOG_LEVEL=error and OTEL_PHP_LOG_DESTINATION=none hide it. A .env line cannot turn redaction off, and an invalid value leaves it on (and warns while OTEL_PHP_AUTOLOAD_ENABLED is on). The canary tests start their processes with it on, whatever the environment says, and fail when a log holds the warning.

What your code puts into a span, and the headers that you tell an instrumentation to record, are your responsibility. Check your service with secrets of its own. What redaction does not cover is in Limits.

Check your service for leaked secrets

Keboola\OpenTelemetryBundle\Testing\SeededCanaryTestCase is a PHPUnit test case for your test suite (record 0032). Plant secrets, run your code, and the test fails when one of them is exported:

use Keboola\OpenTelemetryBundle\Testing\SeededCanaryTestCase;

class TelemetrySecretsTest extends SeededCanaryTestCase
{
    public function testImportExportsNoSecret(): void
    {
        $password = $this->canary('database password');
        $webhook = $this->canary('webhook secret');

        // a new PHP process, whose telemetry goes to a receiver of this test
        $run = $this->runPhp(
            ['bin/console', 'app:import', '--webhook=https://example.com/hooks/' . $webhook],
            ['DATABASE_PASSWORD' => $password, 'APP_ENV' => 'test'],
        );

        // the import fails on purpose: errors repeat what they got
        self::assertSame(1, $run->exitCode, $run->errorOutput);
        // the code was traced: without its spans, a canary is absent for no good reason
        self::assertContains('app:import', $this->exportedSpanNames());
        $this->assertNoCanaryExported();
    }
}
Method What it does
canary($label) a new secret, of lower case letters and digits
watchSecret($label, $secret) watches for a secret of your own, also URL encoded and JSON escaped
runPhp($arguments, $environment) runs php and waits for its end; the process gets no OTEL_* variable of the test, so pass those that it needs; returns the exit code and the output
telemetryEnvironment() the environment for a process that you start yourself, such as a server
exportedSpanNames(), exportedTraces() what arrived, to check that your code was traced
assertNoCanaryExported($knownLeaks) fails when a canary is in a span or resource that was exported, or in a metric or log record when the process exports them; also when no span arrived, and when a process logged an error of OpenTelemetry
collectLog($log), assertNoCanaryInLogs($knownLeaks) the same for the output of the processes and for logs that you add; the package does not redact logs
stopCanaryReceiver() runs after each test, and forgets the canaries, the logs and what arrived; call it to start over inside a test
  • $knownLeaks maps the label of a canary to the reason why it may leave, such as a limit of record 0027. Such a canary must be found, so the list stays true.
  • Put canaries where your service has secrets: URLs and headers of the calls that it makes and receives, SQL, error messages, messages of queues. Make the code fail too, because errors repeat what they got.
  • Always assert the exit code and the names of the spans that you expect: a killed process can export only a part.
  • Stop a server, or wait for its export, before you assert, and pass its log to collectLog(), or a failed export of the server is not seen. Do not give it other OTEL_* settings.
  • The secret is not found when it is encoded another way, such as base64, or cut short.
  • Your test suite needs PHPUnit, and the process the extension opentelemetry. Tested with PHPUnit 10.5, 11.5 and 12.5.

Turn it off

To Set What stays
Stop tracing in a deployment OTEL_PHP_AUTOLOAD_ENABLED unset or false The bundle and its services, with tracers that do nothing. No span is exported, log records get no ids, and #[WithSpan] is off.
Also turn off the SDK layer of the package OTEL_SDK_DISABLED=true The same. The package also sets no defaults and replaces no exporter. The RoadRunner hook still detaches the scopes of each request.
Turn off one part messenger.enabled, messenger.propagation, logs.processor, logs.decorate_json_formatter or KBC_OTEL_TRACE_CLI=off Everything else.

Removing the bundle from config/bundles.php removes the services, listeners and log processor. The SDK layer stays, because Composer loads it with the package. Removing the package with Composer removes all of it.

Limits

  • FrankenPHP worker mode is not supported and not tested (FrankenPHP).
  • Redaction does not cover, among others: secrets in exception text that are not URLs or tokens, such as the response body excerpt of a Guzzle exception on the server or consumer span that the exception reaches; secrets that are not URLs or tokens in span names, span attributes of your code, the values of other recorded headers, the User-Agent header and the trace state; mail addresses in errors of mailers; database errors other than those listed in record 0027, and statements that are not SQL; logs, metrics, and span exporters other than otlp, console and otlp/stdout.
  • RoadRunner: a worker class that implements only PSR7WorkerInterface and does not use the HTTP worker of RoadRunner, and workers of other RoadRunner plugins, such as jobs or gRPC, get no unit of work: use a unit of work there. A request that ends with the process, for example by SIGKILL, by exec_ttl or after the grace period of a stopped server, loses its spans.
  • Messenger (details in record 0019 and record 0031):
    • A transport that sends only the body of a message drops the headers: every message starts a new trace. Nothing warns about it.
    • A serializer of your own is wrapped too. A result without a string body, or with headers that are no array, is left alone.
    • SQS FIFO queue with Symfony 6.4 or 7.4: without a deduplication id of your own, the transport makes one from the body and the headers, so with the headers of the package identical messages are not deduplicated. Add an AmazonSqsFifoStamp with a deduplication id, or set messenger.propagation: false, which turns the link off for all transports.
    • SQS allows 10 message attributes, and each header of a message is one.
    • --concurrency above 1 (Symfony 8.2): the handlers run in child processes. Messages are not linked there, and spans are not exported after each message.
    • Batch handlers: a retry stays in the trace of its message. The spans of the work on a batch, and the acknowledgements of its messages, belong to one trace at most, that of the message that filled the batch.
  • Console commands and scripts: a command or script that is killed, or that a signal that nothing handles stops, exports no spans. A script that is blocked in a read, such as fgets(STDIN), does not react to a signal and loses its spans. A shutdown function that throws, calls exit() or ends in a fatal error stops the export: all spans of the process are lost.

Troubleshooting

No span arrives

Check in this order:

  1. OTEL_PHP_AUTOLOAD_ENABLED=true is in the environment of the PHP process or in php.ini. It is not in .env. Under PHP-FPM, the pool keeps clear_env = no.
  2. OTEL_SDK_DISABLED is not true, and the URL does not match OTEL_PHP_EXCLUDED_URLS.
  3. The command has a root span: see KBC_OTEL_TRACE_CLI and console.untraced_commands. A process that a Composer script starts has no SDK, because the SDK does not start while COMPOSER_DEV_MODE=1.
  4. The collector answers. After a failed export, the package skips exports for 30 s (export breaker).
  5. To see the spans without a collector, set OTEL_TRACES_EXPORTER=console.

An attribute starts with unknown_app.

The attribute was named before KeboolaOpenTelemetryBundle booted: in boot() of a bundle that is listed before it in config/bundles.php, or in a script without the bundle. Call Attr::app() where you set the attribute, or list the bundle earlier.

Where the warnings go

The SDK and the package write their warnings with the logger of OpenTelemetry, not with Monolog. They are not in the JSON logs of the service. By default they go to PHP error_log(): to standard error in a command without an error_log setting, otherwise to the error log of the web server. To see them in the container log, set OTEL_PHP_LOG_DESTINATION=stderr.

The warnings about the build come when the container is built, such as in cache:clear of the image build. They cover a missing protobuf and #[WithSpan] turned off in php.ini.

Errors of the build

  • There is no extension able to load the configuration for "keboola_open_telemetry": a file config/packages/keboola_open_telemetry.yaml exists, and the bundle is not registered yet. Do the installation in its order.
  • keboola_open_telemetry.app_name has no value: the container has neither the app_name parameter nor the setting.
  • keboola_open_telemetry.<setting> is read when the container is built: a setting uses %env()%. Write the value.
  • A container that was cached before you added the bundle does not have its services: clear var/cache.

Public API

What follows is public. Every other class of the package is marked @internal.

  • the classes UnitBoundary, Process\ProcessSpan, Process\SignalExit, Tracing\Spans, Naming\Attr, Naming\SpanName, Log\TraceContextFormatter, Testing\SeededCanaryTestCase and Testing\PhpRun, and the bundle class KeboolaOpenTelemetryBundle;
  • the keys of the Symfony configuration and the service ids of the bundle;
  • the names of the environment variables and php.ini settings of the package, KBC_OTEL_*.

Design decisions

Every design decision, with its reasons, is a record in docs/decisions/.

Development

See AGENTS.md: the commands for the Docker image, the tests and the checks.

License

MIT licensed, see LICENSE file.