invoitrade/otel-common-php

Unified OpenTelemetry logging, tracing, and metrics library for PHP (Compatible with C# Common_lib approach)

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/invoitrade/otel-common-php

dev-master 2026-02-17 09:49 UTC

This package is not auto-updated.

Last update: 2026-02-18 08:14:15 UTC


README

Unified OpenTelemetry logging, tracing, and metrics library for PHP Compatible with C# Common_lib approach

PHP Version License

๐ŸŽฏ Features

  • โœ… Unified Logging: Monolog-based logging with OpenTelemetry integration
  • โœ… OTLP Export: Direct export to OpenTelemetry Collector via OTLP/HTTP
  • โœ… OpenSearch Compatible: Log format compatible with OpenSearch/Elasticsearch
  • โœ… C# Common_lib Compatibility: Same index structure and namespace conventions
  • โœ… Framework Integration: Laravel Service Provider included
  • โœ… PSR-3 Compatible: Standard PHP logger interface
  • โœ… Multi-version PHP: Supports PHP 8.1, 8.2, 8.3

๐Ÿ“ฆ Installation

composer require invoitrade/otel-common-php

๐Ÿš€ Quick Start

Vanilla PHP

<?php
require 'vendor/autoload.php';

use Invoitrade\OtelCommon\Configuration\OtelConfig;
use Invoitrade\OtelCommon\OtelLogger;

// Create configuration
$config = OtelConfig::fromEnv(); // From environment variables

// Or with custom config
$config = new OtelConfig([
    'service' => [
        'name' => 'my-php-app',
        'version' => '1.0.0',
    ],
    'otlp' => [
        'endpoint' => 'http://localhost:4318',
    ],
]);

// Create logger
$logger = new OtelLogger($config);

// Start logging!
$logger->info('Application started', [
    'user_id' => 123,
]);

$logger->error('Database error', [
    'query' => 'SELECT * FROM users',
    'error' => 'Connection timeout',
]);

๐Ÿ”ง Laravel Integration

1. Register Service Provider

// config/app.php
'providers' => [
    // ...
    \Invoitrade\OtelCommon\Integrations\Laravel\OtelServiceProvider::class,
],

2. Publish Configuration

php artisan vendor:publish --provider="Invoitrade\OtelCommon\Integrations\Laravel\OtelServiceProvider"

3. Configure Environment

# .env
OTEL_SERVICE_NAME=my-laravel-app
OTEL_SERVICE_VERSION=1.0.0
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
LOG_LEVEL=info

4. Use in Controllers

use Invoitrade\OtelCommon\OtelLogger;

class UserController extends Controller
{
    public function __construct(private OtelLogger $logger)
    {
    }

    public function store(Request $request)
    {
        $this->logger->info('User creation requested', [
            'data' => $request->all(),
        ]);

        // Business logic...

        $this->logger->info('User created', ['user_id' => $user->id]);

        return response()->json($user);
    }
}

โš™๏ธ Configuration

Environment Variables

Variable Default Description
OTEL_SERVICE_NAME php-app Service name
OTEL_SERVICE_VERSION 1.0.0 Service version
OTEL_SERVICE_NAMESPACE (auto) Service namespace
OTEL_DEPLOYMENT_ENVIRONMENT production Environment (prod/dev/staging)
OTEL_EXPORTER_OTLP_ENABLED true Enable OTLP export
OTEL_EXPORTER_OTLP_ENDPOINT http://localhost:4318 OTLP Collector endpoint
LOG_LEVEL info Log level (debug/info/warning/error)
LOG_FILE_ENABLED false Enable file logging
LOG_CONSOLE_ENABLED true Enable console logging

Configuration via Code

$config = new OtelConfig([
    'service' => [
        'name' => 'my-app',
        'version' => '2.0.0',
        'namespace' => 'MyCompany.MyApp',
    ],
    'deployment' => [
        'environment' => 'staging',
    ],
    'otlp' => [
        'enabled' => true,
        'endpoint' => 'http://otel-collector:4318',
        'timeout' => 10,
    ],
    'logging' => [
        'level' => 'debug',
        'file_enabled' => true,
        'file_path' => '/var/log/app/app.log',
    ],
]);

๐Ÿ“Š Log Format

Logs are formatted for OpenSearch/Elasticsearch with C# Common_lib compatibility:

{
  "@timestamp": "2024-02-12T10:30:45.123456+00:00",
  "service": {
    "name": "my-php-app",
    "version": "1.0.0",
    "namespace": "MyPhpApp"
  },
  "deployment": {
    "environment": "production"
  },
  "host": {
    "name": "web-server-01",
    "ip": "192.168.1.100"
  },
  "level": "INFO",
  "message": "User logged in",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "span_id": "00f067aa0ba902b7",
  "context": {
    "user_id": 123,
    "action": "login"
  },
  "_index": "otel-logs-2024.02.12"
}

Index Naming Convention

OpenSearch compatible format:

otel-logs-{YYYY.MM.DD}

Index Pattern: otel-logs-*

Examples:

  • otel-logs-2024.02.12
  • otel-logs-2024.02.13

Service identification is done through service.name, service.namespace, and deployment.environment fields within the log document.

๐Ÿ”— OpenTelemetry Integration

Trace Context

// Log with trace context
$logger->logWithTrace(
    'info',
    'Processing payment',
    $traceId,  // from OpenTelemetry context
    $spanId,   // from OpenTelemetry context
    ['amount' => 100.50]
);

Exception Logging

try {
    // ...
} catch (\Throwable $e) {
    $logger->logException($e, 'error', [
        'user_id' => $userId,
        'context' => 'payment_processing',
    ]);
}

๐ŸŽจ Advanced Usage

Custom Handlers

use Monolog\Handler\StreamHandler;

$logger = new OtelLogger($config);
$monolog = $logger->getMonolog();

// Add custom handler
$monolog->pushHandler(new StreamHandler('custom.log'));

Custom Processors

$monolog->pushProcessor(function ($record) {
    $record->extra['custom_field'] = 'custom_value';
    return $record;
});

๐Ÿ”„ Comparison with C# Common_lib

Feature C# Common_lib PHP OtelCommon
Logger Serilog Monolog
Config appsettings.json OtelConfig / .env
DI Microsoft.Extensions.DI PSR-11 / Laravel Container
Tracing OpenTelemetry.API Monolog context
Exporter OTLP HTTP OTLP HTTP
Index Format otel-logs-{date} โœ… otel-logs-*
Namespace Service.Namespace โœ… Same (auto-derived)
PSR Compliance - โœ… PSR-3

๐Ÿ“š Examples

See examples/ directory for:

๐Ÿงช Testing

# Run tests
composer test

# Run with coverage
composer test:coverage

# Static analysis
composer analyse

# Code style check
composer cs:check

# Code style fix
composer cs:fix

๐Ÿ› ๏ธ Development

# Clone repository
git clone https://github.com/invoitrade/otel-common-php.git
cd otel-common-php

# Install dependencies
composer install

# Run tests
composer test

๐Ÿ“– Requirements

  • PHP 8.1, 8.2, or 8.3
  • Composer 2.x
  • OpenTelemetry Collector (for OTLP export)
  • OpenSearch/Elasticsearch (optional, for log storage)

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

๐Ÿ“„ License

MIT License. See LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Built on top of Monolog
  • OpenTelemetry Protocol specification
  • Inspired by C# Common_lib architecture

๐Ÿ“ž Support

Made with โค๏ธ for unified observability across C# and PHP applications