### Install using PECL Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/QUICKSTART.md Install the OpenTelemetry PHP extension using PECL. ```bash pecl install opentelemetry ``` -------------------------------- ### Install OpenTelemetry using php-extension-installer (PECL/Pickle) Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/README.md Install the OpenTelemetry extension using the php-extension-installer with PECL or Pickle, specifying the desired release channel. ```shell install-php-extensions opentelemetry[-beta|-stable|-latest] ``` -------------------------------- ### Install using Docker Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/QUICKSTART.md Install the OpenTelemetry PHP extension in a Docker container using php-extension-installer. ```dockerfile FROM php:8.3 RUN install-php-extensions opentelemetry ``` -------------------------------- ### Install OpenTelemetry using php-extension-installer (GitHub) Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/README.md Install the OpenTelemetry extension from GitHub using the php-extension-installer script, typically used with official PHP Docker images. ```shell install-php-extensions opentelemetry-php/ext-opentelemetry@main ``` -------------------------------- ### Basic Pre-Hook Example Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Demonstrates a basic pre-hook to log function entry and arguments before execution. ```php .php at line X // Arguments: ["John",30] // Processing: John (30 years old) ``` -------------------------------- ### Basic Pre-Hook Example Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Demonstrates a basic pre-hook to log function entry and arguments. ```APIDOC ## Basic Pre-Hook ### Description This example shows how to use a pre-hook to log information before a function is executed. ### Method `OpenTelemetry\Instrumentation\hook` ### Parameters - `pre`: A callable function executed before the target function. - `target`: The function to hook (e.g., 'my_function'). ### Request Example ```php ``` ### Response Example ``` Entering function: my_function in file .php at line X Arguments: ["John",30] Processing: John (30 years old) ``` ``` -------------------------------- ### Start gdbserver inside Docker Container Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/DEVELOPMENT.md Initializes the extension build process within the container and starts gdbserver to listen for debugger connections. ```shell phpize ./configure make gdbserver :2345 php -d extension=$(pwd)/modules/opentelemetry.so /path/to/file.php ``` -------------------------------- ### Install opentelemetry via Docker Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/INDEX.md Use this command within a Dockerfile to install the opentelemetry extension. ```dockerfile RUN install-php-extensions opentelemetry ``` -------------------------------- ### Examples of Hookable Built-in Functions Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hooking-function-types.md Provides examples of hooking various built-in PHP functions including string, array, math, and type functions using pre-callbacks. Ensure PHP 8.2+ is used. ```php echo "strlen({$p[0]})\n"); hook(null, 'str_replace', pre: fn($o, $p) => echo "Replacing...\n"); // Array functions hook(null, 'array_filter', pre: fn($o, $p) => echo "Filtering array\n"); hook(null, 'array_map', pre: fn($o, $p) => echo "Mapping array\n"); // Math functions hook(null, 'abs', pre: fn($o, $p) => echo "Getting absolute\n"); // Type functions hook(null, 'is_array', pre: fn($o, $p) => echo "Type check\n"); ``` -------------------------------- ### Verify OpenTelemetry Extension Installation Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/README.md Run this command to check if the OpenTelemetry extension is installed and enabled in your PHP environment. ```shell php --ri opentelemetry ``` -------------------------------- ### Minimal php.ini Setup Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/configuration.md Enables the extension and sets basic configuration for manual hooks only. Ensure `opentelemetry.conflicts` is empty if no conflicts are expected. ```ini ; php.ini extension=opentelemetry.so opentelemetry.conflicts = "" opentelemetry.validate_hook_functions = On opentelemetry.allow_stack_extension = Off opentelemetry.attr_hooks_enabled = Off ``` -------------------------------- ### Run Docker Container for gdbserver Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/DEVELOPMENT.md Starts a Docker container, mapping the current directory to the container's filesystem and exposing a port for gdbserver. ```shell docker run --rm -it -p "2345:2345" -v $(pwd)/ext:/usr/src/myapp otel:8.2.11 bash ``` -------------------------------- ### Custom Handler Example Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/configuration.md Provides an example of custom pre and post handler classes and methods for managing spans with #[WithSpan] attributes. Ensure the handler signature matches the expected format. ```php spanBuilder($span_name) ->setSpanKind($span_kind) ->startSpan(); // Add attributes foreach ($span_attributes ?? [] as $key => $value) { $span->setAttribute($key, $value); } // Attach to context $scope = Context::storage()->attach($span->storeInContext(Context::getCurrent())); return null; // Don't modify parameters } public static function after( object|string|null $object, array $params, mixed $returnValue, ?Throwable $exception ): mixed { // Get and end span $scope = Context::storage()->scope(); $scope?->detach(); if ($scope) { $span = Span::fromContext($scope->context()); if ($exception) { $span->recordException($exception); $span->setStatus(StatusCode::STATUS_ERROR); } else { $span->setStatus(StatusCode::STATUS_OK); } $span->end(); } return $returnValue; } } ``` -------------------------------- ### Hook Registration Failed Example Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/errors.md Demonstrates a scenario where `hook()` returns `false` because a hook is already registered on the target function. Ensure hooks are registered early and only once per function. ```php null); $result = hook(null, 'my_function', post: fn() => null); var_dump($result); // bool(false) - hook already registered function my_function() {} ``` -------------------------------- ### Hooking an Instance Method Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Register a pre-hook for an instance method. The `$object` parameter will be an instance of the hooked class. This example shows how to log the user's name before creating a user. ```php class UserService { public function createUser(string $name, string $email) { /* ... */ } } OpenTelemetry\Instrumentation\hook( UserService::class, 'createUser', pre: function(UserService $user, array $params) { echo "Creating user: " . $params[0]; // name } ); ``` -------------------------------- ### Hook a Static Method Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/QUICKSTART.md Register a pre-hook for a static method of a class. This example hooks the 'hash' static method of the 'Utils' class. ```php 0) { return deep_recursion($n - 1, $hook_payload_size); } // Near end of recursion, hook tries to add 50 parameters return $hook_payload_size; } ``` -------------------------------- ### Error Handling with Post-Hook Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/INDEX.md The `post` callback can inspect the `Throwable` argument to handle exceptions thrown by the target method. This example logs query failures. ```php getMessage()); } return $result; } ); ``` -------------------------------- ### Usage of WithSpan Attribute Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/types.md Demonstrates how to apply the `WithSpan` attribute to class methods for automatic OpenTelemetry span generation. Shows examples with default span naming and with custom span names, kinds, and attributes. ```php 'users'])] public function createUser(string $name) { // Span with custom name, kind, and static attributes return new User(0, $name); } } ``` -------------------------------- ### Hooking Dynamically Named Functions (Unreliable Example) Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hooking-function-types.md Demonstrates an unreliable method for hooking functions with dynamically determined names. This approach may fail if the function is called before the hook is registered. ```php null); // The function might already be called before hook registration call_user_func($function_name); ``` -------------------------------- ### Hooking Methods with Variadic Parameters Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hooking-function-types.md Functions with variadic parameters (`...$args`) pass all arguments as an array to the hook. This example shows how to hook a method that accepts a variable number of arguments. ```php format('a', 'b', 'c', 'd'); // Output: Formatting 4 values ``` -------------------------------- ### Hooking a Static Method Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Register a pre-hook for a static method. The `$object` parameter will be a string containing the class name. This example logs the class name from which the static method was called. ```php OpenTelemetry\Instrumentation\hook( UserService::class, 'validateEmail', pre: function(string $class, array $params) { echo "Called from: $class"; // "UserService" } ); ``` -------------------------------- ### Handle Undefined Attribute Handler Warning Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/errors.md This example demonstrates how to trigger and fix an 'Undefined attribute handler' warning. It shows the configuration that causes the warning and how to correct it by specifying a valid handler. ```php work(); // Warning: Handler "NonExistent\Handler::pre" not found ``` ```php process('hello'); var_dump($output); // Output: // Processing data: hello // Result: HELLO // string(17) "HELLO [processed]" ``` -------------------------------- ### Invalid Hook Signature Examples Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/errors.md Illustrates incorrect hook parameter signatures that will cause errors when `opentelemetry.validate_hook_functions` is enabled. These examples show common mismatches between expected parameter types and actual function arguments. ```php null); // INVALID: hook expects int, but class is a string for static methods hook('Service', 'method', pre: fn(int $x, $params) => null); ``` -------------------------------- ### Time Function Execution Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/QUICKSTART.md Measure the execution time of a function. Records the start time before execution and logs the duration after completion. ```php _start_time = microtime(true); }, post: function($obj, $params, $result) { $duration = microtime(true) - ($obj->_start_time ?? 0); error_log("Took {$duration}s"); return $result; } ); ``` -------------------------------- ### Run All Tests Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/CLAUDE.md Executes all tests for the extension in the PHPT format. This command is used for comprehensive testing. ```bash make test ``` -------------------------------- ### Run Test with gdb or Valgrind using Script Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/DEVELOPMENT.md Executes a specific test case using a generated .sh script, with options to run under gdb or valgrind. ```shell tests/name_of_test.sh gdb # will start gdb tests/name_of_test.sh valgrind # will run test and display valgrind report ``` -------------------------------- ### Modifying Exceptions in Post-Hooks Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Shows how post-hooks can replace or transform original exceptions by throwing a new exception. This example specifically transforms a RuntimeException into a LogicException. ```php hook(null, 'risky_operation', post: function($obj, $params, $ret, ?Throwable $ex) { if ($ex instanceof RuntimeException) { throw new LogicException('Custom error', previous: $ex); } }); ``` -------------------------------- ### Build Extension from Source Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/DEVELOPMENT.md Compiles the OpenTelemetry extension from its source code using standard PHP extension build tools. ```shell $ phpize $ ./configure $ make $ make test $ make install $ make clean ``` -------------------------------- ### Hooking First-Class Callables Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hooking-function-types.md First-class callables (PHP 8.1+) can be hooked like regular methods. This example demonstrates hooking a method that is then assigned to a first-class callable. ```php echo "Processing\n"); $service = new Service(); $callable = $service->process(...); // First-class callable $result = $callable('hello'); // Output: Processing ``` -------------------------------- ### Hooking Instance Methods Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Explains how to hook methods on class instances. ```APIDOC ## Hooking Instance Methods ### Description This example demonstrates how to apply hooks to instance methods of a class. ### Method `OpenTelemetry\Instrumentation\hook` ### Parameters - `target`: The class name (e.g., `DataProcessor::class`). - `method`: The method name (e.g., 'process'). - `pre`: A callable for pre-hook logic. - `post`: A callable for post-hook logic. ### Request Example ```php process('hello'); var_dump($output); ?> ``` ### Response Example ``` Processing data: hello Result: HELLO string(17) "HELLO [processed]" ``` ``` -------------------------------- ### Hooking Static Methods Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Demonstrates how to hook static methods on a class. ```php findUser(123); // Output: Looking for user ID: 123 ``` -------------------------------- ### Hooking a Static Method Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hooking-function-types.md Demonstrates how to hook a static method. The first parameter in pre/post hooks for static methods is a string containing the class name. ```php strtoupper($params[0])]; } ); ``` -------------------------------- ### Hooking an Internal Function (PHP 8.2+) Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Register a pre-hook for a built-in PHP function, available in PHP 8.2 and later. This example logs the number of arguments passed to `array_map`. ```php OpenTelemetry\Instrumentation\hook( null, 'array_map', pre: function(null $obj, array $params) { echo "array_map called with " . count($params) . " args"; } ); ``` -------------------------------- ### Enable Extension via Command Line Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/DEVELOPMENT.md Temporarily enables the OpenTelemetry extension for the current PHP execution. ```shell $ php -dextension=opentelemetry -m ``` -------------------------------- ### Build Docker Image Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/CLAUDE.md Builds the Docker image used for development and testing. This is the primary workflow command. ```bash make build-image ``` -------------------------------- ### Build Extension from Source Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/CLAUDE.md Manually builds the extension from source code. Requires PHP debug build or execution within a Docker container. ```bash phpize && ./configure && make ``` -------------------------------- ### Hooks Apply to All Instances Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hooking-function-types.md Hooks defined for a class apply to all instances of that class. This example shows how a post hook logs the incremented count for separate instances of the Counter class. ```php count++; return $this->count; } } hook( Counter::class, 'increment', post: function(Counter $counter, $params, int $result): int { echo "Counter now: {$result}\n"; return $result; } ); $c1 = new Counter(); $c2 = new Counter(); $c1->increment(); // Output: Counter now: 1 $c1->increment(); // Output: Counter now: 2 $c2->increment(); // Output: Counter now: 1 (separate instance) ``` -------------------------------- ### Modify Instance Properties via Hooks Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hooking-function-types.md Pre and post hooks can be used to read and modify instance properties. This example demonstrates adding a header to a Request instance before its execution. ```php headers['X-Trace-ID'] = uniqid(); } ); class Request { public $headers = []; public function execute() { return $this->headers; } } $request = new Request(); $result = $request->execute(); var_dump($result); // Output: array(1) { ["X-Trace-ID"] => string(13) "..." } ``` -------------------------------- ### Build Extension via Docker Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/CLAUDE.md Compiles the OpenTelemetry PHP extension using the Docker image. Ensure the Docker image is built first. ```bash make build ``` -------------------------------- ### Hooking Static Methods Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Illustrates how to hook static methods of a class. ```APIDOC ## Hooking Static Methods ### Description This example shows how to apply hooks to static methods of a class. ### Method `OpenTelemetry\Instrumentation\hook` ### Parameters - `target`: The class name (e.g., `Validator::class`). - `method`: The method name (e.g., 'email'). - `pre`: A callable for pre-hook logic. - `post`: A callable for post-hook logic. ### Request Example ```php ``` ### Response Example ``` Validating email from class: Validator Result: valid ``` ``` -------------------------------- ### Pre-Hook: Modify Parameters Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/QUICKSTART.md Modify function parameters using a pre-hook. The hook must return an array of the modified parameters. This example modifies and adds parameters for the 'process' function. ```php strtoupper($params[0]), // Modify first parameter 1 => $params[1] * 2, // Modify second parameter 2 => 'new_param', // Add new parameter ]; } ); function process($name, $value = 0, $extra = null) { echo "$name: $value, $extra\n"; } process('hello', 5); // Output: HELLO: 10, new_param ``` -------------------------------- ### Build and Run Tests in Docker Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/DEVELOPMENT.md Builds the Debian Docker image and runs all extension tests within the container. ```shell PHP_VERSION=8.2.8 docker compose build debian PHP_VERSION=8.2.8 docker compose run debian phpize ./configure make clean make make test ``` -------------------------------- ### Basic Return Value Modification Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/return-value-modification.md Declare a return type in the post-hook closure to modify a function's return value. This example adds 10% tax to the calculated price. ```php = 80200) { OpenTelemetry\Instrumentation\hook( null, 'array_filter', pre: function($obj, array $params) { echo "Filtering array with " . count($params[0]) . " items\n"; } ); $result = array_filter([1, 2, 3, 4], fn($x) => $x > 2); // Output: Filtering array with 4 items } ``` -------------------------------- ### Hooking a Global Function Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Register a pre-hook for a global function. Pass `null` for the class name, and the `$object` parameter in the hook will also be `null`. This example logs the second argument of `str_replace`. ```php OpenTelemetry\Instrumentation\hook( null, 'str_replace', pre: function(null $obj, array $params) { echo "Replacing: " . $params[1]; } ); ``` -------------------------------- ### Run Test with Valgrind Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/CLAUDE.md Executes a specific PHPT test file under Valgrind to detect memory errors. Replace `.phpt` with the actual test file name. ```bash php run-tests.php -d extension=$(pwd)/modules/opentelemetry.so -m tests/.phpt ``` -------------------------------- ### Return Type Requirement for Modification Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/return-value-modification.md The post-hook must declare a return type for the modification to take effect. The WRONG example shows a modification being ignored due to the absence of a return type. ```php $value * 2); // CORRECT: return type declared hook(null, 'double', post: fn($obj, $params, $value): int => $value * 2); function double($x) { return $x; } double(5); // WRONG version: returns 5 (modification ignored) // CORRECT version: returns 10 (modification applied) ``` -------------------------------- ### Verify OpenTelemetry Extension and Configuration Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/configuration.md Use this command to check if the opentelemetry extension is loaded and to view its current configuration settings. Look for 'enabled' hooks and specific directive values. ```bash php --ri opentelemetry ``` -------------------------------- ### Recording Exceptions in Post-Hook Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Demonstrates how to handle and log exceptions thrown by a hooked function within a post-hook. ```php getMessage()); // Optionally rethrow, transform, or suppress the exception } } ); function risky_operation($input) { if ($input < 0) { throw new InvalidArgumentException('Input must be positive'); } return $input * 2; } try { risky_operation(-5); } catch (InvalidArgumentException $e) { echo "Caught: " . $e->getMessage() . "\n"; } // Output: Function threw: Input must be positive // Caught: Input must be positive ``` -------------------------------- ### Exception Thrown in Pre-Hook Example Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/errors.md Illustrates a scenario where an exception is thrown within a pre-hook closure. The exception is caught, logged as a warning, and the original function `risky_operation` still executes and returns its value. ```php .phpt` with the actual test file name. ```bash php run-tests.php -d extension=$(pwd)/modules/opentelemetry.so tests/.phpt ``` -------------------------------- ### Hooking a Class Method with OpenTelemetry Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/README.md Use the `hook` function to instrument a specific method of a class. The `pre` callback starts a span and attaches it to the context, while the `post` callback detaches the scope, records any exceptions, sets the status, and ends the span. Ensure hooks are registered before the function is first executed. ```php spanBuilder($class) ->startSpan(); Context::storage()->attach($span->storeInContext(Context::getCurrent())); }, post: static function (DemoClass $demo, array $params, $returnValue, ?Throwable $exception) use ($tracer) { $scope = Context::storage()->scope(); $scope?->detach(); $span = Span::fromContext($scope->context()); $exception && $span->recordException($exception); $span->setStatus($exception ? StatusCode::STATUS_ERROR : StatusCode::STATUS_OK); $span->end(); } ); ``` -------------------------------- ### Hooking Built-in Functions (PHP 8.2+) Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Demonstrates hooking built-in PHP functions, requiring PHP 8.2 or later. ```APIDOC ## Hooking Built-in Functions (PHP 8.2+) ### Description This example shows how to hook built-in PHP functions, which is supported from PHP 8.2 onwards. ### Method `OpenTelemetry\Instrumentation\hook` ### Parameters - `target`: `null` for built-in functions. - `method`: The name of the built-in function (e.g., 'array_filter'). - `pre`: A callable for pre-hook logic. ### Request Example ```php = 80200) { OpenTelemetry\Instrumentation\hook( null, 'array_filter', pre: function($obj, array $params) { echo "Filtering array with " . count($params[0]) . " items\n"; } ); $result = array_filter([1, 2, 3, 4], fn($x) => $x > 2); } ?> ``` ### Response Example ``` Filtering array with 4 items ``` ``` -------------------------------- ### Run All Tests with Valgrind Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/DEVELOPMENT.md Executes all extension tests while enabling Valgrind for memory leak detection. ```shell php run-tests.php -d extension=$(pwd)/modules/opentelemetry.so -m ``` -------------------------------- ### Enable Extension in php.ini Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/QUICKSTART.md Enable the OpenTelemetry extension by adding it to your php.ini configuration. ```ini extension=opentelemetry.so ``` -------------------------------- ### Configuration for Custom Handlers Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/attribute-based-hooks.md Configure custom pre-handler and post-handler functions by specifying their fully qualified names in the php.ini configuration file. Ensure attribute hooks are enabled. ```ini opentelemetry.attr_pre_handler_function = "MyNamespace\TraceHandler::before" opentelemetry.attr_post_handler_function = "MyNamespace\TraceHandler::after" opentelemetry.attr_hooks_enabled = On ``` -------------------------------- ### Enable Extension via .ini File Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/DEVELOPMENT.md Persistently enables the OpenTelemetry extension by creating or appending to a PHP configuration file. ```shell $ echo 'extension=opentelemetry' > $(php-config --ini-dir)/opentelemetry.ini ``` -------------------------------- ### Enable Stack Extension (INI) Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/QUICKSTART.md Enable the stack extension in the PHP configuration to allow adding more than 16 parameters to hooks. ```ini opentelemetry.allow_stack_extension = On ``` -------------------------------- ### Recording Exceptions in Post-Hook Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hook.md Demonstrates how to handle and log exceptions thrown by a function within a post-hook. ```APIDOC ## Recording Exceptions in Post-Hook ### Description This example shows how to detect and log exceptions that occur during a function's execution using a post-hook. ### Method `OpenTelemetry\Instrumentation\hook` ### Parameters - `post`: A callable function that receives the exception object if one occurred. - `target`: The function to hook (e.g., 'risky_operation'). ### Request Example ```php getMessage()); // Optionally rethrow, transform, or suppress the exception } } ); function risky_operation($input) { if ($input < 0) { throw new InvalidArgumentException('Input must be positive'); } return $input * 2; } try { risky_operation(-5); } catch (InvalidArgumentException $e) { echo "Caught: " . $e->getMessage() . "\n"; } ?> ``` ### Response Example ``` Function threw: Input must be positive Caught: Input must be positive ``` ``` -------------------------------- ### Format Code (Debian) Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/CLAUDE.md Applies clang-format to C and H files for code style consistency on Debian-based Docker images. Run before committing. ```bash make format ``` -------------------------------- ### Logging and Passthrough of Function Parameters Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/parameter-modification.md Employ the `hook` function with a `pre` callback to log function parameters before execution without altering them. The `pre` callback returns `null` to indicate that the original parameters should be passed through. ```php echo 'OK'); func();" ``` -------------------------------- ### Enable Stack Extension for Pre-hooks Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/configuration.md Allow pre-hooks to add more than 16 arguments to a function call by enabling stack extension. This may have a performance impact if heavily used. ```ini opentelemetry.allow_stack_extension = On ``` ```php echo "Call via __call\n"); hook(DynamicService::class, '__callStatic', pre: fn($o, $p) => echo "Call via __callStatic\n"); $service = new DynamicService(); $service->unknown_method(); // Output: Call via __call DynamicService::unknown_static(); // Output: Call via __callStatic ``` -------------------------------- ### Hook Instance Method with First Parameter as Instance Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/_autodocs/api-reference/hooking-function-types.md In pre/post hooks for instance methods, the first parameter passed to the hook callback is the instance object itself. This allows direct access to the instance's properties and methods. ```php level] $message\n"; } } hook( Logger::class, 'log', pre: function(Logger $logger, array $params) { // $logger is the actual Logger instance echo "Current level: {$logger->level}\n"; echo "Message: {$params[0]}\n"; } ); $logger = new Logger(); $logger->log('Test message'); // Output: // Current level: INFO // Message: Test message // [INFO] Test message ``` -------------------------------- ### Debug with lldb Source: https://github.com/open-telemetry/opentelemetry-php-instrumentation/blob/main/DEVELOPMENT.md Launches the PHP executable with lldb for debugging, targeting a specific PHP binary compiled in debug mode. ```shell lldb -- $HOME/php-bin/DEBUG/bin/php test.php ```