PHP code example of gilbitron / canonical-context-logging

1. Go to this page and download the library: Download gilbitron/canonical-context-logging 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/ */

    

gilbitron / canonical-context-logging example snippets


use CanonicalContextLogging\Context\SingletonStorage;
use CanonicalContextLogging\Exporter\OtlpExporter;
use CanonicalContextLogging\Logger\CanonicalLogger;
use CanonicalContextLogging\Middleware\RequestMiddleware;

// Setup - OTLP exporter reads from environment variables by default
// Set OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
$storage = new SingletonStorage();
$exporter = new OtlpExporter(); // Reads config from environment
$logger = new CanonicalLogger(
    exporter: $exporter,
    slowRequestThreshold: 1.0, // Log requests slower than 1 second
    sampleRate: 0.1 // Sample 10% of normal requests
);
$middleware = new RequestMiddleware($storage, $logger);

// Start request
$context = $middleware->start();
$context->setService('my-service', '1.0.0');
$context->addContext('user_id', 123);
$context->addContext('org_id', 456);

// ... your application logic ...

// End request
$context->setStatus(200);
$context->setDuration(0.123);
$middleware->end($context);

try {
    $context = $middleware->start();
    $context->setService('my-service', '1.0.0');

    // ... application logic ...

    $context->setStatus(200);
} catch (\Throwable $e) {
    $context->setError($e);
    $context->setStatus(500);
} finally {
    $context->setDuration($context->getDuration());
    $middleware->end($context);
}

use CanonicalContextLogging\Exporter\ConsoleExporter;

// Output to stderr with pretty printing
$exporter = new ConsoleExporter(useStderr: true, prettyPrint: true);

// Output to stdout, compact JSON
$exporter = new ConsoleExporter(useStderr: false, prettyPrint: false);

use CanonicalContextLogging\Exporter\OtlpExporter;
use CanonicalContextLogging\Exporter\OtlpConfig;

// Option 1: Use environment variables (recommended)
$exporter = new OtlpExporter(); // Reads from environment

// Option 2: Explicit configuration
$config = OtlpConfig::create(
    endpoint: 'https://otel-collector:4318',
    protocol: 'http/protobuf',
    headers: ['Authorization' => 'Bearer ' . $apiKey],
    timeout: 10
);
$exporter = new OtlpExporter($config);

use CanonicalContextLogging\Exporter\FileExporter;

// Compact JSON (default)
$exporter = new FileExporter('/var/log/app.jsonl');

// Pretty-printed JSON
$exporter = new FileExporter('/var/log/app.jsonl', prettyPrint: true);

use CanonicalContextLogging\Exporter\ExporterInterface;

class CustomExporter implements ExporterInterface
{
    public function export(array $data): void
    {
        // Your custom export logic
    }
}

use CanonicalContextLogging\Logger\CanonicalLogger;

$logger = new CanonicalLogger(
    exporter: $exporter,
    slowRequestThreshold: 1.0, // Always log requests slower than 1 second
    sampleRate: 0.1 // Sample 10% of normal requests (0.0 to 1.0)
);

use CanonicalContextLogging\Context\SingletonStorage;

$storage = new SingletonStorage();

$context = new EventContext();

// Initialize request
$context->startRequest($traceId, $spanId);

// Service metadata
$context->setService('my-service', '1.0.0');

// Business context (user, org, plan, feature flags, etc.)
$context->addContext('user_id', 123);
$context->addContext('org_id', 456);
$context->addContext('plan', 'premium');
$context->addContext('feature_flags', ['feature_a', 'feature_b']);

// Or add multiple at once
$context->addContexts([
    'user_id' => 123,
    'org_id' => 456,
    'plan' => 'premium',
]);

// Error handling
$context->setError($exception);

// HTTP status
$context->setStatus(200);

// Duration (auto-calculated if not set)
$context->setDuration(0.123);

// Export as array for JSON encoding
$data = $context->toArray();
bash
export OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer token123"
export OTEL_EXPORTER_OTLP_TIMEOUT=10