summaryrefslogtreecommitdiff
path: root/vendor/open-telemetry/context/README.md
blob: 4dfe0e23f78b4e7b1753a844960dd7df52bb5c0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
[![Releases](https://img.shields.io/badge/releases-purple)](https://github.com/opentelemetry-php/context/releases)
[![Source](https://img.shields.io/badge/source-context-green)](https://github.com/open-telemetry/opentelemetry-php/tree/main/src/Context)
[![Mirror](https://img.shields.io/badge/mirror-opentelemetry--php:context-blue)](https://github.com/opentelemetry-php/context)
[![Latest Version](http://poser.pugx.org/open-telemetry/context/v/unstable)](https://packagist.org/packages/open-telemetry/context/)
[![Stable](http://poser.pugx.org/open-telemetry/context/v/stable)](https://packagist.org/packages/open-telemetry/context/)

# OpenTelemetry Context

Immutable execution scoped propagation mechanism, for further details see [opentelemetry-specification][1].

## Installation

```shell
composer require open-telemetry/context
```

## Usage

### Implicit propagation

```php
$context = Context::getCurrent();
// modify context
$scope = $context->activate();
try {
    // run within new context
} finally {
    $scope->detach();
}
```

It is recommended to use a `try-finally` statement after `::activate()` to ensure that the created scope is properly `::detach()`ed.

## Async applications

### Fiber support

Requires `PHP >= 8.1`, an NTS build, `ext-ffi`, and setting the environment variable `OTEL_PHP_FIBERS_ENABLED` to a truthy value. Additionally `vendor/autoload.php` has to be preloaded for non-CLI SAPIs if [`ffi.enable`](https://www.php.net/manual/en/ffi.configuration.php#ini.ffi.enable) is set to `preload`.

### Event loops

Event loops have to restore the original context on callback execution. A basic implementation could look like the following, though implementations should avoid keeping unnecessary references to arguments if possible:

```php
function bindContext(Closure $closure): Closure {
    $context = Context::getCurrent();
    return static function (mixed ...$args) use ($closure, $context): mixed {
        $scope = $context->activate();
        try {
            return $closure(...$args);
        } finally {
            $scope->detach();
        }
    };
}
```

## Contributing

This repository is a read-only git subtree split.
To contribute, please see the main [OpenTelemetry PHP monorepo](https://github.com/open-telemetry/opentelemetry-php).

[1]: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/context/README.md#context