PHP code example of kaz29 / cakephp-otel-plugin

1. Go to this page and download the library: Download kaz29/cakephp-otel-plugin library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kaz29 / cakephp-otel-plugin example snippets


$this->addPlugin('OtelInstrumentation');

// config/bootstrap.php or config/app_local.php
use Cake\Core\Configure;

Configure::write('OtelInstrumentation.exclude', [
    // Skip every action on HealthController (health/readiness/liveness probes)
    ['controller' => \App\Controller\HealthController::class, 'action' => '*'],

    // Skip a specific action while leaving others instrumented
    ['controller' => \App\Controller\PostsController::class, 'action' => 'ping'],
]);

// config/bootstrap.php or config/app_local.php
use Cake\Core\Configure;
use OpenTelemetry\API\Trace\SpanKind;

Configure::write('OtelInstrumentation.hooks', [
    // Minimal — span name auto-generated as "App\Service\PaymentService::charge"
    ['class' => \App\Service\PaymentService::class, 'method' => 'charge'],

    // With options
    [
        'class' => \App\Service\PaymentService::class,
        'method' => 'refund',
        'spanName' => 'payment.refund',
        'kind' => SpanKind::KIND_CLIENT,
        'attributes' => ['payment.provider' => 'stripe'],
    ],
]);

// In Application::bootstrap(), before $this->addPlugin('OtelInstrumentation')
use OtelInstrumentation\Instrumentation\CustomInstrumentation;
use OpenTelemetry\API\Trace\SpanKind;

CustomInstrumentation::register(
    \App\Service\PaymentService::class,
    'charge',
    spanName: 'payment.charge',
    kind: SpanKind::KIND_CLIENT,
    attributes: ['payment.provider' => 'stripe'],
    attributeCallback: fn($instance, $params, $class, $function) => [
        'payment.amount' => $params[0] ?? null,
    ],
);

use OtelInstrumentation\Middleware\OtelErrorLoggingMiddleware;

public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
    $middlewareQueue
        ->add(new ErrorHandlerMiddleware())
        ->add(new OtelErrorLoggingMiddleware())
        // ...
    ;
}

$logger = new \OtelInstrumentation\Log\TraceAwareLogger($existingPsr3Logger);
bash
OTEL_PHP_AUTOLOAD_ENABLED=true
OTEL_SERVICE_NAME=my-cakephp-app
OTEL_TRACES_EXPORTER=otlp
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318