Compare commits

...

385 Commits
0.0.14 ... main

Author SHA1 Message Date
Brett McBride 4274371493
update DebugScope error message (#1688)
Make the scope id in error messages consistent between the detached-with-error and not-detached cases,
by using spl_object_id($this) in the latter to match the former.
2025-08-13 11:12:00 +10:00
dependabot[bot] 49aca4a36f
Bump github/codeql-action from 3.29.7 to 3.29.8 (#1686)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.29.7 to 3.29.8.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](51f77329af...76621b61de)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.29.8
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-11 09:47:15 -04:00
Brett McBride 87a145a3b6
stabilize LocalRootSpan (#1683) 2025-08-08 09:07:38 +10:00
Brett McBride 9fb9e549bf
adding network semantic conventions (#1682) 2025-08-08 09:07:04 +10:00
Brett McBride d5fd499752
update collector to listen on all interfaces (#1685)
by default, the collector only listens on localhost now, and so is not reachable from
dev containers when running examples
2025-08-08 09:04:16 +10:00
Brett McBride d4c16332af
adding pgsql to developer docker image (#1684) 2025-08-08 09:03:53 +10:00
Chris Lightfoot-Wild 99a35dadf2
Fix psalm regressions. (#1680) 2025-08-06 13:07:06 +10:00
Evan 7981956060
feat(carreirs): implement environment context getter setter (#1668)
* feat(carreirs): implement environment context getter setter

Closes #1566

* tests(carrier): add EnvironmentGetterSetter missing test

* fix(carrier): modify keys empty env condition

* test: use OpenTelemetry\Tests\TestState trait to handle environment

* docs: add trace context and baggage environment carrier example

* refactor: clean up baggage and trace context examples by removing unused span logic

* test: fix Psalm static analysis failures
2025-08-04 13:25:06 +10:00
Brett McBride 9d68afb238
refactor semantic conventions (#1659)
Align with how the spec advises SemConv should be organised, and break unstable
semconvs out into their own directory.
I played around with generating values as enums, but I could only get this to work
if the output was in the same file as the attributes (which would not work well with
composer autoloading), so I've used <attribute>_VALUE_<name>, similar to what we have
now except all in the same file.

* fix linting, broken values containing '.'

* fix incubating namespace

* update semconv readme

* restore ResourceAttributeValues

* adding DNS semconv

* adding db metrics
2025-08-04 13:22:08 +10:00
dependabot[bot] 4afe0aad8a
Bump github/codeql-action from 3.29.3 to 3.29.5 (#1675)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.29.3 to 3.29.5.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](d6bbdef45e...51f77329af)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.29.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-04 13:21:30 +10:00
OpenTelemetry Bot 6d14251299
Add subscript to issue templates (#1677)
Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
2025-08-02 09:06:53 +10:00
Chris Lightfoot-Wild a54f48bbb9
Configuration\CompositeResolver and SPI discovery (#1523)
* Configuration\CompositeResolver can discover additional configuration resolvers via SPI.

* Apply suggestions from code review

Co-authored-by: Tobias Bachert <git@b-privat.de>

* Fix imports.

* Porting EnvSourceProvider changes from Nevay.

* Moved VlucasPhpdotenvProvider to sdk-configuration.

* Added SdkConfigurationResolver.

* Added SymfonyDotenvProvider.

* Removed vlucas/phpdotenv dev package.

* make style 😎

* Update deptrac for dotenv providers.

* Suppress Psalm errors for optional packages.

* Added phpstan ignoreErrors rules for optional dependency behavior.

* Added test for SPI-backed configuration loading via EnvSourceProvider

* Restructure SPI based test for EnvSourceProvider.

* Bumped SPI dependency.

* Added implied mixed return type to ResolverInterface::retrieveValue

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2025-08-01 11:37:37 +10:00
Trask Stalnaker e54a43d262
Fix scorecard checks (#1674) 2025-07-29 21:51:48 +10:00
dependabot[bot] 9c3ae60164
Bump phpDocumentor/phpDocumentor from 3.8.0 to 3.8.1 (#1669)
Bumps [phpDocumentor/phpDocumentor](https://github.com/phpdocumentor/phpdocumentor) from 3.8.0 to 3.8.1.
- [Release notes](https://github.com/phpdocumentor/phpdocumentor/releases)
- [Changelog](https://github.com/phpDocumentor/phpDocumentor/blob/master/CHANGELOG.md)
- [Commits](https://github.com/phpdocumentor/phpdocumentor/compare/v3.8.0...v3.8.1)

---
updated-dependencies:
- dependency-name: phpDocumentor/phpDocumentor
  dependency-version: 3.8.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-22 09:39:38 -04:00
dependabot[bot] 776bed563b
Bump github/codeql-action from 3.29.2 to 3.29.3 (#1670)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.29.2 to 3.29.3.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](181d5eefc2...d6bbdef45e)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.29.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-22 09:39:19 -04:00
Brett McBride 2d9097492c
fixing CI complaints (#1666)
* fixing psalm complaints
use rector (and psalm) to add Override attributes, and add symfony polyfill to
provide Override in earlier php versions

* fixing more psalm complaints

* more fixes

* adding stubs for deptrac
there are some things in our code that deptrac doesn't understand or are missing
for some php versions. stub them to quieten all those violation warnings

* why not cache invalid :(

* display tools versions

* fix tools cache key

* changing cache key

* dont complain about unused psalm suppressions

* suppress invalid attribute

* quieten phpstan php8.5 complaints

* revert previous commit...now other php versions complain about an unused ignore :(

* revert typecasting in metrics aggregators

* Update src/Contrib/Otlp/ProtobufSerializer.php

Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>

* remove override stub and use the polyfill from deptrac

---------

Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>
2025-07-22 11:02:18 +10:00
Brett McBride 2421c64c51
build base image from debian (#1662) 2025-07-11 07:11:46 -04:00
OpenTelemetry Bot dc52549640
Sort contributor listings and remove affiliation from emeriti (#1665)
Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
2025-07-10 09:43:36 +10:00
OpenTelemetry Bot 7033191a74
Add minimum token permissions for all github workflow files (#1655)
* Add minimum token permissions for all github workflow files

* Update .github/workflows/phpdoc-to-github-pages.yml

---------

Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
Co-authored-by: Trask Stalnaker <trask.stalnaker@gmail.com>
2025-07-07 11:29:47 +10:00
dependabot[bot] e27aac84f6
Bump github/codeql-action from 3.29.0 to 3.29.2 (#1656) 2025-07-01 09:00:03 -04:00
Trask Stalnaker 3968f7459a
Update community member listings (#1650)
* Update community member listings

* Update CONTRIBUTING.md

Co-authored-by: Brett McBride <brett.a.mcbride@gmail.com>

* Update CONTRIBUTING.md

Co-authored-by: Brett McBride <brett.a.mcbride@gmail.com>

* Update CONTRIBUTING.md

Co-authored-by: Brett McBride <brett.a.mcbride@gmail.com>

---------

Co-authored-by: Brett McBride <brett.a.mcbride@gmail.com>
2025-06-27 15:06:58 +10:00
Brett McBride 33715fddc1
adding metrics semconv (#1633) 2025-06-23 22:32:27 -04:00
Brett McBride 768c387068
add Logger.Enabled event name parameter (#1632)
extra parameter added in spec 1.45.0, which is optional and development stability
2025-06-20 09:36:51 +10:00
dependabot[bot] 526b8eb33d
Bump phpDocumentor/phpDocumentor from 3.7.1 to 3.8.0 (#1639)
Bumps [phpDocumentor/phpDocumentor](https://github.com/phpdocumentor/phpdocumentor) from 3.7.1 to 3.8.0.
- [Release notes](https://github.com/phpdocumentor/phpdocumentor/releases)
- [Changelog](https://github.com/phpDocumentor/phpDocumentor/blob/master/CHANGELOG.md)
- [Commits](https://github.com/phpdocumentor/phpdocumentor/compare/v3.7.1...v3.8.0)

---
updated-dependencies:
- dependency-name: phpDocumentor/phpDocumentor
  dependency-version: 3.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-18 09:44:45 -04:00
Brett McBride 443c662653
Psr transport network exception test (#1635)
* add test for NetworkException in PsrTransport

* remove unneeded exception expectation
2025-06-18 08:06:04 -04:00
Brett McBride 5ed1ec09db
fixing psalm+phpstan protobuf complaints (#1636) 2025-06-16 21:11:54 +10:00
Tobias Bachert 5451d57dbf
Allows API packages to specify file-based and env-based config (#1621)
* Move `ComponentProvider` and related classes to API

* Use API `ComponentProvider`

* Use API `ComponentProvider` in tests

* Add `EnvComponentLoader` API

* Add `EnvComponentLoader` example

* Ignore deptrac violations

* Remove namespace from `ComponentProvider` BC layer

* Add API requirement to config package

* Fix/suppress unrelated phpstan errors caused by `google/protobuf` `^4.31`
2025-06-16 10:24:51 +10:00
Brett McBride 95229b7bf8
skip segfaulting test on more xdebug versions (#1634)
verified that the bug we experience still exists in xdebug 3.4.4 so lets assume
it will be live for some more releases, and un-skip the test in the future
2025-06-13 20:54:15 +10:00
dependabot[bot] 04acb40874
Bump github/codeql-action from 3.28.19 to 3.29.0 (#1631)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.19 to 3.29.0.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](fca7ace96b...ce28f5bb42)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.29.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-13 13:47:56 +10:00
Brett McBride dcf96ddf96
update weaver to 0.15.2 (#1629) 2025-06-13 09:36:21 +10:00
Bob Strecansky 873a39c4fd
Update Dockerfile (#1625)
chore: Made the update from https://github.com/open-telemetry/opentelemetry-php/pull/1624 strictly for PHP 8.4
2025-06-10 12:12:14 +10:00
Tobias Bachert 07d1da976a
Mark `.instrumentation` as experimental (#1620) 2025-06-10 11:32:38 +10:00
dependabot[bot] 78bd695c02
Bump github/codeql-action from 3.28.18 to 3.28.19 (#1619)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.18 to 3.28.19.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](ff0a06e83c...fca7ace96b)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.19
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-06-04 12:42:55 -04:00
dependabot[bot] 65c2979523
Bump ossf/scorecard-action from 2.4.1 to 2.4.2 (#1616) 2025-06-02 07:03:16 -04:00
Tobias Bachert 38351980a6
Update ratio based sampler threshold algorithm (#1391)
See OTEP 235, Threshold = (1 - Probability) * 2**56.
2025-05-22 12:33:34 +10:00
Shawn Maddock 23c3cdae61
fixes #1600 (#1603) 2025-05-21 08:02:20 -04:00
dependabot[bot] acf6dc7e5b
Bump github/codeql-action from 3.28.17 to 3.28.18 (#1601)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.17 to 3.28.18.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](60168efe1c...ff0a06e83c)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.18
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-20 12:27:55 +10:00
dependabot[bot] 691c0d43ae
Bump fossas/fossa-action from 1.6.0 to 1.7.0 (#1594)
Bumps [fossas/fossa-action](https://github.com/fossas/fossa-action) from 1.6.0 to 1.7.0.
- [Release notes](https://github.com/fossas/fossa-action/releases)
- [Commits](c0a7d013f8...3ebcea1862)

---
updated-dependencies:
- dependency-name: fossas/fossa-action
  dependency-version: 1.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-19 16:34:55 +10:00
Tobias Bachert 2fcafabc81
Catch `TypeError` if `google/protobuf` `^4.31` and `ext-protobuf` `<4.31` are installed (#1598) 2025-05-17 14:39:11 +10:00
Brett McBride 389fa3fd50
support config 0.4 (#1562)
* support opentelemetry/configuration 0.4

* implement resource detectors

* green checks

* implement configurators

* implement resources and detectors

* tidy

* fix include/exclude pattern matching, fix todo

* move attribute processing into a class, add unit tests

* allow null includes, treat as 'include all'

* remove useless noop propagator

* fix cardinality_limits config

* dont reference config in closure

* remove env detector component
per review feedback, we can achieve this with env var substitution in the yaml document

* add memory exporters

* rework composite_list

* improve test

* fix unstable test

* composite_list is string

* revert configurator changes

* enforce mandatory resource attributes

* remove mandatory detector component providers

* remove null attributes + array values

* disabled is required, remove no-op normalization

* rector

* remove duplicate propagators from composite_list

* update semconv schema versions

* fix test

* Apply suggestions from code review

Co-authored-by: Tobias Bachert <git@b-privat.de>

* dont allow attribute removal from mandatory detectors

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2025-05-14 08:46:38 -04:00
Tobias Bachert 5fdfac284a
Use protobuf `PrintOptions` if available (#1593)
Resolves #978
2025-05-12 10:36:35 +10:00
Bob Strecansky f0f5a2a83f
update docker container versions (#1590) 2025-05-12 10:30:54 +10:00
Tobias Bachert b5a5ac79ff
Allow immediate gc of `ContextStorageNode`s after `::detach()` (#1585)
Use dummy object instead of self references as detached-marker to avoid relying on gc cycle collection.

Resolves #1584.
2025-05-08 09:36:50 +10:00
Brett McBride 4851a4e03b
stabilize logger.enabled (#1580)
- update Logger.isEnabled signature to include context and severity number, per spec
- accept event_name on a LogRecord
- add event name to otlp logs payload
- update or remove some comments that were based on the old logs-bridge specification
2025-05-07 08:32:21 -04:00
dependabot[bot] 3679ada34e
Bump github/codeql-action from 3.28.16 to 3.28.17 (#1581)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.16 to 3.28.17.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](28deaeda66...60168efe1c)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.17
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-05 10:01:19 -04:00
Brett McBride 91e05d9f1f
Semconv 1.32.0 (#1577)
* update semconv to 1.32.0
* don't generate semconv for android, cpython, ios
2025-05-05 13:58:53 +10:00
Evan 351aa18abe
implement getAll function in TextMap Extract (#1570)
* implement getAll function in TextMap Extract

* refactor propagation interfaces to introduce ExtendedPropagationGetterInterface

* Refactor getAll method in SanitizeCombinedHeadersPropagationGetter to streamline conditional logic for getter instance check
2025-05-02 11:57:57 +10:00
Bartosz Tomczak 39cd6e2f09
Use timeout to set max_duration on symfony http client (#1575) 2025-05-02 09:20:43 +10:00
Brett McBride ab05329ffe
update resource detectors to align with spec changes (#1573)
PR https://github.com/open-telemetry/opentelemetry-specification/pull/4461 clarifies that some
attributes (service.name, telemetry.*) are mandatory. It also reserves a couple of well-known
detectors names (container, host, process, service) and the attributes they should populate.
Consolidate some of our resource detectors into the built-in ones:
- process-runtime into process, and deprecate
- os into host, and deprecate
- sdk-provided into sdk, and deprecate
- service.name attribute from environment into service detector

Add "mandatory attributes", which is currently service.name, and initially set this to "unknown_service:php"
similar to Java's implementation. Ensure that the composite detector starts with mandatory attributes.

Ensure that "sdk" and "service" detectors are always included from ResourceInfoFactory.

The deprecated detectors are still available, but do not do anything.
2025-05-01 13:37:15 +10:00
dependabot[bot] 821b7543c9
Bump github/codeql-action from 3.28.15 to 3.28.16 (#1571)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.15 to 3.28.16.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](45775bd823...28deaeda66)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.16
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-24 07:37:04 -04:00
Evan e2f24eb494
remove FilteredAttributes and related references (#1565) 2025-04-17 09:39:10 +10:00
Grzegorz Drozd 39a2b486b1
Refactor InMemory exporters to use shared storage manager (#1559)
Introduced `InMemoryStorageManager` to centralize storage management for spans, metrics, and logs. Updated InMemory exporters and their factory classes to utilize this shared storage.

* Add integration test for InMemoryExporter

- add integration test that shows that storage contains metrics
- because of src/SDK/Metrics/MetricReader/ExportingReader.php:148 I had to add `PushMetricExporterInterface` to InMemoryExporter class

* Add integration test for InMemoryExporter
2025-04-15 17:02:07 +10:00
dependabot[bot] e253da3e8b
Bump github/codeql-action from 3.28.12 to 3.28.15 (#1561)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.12 to 3.28.15.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](5f8171a638...45775bd823)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-11 09:20:20 +10:00
OpenTelemetry Bot 64821d89a5
Add ossf-scorecard scanning workflow (#1543)
* Add ossf-scorecard scanning workflow

* Add end of file newline

---------

Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
2025-04-09 23:09:50 +10:00
Grzegorz Drozd fadec4c8da
Fix missing metrics attributes in console exporter (#1558)
This PR fixes a case that when using console exporter for metrics, attributes are not included in the export.
2025-04-08 19:55:41 +10:00
dependabot[bot] d084288a12
Update monolog/monolog requirement from ^2.3 to ^2.3 || ^3.0 (#1551)
* Update monolog/monolog requirement from ^2.3 to ^2.3 || ^3.0

Updates the requirements on [monolog/monolog](https://github.com/Seldaek/monolog) to permit the latest version.
- [Release notes](https://github.com/Seldaek/monolog/releases)
- [Changelog](https://github.com/Seldaek/monolog/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Seldaek/monolog/compare/2.3.0...3.9.0)

---
updated-dependencies:
- dependency-name: monolog/monolog
  dependency-version: 3.9.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>

* update monolog example

* style

* drop monolog 2.3 from example

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Brett McBride <brett@deakin.edu.au>
2025-04-08 11:19:29 +10:00
dependabot[bot] 1413c3470e
Bump fossas/fossa-action from 1.5.0 to 1.6.0 (#1549)
Bumps [fossas/fossa-action](https://github.com/fossas/fossa-action) from 1.5.0 to 1.6.0.
- [Release notes](https://github.com/fossas/fossa-action/releases)
- [Commits](93a52ecf7c...c0a7d013f8)

---
updated-dependencies:
- dependency-name: fossas/fossa-action
  dependency-version: 1.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-03 12:12:34 +11:00
Brett McBride 68b6d4f6ee
skip segfault-inducing test (#1555)
this test triggers a bug that surfaced in xdebug 3.4.2, see https://bugs.xdebug.org/view.php?id=2332
2025-04-03 09:34:15 +11:00
dependabot[bot] 5c0004b515
Bump phpDocumentor/phpDocumentor from 3.5.3 to 3.7.1 (#1550)
Bumps [phpDocumentor/phpDocumentor](https://github.com/phpdocumentor/phpdocumentor) from 3.5.3 to 3.7.1.
- [Release notes](https://github.com/phpdocumentor/phpdocumentor/releases)
- [Changelog](https://github.com/phpDocumentor/phpDocumentor/blob/master/CHANGELOG.md)
- [Commits](https://github.com/phpdocumentor/phpdocumentor/compare/v3.5.3...v3.7.1)

---
updated-dependencies:
- dependency-name: phpDocumentor/phpDocumentor
  dependency-version: 3.7.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-02 22:53:18 +11:00
dependabot[bot] 6ed191498e
Bump docker/build-push-action from 5 to 6 (#1548)
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 5 to 6.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v5...v6)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-02 22:52:36 +11:00
dependabot[bot] 59a4f7730b
Bump codecov/codecov-action from 4 to 5 (#1547)
Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 4 to 5.
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codecov/codecov-action/compare/v4...v5)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-04-02 22:51:58 +11:00
Cedric Ziel 2b5ce6c611
fix: bump timeout for building images (#1553)
Bumps the timeout to 500 (default 360) minutes.
2025-04-02 22:47:06 +11:00
Cedric Ziel 8028f9715f
chore: build images dynamically (#1545)
* chore: build images dynamically

* fix: only push on main

* chore: build on PR with path change

* chore: align casing

* fix: add missing 8.0 alias

* fix: declare arg before all others
2025-04-02 09:04:31 +11:00
Cedric Ziel 5899a9e287
chore: auto-update dependencies via dependabot (#1544) 2025-04-02 09:02:04 +11:00
Cedric Ziel a354f46612
chore: publish base image for 8.4 as well (#1539) 2025-03-30 20:51:14 +11:00
Tobias Bachert 015da800aa
Fix `YamlSymfonyFileLoader` if locator uses directory besides `getcwd()` (#1526) 2025-03-12 10:55:57 +11:00
Sergey Kleyman 968083597f
Fix IS_REMOTE flag (#1522)
* Fixed span's is_remote flag computation
* Added testing for cases without parent and with local parent span
2025-03-07 10:21:56 +11:00
Tobias Bachert 08c88605b4
Fix `LateBindingMeter::createObservable{Instrument}()` (#1524) 2025-03-06 08:42:54 +11:00
Bartosz Tomczak 68462e0bb2
Check max retry on grpc transport (#1516)
* Check max retry on grpc transport
* Skip retry policy when maxRetries is 0
2025-03-05 09:35:49 +11:00
OpenTelemetry Bot 88c79091ca
Add FOSSA scanning workflow (#1511)
Co-authored-by: otelbot <197425009+otelbot@users.noreply.github.com>
2025-02-27 07:59:13 -05:00
Richard Chukwu 656f5db415
Update development guide to contributing guide (#1513)
* Update CONTRIBUTING.md
2025-02-25 15:59:05 +11:00
Brett McBride 8316c50e93
use a local const for grpc time conversions (#1505)
using a newly-added const in ClockInterface breaks things for some older PHP versions, so
lets use a local const for now
2025-02-10 09:37:38 +11:00
Brett McBride 66c8ce8059
Semconv 1.30 (#1495)
* generate semconv 1.30
NB that v1.29 contained a bug, and the recommendation was to skip this version

* reduce minimum php version to 8.0
we still have a bunch of auto-instrumentations that work with 8.0
2025-02-06 11:21:48 +11:00
Jon Bates 5d24db8fca
A couple of code tidies left over from PR #1499 (#1502) 2025-02-06 09:26:24 +11:00
Jon Bates 31d902b6c6
fix gRPC timeout (#1498) (#1499) 2025-02-04 08:49:11 +11:00
Brett McBride 96ce422b6a
generate semconv 1.28 (#1491) 2025-01-30 10:41:46 +11:00
Brett McBride 3e8ae81e35
handle empty meter observers (#1490)
* if no observers are registered for a meter's instruments, some tests were emitting php warnings:
- foreach() argument must be of type array|object, null given
- Undefined array key XXX

null coalesce to an empty array to make the test happy.

* handle empty writers
2025-01-30 08:40:28 +11:00
Brett McBride 420b5ef6df
disallow empty string for baggage name (#1484)
spec 1.36.0 clarifies that empty string is not a valid baggage name
2025-01-30 08:38:08 +11:00
Brett McBride e3f77b7ada
remove todo for logging dropped attributes (#1485)
this is already implemented for logs and traces as required by spec
2025-01-30 08:37:19 +11:00
Brett McBride b24a30c31a
yaml config env var spec conformance (#1486)
* add support for env: prefix in yaml config
* align test to example in spec
* do not recursively replace env vars
  - fix env substitution normalization so that it doesn't apply 2 replacement normalizers for string nodes
2025-01-28 12:37:53 +11:00
Brett McBride 7eb3abb276
adding otlp/file exporter (#1481)
* otlp_file config support
* handle otlp_file scheme://path format
* update kitchen-sink
2025-01-23 10:12:34 +11:00
Brett McBride a4119f9e32
support refactored otlp export config (#1477)
upstream config now splits otlp exporters into otlp_http and otlp_grpc

* use const, remove insecure from otlp_http config

* Apply suggestions from code review

Co-authored-by: Tobias Bachert <git@b-privat.de>

* set default endpoints, fix review feedback

* move endpoint out of yaml anchor

* convert timeouts from millis to seconds

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2025-01-21 10:35:16 +11:00
Brett McBride 29b7da48c4
generate proto 1.5.0 (#1478) 2025-01-16 10:07:07 +11:00
Brett McBride 83cddd9157
declarative config 0.3+ support (#1452)
This brings declarative config support up to 0.3 plus some of the unreleased 0.4 features:

* porting code from Nevay/otel-sdk-configuration
* support 0.4 metric reader config
* allow empty keys
since https://github.com/open-telemetry/opentelemetry-specification/pull/4269 empty keys are allows, and NULL is no longer equivalent to unset
* update config example to remove empty objects
* remove moved component providers from composer.json
* add ComponentProviderRegistry::componentMap for instrumentation configuration
2025-01-10 10:17:14 +11:00
Brett McBride 4b575e6b6c
deprecate event logger (#1466)
The event logger was a Development-status component of the logging signal. It has been
removed in favour of adding emitEvent to the logger interface,
see https://github.com/open-telemetry/opentelemetry-specification/pull/4319
2025-01-09 10:50:34 +11:00
Brett McBride 32e301ea6a
adding otlp/file exporter (#1465)
the spec has added in-development otlp file/stdout exporter. We already supported this programmatically, so
add some factories and sdk config to allow configuration from environment (only for stdout, per spec)
2025-01-09 10:50:03 +11:00
Brett McBride 7aa3e02eb0
remove blank lines after class opening (#1468)
add the php-cs-fixer no_blank_lines_after_class_opening rule and apply to codebase
2025-01-07 21:18:52 +11:00
Brett McBride b515b6b6ff
handle host detector with custom error handler and open_basedir (#1454)
if open_basedir is configured such that files that it tries to open are denied with a php warning, and
a custom error handler is installed which converts warnings to exceptions, an unhandled exception occurs.
add a test for this, suppress error handling around the code that can trigger this.
2024-12-20 19:29:15 +11:00
Brett McBride f73bcfa22c
ignore platform reqs for 8.4 install (#1460)
psalm is not yet compatible with 8.4, so force it
2024-12-20 18:57:57 +11:00
Brett McBride 4a021fbaec
adding php 8.5 to build matrix (#1439)
- build against 8.5 (nightly)
- make 8.4 non-experimental
2024-11-27 21:03:40 +11:00
Brett McBride f1c982734b
add sdk-config 0.3 support for key/value headers and attributes (#1428)
- headers and attributes are now arrays with `key` and `value` elements
- headers can optionally contain a `headers_list` element which supports a lower-priority CSV of key/value entries
- attributes can optionally contain an `attributes_list` element which supports a lower-priority CSV of key/value/data-type entries
2024-11-26 11:48:31 +11:00
Chris Lightfoot-Wild 8857b0c103
Added \Attribute::TARGET_PARAMETER to \OpenTelemetry\API\Instrumentation\SpanAttribute (#1433)
Fixes #1429.
2024-11-16 15:32:30 +11:00
John Spaetzel 7b5cbb5078
guard against possible false value from file_get_contents in Host.php (#1430) 2024-11-15 16:42:53 +11:00
Bob Strecansky 38633fba0e
Update README.md (#1427)
Adding API Documentation Link
2024-11-06 11:15:52 -05:00
Severin Neumann ea908b161d
Rename phpdoc-to-github-pages to phpdoc-to-github-pages.yml (#1425)
- follow up to #1418, where I named the file without the required YML suffix
- Do not run on pull requests
2024-11-05 20:38:15 +11:00
Aleksei Gagarin 39cc549f04
Support google protobuf v4 (#1421) 2024-10-30 22:49:49 +11:00
Severin Neumann 1aae9dd619
Workflow to publish phpdoc to github pages (#1418) 2024-10-28 08:27:02 +11:00
znerol 93f2068d0b
fix start timestamp in auto root span (#1413) 2024-10-19 08:01:35 +11:00
Mark van Duijker fd654b99c7
fix: Guzzle version 6 error in Http Client Discovery (#1409) 2024-10-17 20:58:13 +11:00
Brett McBride d2b15077df
use weaver to generate semconv (#1398)
update semconv generation to use the new tooling. This is fairly close to a 1:1 of what we have now,
although I noted a couple of TODOs which we might consider in future to align with what Java is
doing: split attribute up into file-per-type, and split stable/unstable.
2024-10-17 20:57:37 +11:00
Brett McBride 01d0fd3618
ensure zipkin tags and attributes are cast to strings (#1406) 2024-10-16 08:03:20 -04:00
Tobias Bachert 2c1da9aaec
Add `TextMapPropagator` to instrumentation context (#1401) 2024-10-16 09:42:37 +11:00
Brett McBride c632d960a5
check for readable host id files before read (#1400)
* check for readable host id files before read
* reset vfs between tests
2024-10-16 09:42:15 +11:00
Tobias Bachert f29277abc0
Move hook manager registration to API package (#1402)
Keeping registration in SDK to not break API >1.1.0 w/ SDK 1.1.0.
2024-10-14 09:16:24 +11:00
Chris Lightfoot-Wild cd8c0e3124
Fix HookManagerInterface annotation (#1395)
* Align OpenTelemetry\API\Instrumentation\AutoInstrumentation\HookManagerInterface::hook signatures with OpenTelemetry\Instrumentation\hook.

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-10-05 16:00:52 +10:00
Brett McBride 0ae272373d
84 implicit null (#1394)
* 8.4: fixing some implicit nullable params

* fix withspan handler nullable + example (#1377)

- class is nullable for pre hooks
- add phpt tests for withspan and its interaction with auto root span

* fix: update references to logging exporter (#1383)

This exporter has been replaced by the debug exporter and will be removed soon. Related to https://github.com/open-telemetry/opentelemetry-collector/pull/11037

Signed-off-by: Alex Boten <223565+codeboten@users.noreply.github.com>

* fix: Update collector tag in example to latest (#1384)

Follow-up from #1383. Debug exporter isn't available until v0.86.0, so this new configuration throws an error when trying to run the collector. `Error: cannot unmarshal the configuration: unknown exporters type "debug" for "debug"` Instead of setting to v0.86.0, I noticed the other docker files omitted the tag (so latest is pulled). I just updated this to match.

* Remove `MeterInterface::isEnabled()` and fix meter config re-enabling (#1387)

* Update SPI dependency to v1. (#1388)

* Fix README badges. (#1389)

* add phpDocumentor instructions to Makefile (#1385)

* add phpDocumentor instructions to Makefile

Signed-off-by: svrnm <neumanns@cisco.com>

* update DEVELOPMENT.md

Signed-off-by: svrnm <neumanns@cisco.com>

---------

Signed-off-by: svrnm <neumanns@cisco.com>

* Update README.md (#1344)

* Fix `IncompatibleReturnValueException` in `MessageFactoryTest` (#1392)

PSR7 `RequestInterface::getUri()` must return `UriInterface`, not `string`; explicit typehint was added in `2.0`.

* more implicit nulls

---------

Signed-off-by: Alex Boten <223565+codeboten@users.noreply.github.com>
Signed-off-by: svrnm <neumanns@cisco.com>
Co-authored-by: Alex Boten <223565+codeboten@users.noreply.github.com>
Co-authored-by: Jamie Danielson <jamieedanielson@gmail.com>
Co-authored-by: Tobias Bachert <git@b-privat.de>
Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>
Co-authored-by: Severin Neumann <neumanns@cisco.com>
Co-authored-by: Oleg <142805497+devactivity-team@users.noreply.github.com>
2024-10-02 08:06:03 -04:00
Tobias Bachert fd24607c10
Fix `IncompatibleReturnValueException` in `MessageFactoryTest` (#1392)
PSR7 `RequestInterface::getUri()` must return `UriInterface`, not `string`; explicit typehint was added in `2.0`.
2024-09-29 22:12:53 +10:00
Oleg 20bf3cff3e
Update README.md (#1344) 2024-09-25 14:40:03 -04:00
Severin Neumann 91f4735b3a
add phpDocumentor instructions to Makefile (#1385)
* add phpDocumentor instructions to Makefile

Signed-off-by: svrnm <neumanns@cisco.com>

* update DEVELOPMENT.md

Signed-off-by: svrnm <neumanns@cisco.com>

---------

Signed-off-by: svrnm <neumanns@cisco.com>
2024-09-25 14:39:36 -04:00
Chris Lightfoot-Wild 7d744e0086
Fix README badges. (#1389) 2024-09-25 21:59:48 +10:00
Chris Lightfoot-Wild 439447b286
Update SPI dependency to v1. (#1388) 2024-09-25 21:54:21 +10:00
Tobias Bachert 6a2242d46a
Remove `MeterInterface::isEnabled()` and fix meter config re-enabling (#1387) 2024-09-25 09:58:09 +10:00
Jamie Danielson 8ed62b1e43
fix: Update collector tag in example to latest (#1384)
Follow-up from #1383. Debug exporter isn't available until v0.86.0, so this new configuration throws an error when trying to run the collector. `Error: cannot unmarshal the configuration: unknown exporters type "debug" for "debug"` Instead of setting to v0.86.0, I noticed the other docker files omitted the tag (so latest is pulled). I just updated this to match.
2024-09-24 08:35:18 +10:00
Alex Boten 3be58cff57
fix: update references to logging exporter (#1383)
This exporter has been replaced by the debug exporter and will be removed soon. Related to https://github.com/open-telemetry/opentelemetry-collector/pull/11037

Signed-off-by: Alex Boten <223565+codeboten@users.noreply.github.com>
2024-09-22 17:42:55 +10:00
Brett McBride 068086347b
fix withspan handler nullable + example (#1377)
- class is nullable for pre hooks
- add phpt tests for withspan and its interaction with auto root span
2024-09-07 08:51:46 +10:00
Brett McBride bee9c64ae9
adding auto-instrumentation attribute to API (#1371)
adding WithSpan and SpanAttribute attributes to the API. These attributes
are used by an upcoming feature in auto-instrumentation which allows users
to add attributes to their code to enable auto-instrumentation.
2024-08-31 09:17:53 +10:00
Brett McBride 4fc170002d
re-adding removed trace attribute values (#1368)
the MESSAGING_OPERATION_* attribute values were removed in semconv 1.26.0,
so update our generation to put them back, marking as deprecated
2024-08-28 19:20:31 +10:00
Brett McBride 653e453f95
adding config provider (#1366)
implement recent additions to the otel spec re: config provider. Config provider should return a
ConfigProperties, but we were already returning a ConfigurationRegistry. Added a ConfigProperties
interface for ConfigurationRegistry to implement, which gets us pretty close to spec.
We don't make ConfigProvider globally available, instead passing the ConfigurationRegistry in to
each instrumentation as we register it. The spec allows for this.
2024-08-27 09:28:08 +10:00
Brett McBride f4b52c4b49
add minimal auto-instrumentation hook functions (#1358)
add OpenTelemetry\API\Instrumentation\WithSpanHandler, which will be the default pre/post
hook callbacks for attribute-based auto-instrumentation.
2024-08-26 11:17:16 +10:00
Brett McBride 5276df3171
auto root span creation (#1354)
* auto root span creation
proof of concept for automatically creating a root span on startup.
the obvious deficiencies are:
- no idea of response values (status code etc)
- does not capture exceptions

* deptrac
2024-08-23 09:15:18 -04:00
Brett McBride 69825d395a
fix implicit null usage (#1362)
php8.4 deprecates implicit null (now checked by phan)
2024-08-21 10:29:20 +10:00
Luc 80e97da6eb
Allow 'google/protobuf' '^4.0' to be used. (#1361) 2024-08-18 21:02:08 +10:00
Brett McBride 41dd113030
implement scope configuration (#1353) 2024-08-18 20:52:43 +10:00
Brett McBride 382331e062
semconv 1.27.0 (#1356)
* generate semconv 1.27.0

* improve attribute values brief and deprecation display

* remove duplicate trace attribute, ignore deprecated attributes

* fix tests
2024-08-06 11:17:39 -04:00
Brett McBride d2ec5e6d0b
add enabled to late binding logger and tracer (#1357) 2024-08-06 07:58:59 -04:00
Brett McBride 10b8d9732b
adding LocalRootSpan (#1310)
* adding LocalRootSpan class
this is based on Java's implementation, https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/v2.3.0/instrumentation-api/src/main/java/io/opentelemetry/instrumentation/api/instrumenter/LocalRootSpan.java
and adds the ability to identify and locate the "local root span" in a trace. The local root span is the top-level active span which has either
an invalid or remote parent.
It's tracked automatically as part of making a span active, either via `Span::activate()` or `Span::storeInContext()`, and can be retrieved in
a couple of ways, but most easily via `LocalRootSpan::current()`.

* remove redundant local root span check

* move context key to api

* internal

* adding example

* mark LocalRootSpan as experimental

* adding an example of local root span usage

* style, fix broken build
2024-08-06 07:58:33 -04:00
Brett McBride 68b1b43cab
auto-instrumentation registration (#1304)
* [WIP] Add instrumentation configuration

* add autoloading for auto-instrumentations using SPI

* allow autoloading and non-autoloading to work

* fix attribute

* experimental config file

* fixing invalid dependencies
- deptrac was rightly complaining that API (indirectly) depended on SDK through config/sdk. For now,
remove usage of Config\SDK\Configuration\Context
- update deptrac config to allow some new dependencies

* dont register hook manager globally or in sdk

* remove unused function, psalm ignore missing extension function

* possibly fixing type-hint
psalm doesn't complain now, so that should be good

* load config files relative to cwd

* fixing hook manager enable/disable + psalm complaints

* fixing 8.1 psalm error

* use context to pass providers to instrumentations
- make "register global" a function of Sdk, but keep the sdk builder's interface intact
- invent an API instrumentation context, similar to the one in config/sdk, to pass providers
  to instrumentations
- add an initial test of autoloading from a config file

* adding tests for sdk::registerGlobal
in passing, remove some dead code for handling invalid booleans - config already handles this correctly

* linting

* test coverage for globals

* add opentelemetry extension to developer image and actions

* always register instrumentations via SPI

* register globals initializer for file-config sdk
allow SDK created from config file to coexist with components using globals initializer

* linting

* remove globals init function

* fix phan warning

* simplify hook manager
- drop storage from hook manager: can't guarantee that something else, eg swoole, won't modify storage
- drop context from hook manager: we must lazy-load globals via initializers, because not all instrumentations use SPI (although that may change in future)
- default hook manager to enabled

* add todo to deprecate Registry in future

* autoload instrumentations without config
if no config provided, still try to load them. wrap registration in a try/catch/log

* fixing phan ref, update doc

* remove phan suppress

* fix example

* bump SPI to 0.2.1

* adding late-binding tracer+provider
per review from Nevay, this will allow instrumentations to get things from Globals as late as possible

* adding late binding logger and meter providers

* more late binding test coverage

* tidy

* dont use CoversMethod yet
not available in phpunit 10, so comment out and leave a todo

* kitchen sink, remove unused var

* instrumentation config as a map, per config file spec

* adding general config

* move general config into sdk

* test config caching

* move general instrumentation config to api

* avoid bad version of sebastian/exporter

* bump config yaml files to 0.3

* fix tests

* disable hook manager during file-based init

* cleanup

* support multiple config files in autoloader

* move hook manager enable/disable out of extension hook manager
The most obvious place to do this is in a class named HookManager, which _was_ an
interface for hook managers. Rename existing HookManager to HookManagerInterface,
then re-purpose HookManager for globally enabling/disabling hook managers as well
as determining the disabled status.

* update spi config

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-07-22 10:40:34 -04:00
Brett McBride 4ed0d870f7
add enabled functions (#1350)
* add enabled function
spec 1.34 requires logger, tracer, and instrument to have an enabled function

* Update src/API/Metrics/Instrument.php

Co-authored-by: Tobias Bachert <git@b-privat.de>

* adjust instrument enabled logic

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-07-19 10:28:32 -04:00
Brett McBride 1271f1ed69
add return type hints (#1351)
now that 7.4 and 8.0 support is dropped, we can add correct return type-hints
to these functions, and remove the ReturnTypeWillChange attribute.
2024-07-19 09:33:49 -04:00
Brett McBride e4f9604411
remove deprecated rector rule (#1352)
this silences a rector warning which was breaking local build
2024-07-19 09:30:29 -04:00
Cedric Ziel 17ad56a3f3
Add linux/arm64 to base images support M3 devices (#1343) 2024-07-05 17:14:50 -04:00
Brett McBride a822c455a4
update semconv to 1.26.0 (#1316)
note that `messaging.client_id` was renamed to `messaging.client.id`, which causes a conflict in const name.
The recommendation from semconv maintainers is to replace the old value, `messaging.client_id`.
2024-06-28 11:51:36 +10:00
Brett McBride 36f29a37cb
fixing implicit nullable deprecations, bump GH actions (#1340)
* implicit nullable parameters are deprecated in 8.4, so make them explicit
* update github actions versions
2024-06-28 11:44:08 +10:00
Brett McBride b6f9afb5af
log discarded span+log attributes (#1336)
The SDK should log a warning once if there are any dropped span attributes, links, link attributes, events or event attributes.
The SDK should log a warning once if there are any dropped LogRecord attributes.
2024-06-27 08:52:30 +10:00
Brett McBride a90f18cc72
event logger spec compliance (#1335)
update event logger to conform to spec 1.34.0:
- implement ForceFlush, which delegates to the LoggerProvider
- rename event payload to body
2024-06-26 15:34:36 +10:00
Brett McBride fc28032748
handle empty encoded responses (#1337)
at least one otel backend product sends an empty response with a gzip encoding, which we fail to decode (because
an empty string is not valid). Work around this by not trying to decode an empty value.
2024-06-20 09:44:40 +10:00
Matt Hensley 6bf422c0f1
Adds experimental service.instance.id resource detector (#1309)
* implement experimental service.instance.id attribute
2024-06-15 12:09:33 +10:00
Bart Reunes eebf23a21d
Add return types for ArrayAccess in docblocks (#1319) 2024-06-05 08:04:47 -04:00
David Grayston 600d8a5f53
Fix logs exporter factory exception message (#1318) 2024-06-03 09:14:46 -04:00
Chris Lightfoot-Wild 39f81a3cc6
Updated link to 3musketeers site. (#1315) 2024-05-22 09:40:03 +10:00
Brett McBride eaba9e3228
conflict with mockery 1.6.12 (#1313) 2024-05-21 14:27:12 +10:00
Brett McBride fbdb103590
upgrade to phpunit 11 (#1308)
* run unit tests in random order
running in random order highlights some interference between tests (mostly logging being enabled), and is a requirement for
mutation testing (ie, all tests must pass when executed in a random order).
* adding infection mutation testing
this adds the ability to run infection. It generates a lot of output, which is an exercise for another PR...
* replace assertwell/phpunit-global-state
the package was not compatible with phpunit 11. create out own test Trait, which handles
env vars, as well as general cleanup of the usual suspects of state that our tests mess up
* remove redundant tearDown functions
there's an after annotation on the trait to handle this
* use rector to upgrade tests for phpunit 11
* fixing CoversFunction for namespaced functions
* use FQNs in test attributes
2024-05-16 09:21:28 +10:00
Brett McBride 4f32817065
Add infection test tool (#1306)
* run unit tests in random order
running in random order highlights some interference between tests (mostly logging being enabled), and is a requirement for
mutation testing (ie, all tests must pass when executed in a random order).
* adding infection mutation testing
this adds the ability to run infection. It generates a lot of output, which is an exercise for another PR...
* infection max threads
2024-05-15 20:46:42 +10:00
Brett McBride 500f6ee1bd
implement events v1.32 (#1291)
* implement events v1.32
implement the events api + sdk per spec v1.32:
- event logger is now only retrievable via an event logger provider
- domain attribute for events is removed
- events accept a subset of logrecord params, rather than an entire logrecord

* convert severity to a backed enum

* lint

* remove instead of deprecating logEvent, mark Logger constructor as internal

* make severity an enum only

* event attributes to iterable

* inject ClockInterface, add CachedInstrumentation, update examples

* set correct defaults for events

* test coverage

* Revert "make severity an enum only"

This reverts commit 710822907b.
Also, move PSR-3 mapping into the Severity enum.

* event attributes to iterable

* apply review feedback
2024-05-05 18:35:19 -04:00
Brett McBride 8031c78512
move test tools into vendor-bin (#1302)
* move test tools into vendor-bin
To reduce (hopefully, eliminate) the situations where our testing tools have conflicting
dependencies, use bamarni/composer-bin-plugin to manage them as separate vendored dirs.
Add symlinks under tools/, and update Makefile to use the self-contained versions.
Remove the dependencies from root composer.json
Rejigger dockerfile to add opcache, and some config required for latest version of grpc

* update action tools locations

* revert phpstan from vendor-bin
the phpstan plugins do not work. phpstan has no dependencies anyway, so it's safe enough to keep in vendor

* remove tools symlinks, update makefile
2024-05-05 18:34:52 -04:00
Brett McBride 8e810c6598
adding enum for semconv versions (#1301) 2024-05-05 10:19:13 +10:00
Tobias Bachert 82b191b984
Fix `weaken` for PHP8.4 closure names (#1303) 2024-05-03 09:14:33 +10:00
Brett McBride 100e593bd6
fix deptrac config to allow http clients (#1293)
* fix deptrac config to allow http clients

* Update deptrac.yaml

Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>

---------

Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>
2024-04-30 14:28:45 -04:00
Tobias Bachert 80114317f8
Set OTLP 1.2.0 span parent/link remote flags (#1298)
* Generate protobuf 1.3.0

* Set otlp exporter proto 1.2.0 remote flags
2024-04-30 14:28:30 -04:00
Dalibor Karlović 5747fac40c
fix: correct path to autoloader in metrics/getting-started (#1299) 2024-04-30 20:51:20 +10:00
Andy Postnikov f2cba82c28
[PHP 8.4] Fixes for implicit nullability deprecation (#1297) 2024-04-29 15:24:44 +10:00
Brett McBride fc161a8548
migrate Clock classes to API (#1281)
* migrate Clock classes to API
- move Clock* + Util into API
- add a deprecated wrapper for ClockFactory and Util
- remove unused StopWatch* classes

* review feedback

* replace ClockFactory with Clock
It's not really a factory, and really only provides access to a system clock. Create a
Clock class which is more clear in its purpose.

* remove time Util class
per review feedback, it's only used in Zipkin. Removed some unused consts from ClockInterface

* Apply suggestions from code review

Co-authored-by: Tobias Bachert <git@b-privat.de>

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-04-29 10:28:06 +10:00
Paul 9fe6aa0cd7
Include schema_url in FriendlySpanConverter (#1292) 2024-04-29 10:22:58 +10:00
Brett McBride cea2d7c4cb
use codecov action (#1294)
our previous method of uploading to codecov.io is suffering from throttling and taking 5+ hours,
a post in the opentelemetry maintainers channel suggests this is the way to do it now
2024-04-29 09:51:57 +10:00
Tobias Bachert 8a6dd4750d
Add `Span::addLink()` and `Meter::createGauge()` (#1289)
* Add `Span::addLink()`

https://opentelemetry.io/docs/specs/otel/trace/api/#add-link

* Bump API version to `1.1.x-dev`

* Add experimental `Meter::createGauge()`

https://opentelemetry.io/docs/specs/otel/metrics/api/#gauge
2024-04-27 14:59:15 +10:00
Brett McBride 5a395e09da
enable timeout for http transports (#1275)
* enable timeout for http transports
Attempt to do our own discovery for some well-known PSR-18 clients, which allows
for configuring timeout (and in future certificates, keys etc).
This is not complete and a prototype for feedback, but I've updated an example to
show that it works for Guzzle and Symfony http clients

* improve client discovery

* refactor, test, add more implementations

* add timeout for logs and metrics
2024-04-25 16:21:00 +10:00
Brett McBride 5019361068
fixing warnings from local build (#1277)
A couple of warnings have popped up recently:
- docker compose 'version' is deprecated
- BSD host id test was running a command that doesn't exist, which was visible in test output (removed test case)
- synchronous metric stream test was triggering a warnings which was visible in test output (changed to use LogsMessagesTrait)
- resource merging with different schema URLs was triggering a warnings from Config test (updated yaml schema_url and documented)
2024-04-19 09:04:57 +10:00
Brett McBride 43339294f5
port Nevay/otel-sdk-configuration into opentelemetry-php (#1276)
* port Nevay/otel-sdk-configuration into opentelemetry-php
This is a lift-and-shift, except for:
- changing namespaces
- fixes or ignore rules required to make static analysis tools happy
- commenting out one part of yaml test (unquoted hex value from env var)

* fix psalm on php81
2024-04-15 09:15:37 -04:00
Kevin Mian Kraiker fda522a90b
Update SemConv to 1.25.0 (#1271)
* generate semconv 1.25.0
* Tweak template `deprecated` attributes behavior and regen
* Use is_deprecated filter
2024-04-10 09:31:35 +10:00
Tobias Bachert 6cd7a8af2c
Improve fiber bound context storage (#1270)
* Improve fiber bound context storage

Now works properly in fibers once initial context is attached.

* Change `Context::storage()` return type to `ContextStorageInterface`

`ExecutionContextAwareInterface` should not be relevant for end-users / it was mainly exposed for the FFI fiber handler; calling any of its method with enabled fiber handler would have broken the storage.
Swoole context storage README creates a new storage instead of wrapping `Context::storage()`: `Context::setStorage(new SwooleContextStorage(new ContextStorage()));`.

* Add BC layer for execution context aware fiber storage

* Fix BC layer inactive execution context detection for {main}
2024-04-09 09:11:29 +10:00
John Bley e44f5a97d9
Clean up shell scripts (#1269)
* Clean up shell scripts
* Add shellcheck CI step
2024-04-03 10:54:21 +11:00
Matt Hensley bb9eb40a50
Add host.id for non-containerized systems (#1266)
Co-authored-by: Tobias Bachert <git@b-privat.de>
Co-authored-by: Chris Lightfoot-Wild <github-clw@wild.me.uk>
2024-04-02 09:20:09 +11:00
Tobias Bachert 7ec0e90402
File configuration (#1249)
* Add configuration model
* Add metrics and logs configuration model
* Remove accidentally added package dependency
* Fix `$properties` typehint to match config
Default value available -> cannot be null.
* Add configuration example that utilizes env substitution
* Fix/suppress config psalm issues
* Fix/suppress config phpstan issues
* Suppress config phan issues
* Apply cs-fixer
* Change config package version to development version 0.x
* Add README
* Add basic test
* Fix psalm and cs
* Fix composer requirement for PRs
* gitsplit, copy spi config to root composer.json
2024-04-01 18:13:01 +11:00
Tobias Bachert 6dd255deac
Fix tracestate implementation (#1267)
* Port tracestate tests
* Fix tracestate implementation
* Fix W3C test service
* Fix style
* Move tests into `TraceStateTest`
* Assert that warning is triggered when parsing invalid tracestate
* Add additional tests for valid/invalid keys/values
2024-04-01 17:05:09 +11:00
Brett McBride a1489d3081
upgrade to phpunit 10 (#1258)
* upgrade to phpunit 10

* removing unintended commented code
2024-03-18 21:02:39 -04:00
Tobias Bachert 639d8e2561
Update docker compose default php version to 8.1 (#1259)
* Update default php version for docker compose
* Use docker compose v2
> From July 2023 Compose V1 stopped receiving updates.
2024-03-16 10:50:25 +11:00
Brett McBride 4cb04999d9
drop php 8.0 support (#1256)
* bump php to 8.1, apply rector
* readonly and typehints
* suppress a dodgy readonly property conversion
* remove some redundant readonly phpdocs
* dont run workflows against 8.0
* more readonly and typehints
* phpdoc reformat
* typehints
* remove php81 polyfill
* revert a rector BC breaking change, and disable that rector for ParentBased
2024-03-15 10:14:21 +11:00
Tobias Bachert 1753fbe32b
Fix conversion of non-utf8 sequences to `AnyValue` (#1253)
String values which are not valid Unicode sequences SHOULD be converted to AnyValue's bytes_value with the bytes representing the string in the original order and format of the source string.
2024-03-14 09:30:50 +11:00
Alexandre Choura 01c46a2350
perf: Re-use empty resource instance (#1251) 2024-03-12 14:49:02 +11:00
Brett McBride bb07aca7a2
upgrade psalm to v5 (#1246) 2024-03-04 06:58:09 -05:00
Brett McBride f798bb6f01
Drop PHP 7.4 support (#1244)
* drop php 7.4 support
update composer.json minimums, and run rector over the code to update what it can. changed some static analysis
config to fix some rector-induced failures.

* adding union typehints

* reformat constructor property promotions

* updating/removing phpdoc

* suppress protobuf extension complaint
submitted a PR upstream to fix phan stubs

* don't validate packages against 7.4

* remove php8 polyfill

* fix readonly comments

* apply trailing commas to multiline fixer
upgrade php-cs-fixer, and apply a new rule for multiline comments

* remove unreachable default match arms for protobuf serializer

* adding more union types to vars

* use weakmap directly

* remove handling for not-supported WeakMap

* spacing
2024-03-03 20:21:16 -05:00
Alexandre Choura cc56628c4d
feat: Allow OTEL_PHP_DEBUG_SCOPES_DISABLED as en environment variable (#1237)
* fix: Allow OTEL_PHP_DEBUG_SCOPES_DISABLED env var + use of null-coalescing operator
* refactor: Check order & env reset
* refactor: Use class constant
* fix: Respect order and value if it is set
* style: Lint
* tests: Falsey behavior
2024-03-01 10:04:41 +11:00
Brett McBride 258e58644a
support url-encoded OTEL_EXPORTER_OTLP_HEADERS values (#1242)
Per a recent spec clarification in https://github.com/open-telemetry/opentelemetry-specification/issues/3832 OTLP
headers should support url-encoded header values.

Co-authored-by: Tobias Bachert <git@b-privat.de>
2024-02-29 08:57:02 +11:00
Brett McBride b20c45df10
log previous exception message from error writer (#1231)
it's not always clear from an exception message what the underlying issue was, so
also print out the previous exception's message, if available.
2024-02-06 12:32:25 +11:00
Brett McBride 1f187c7837
update image build actions to latest versions (#1229)
this should resolve some deprecation warnings for some things that will soon break
2024-02-05 14:09:57 +11:00
Brett McBride e522d9d81f
improve excluded urls code (#1227)
improve code and add more tests to the OTEL_PHP_EXCLUDED_URLS feature
2024-02-02 14:42:40 +11:00
Brett McBride 36e2b7f613
adding OTEL_PHP_EXCLUDED_URLS (#1226)
Modeled on python's feature to turn off all instrumentation for specific URLs,
https://opentelemetry.io/docs/languages/python/automatic/agent-config/#excluded-urls
this feature will effectively disable SDK autoloading if there is a request URI that
matches one of the provided excluded URLs, and no-op implementations will be used
for tracer/logger/meter providers.
2024-02-01 08:21:30 -05:00
Brett McBride 91f5e20ffc
document when we drop support for end of life PHP versions (#1222) 2024-01-31 07:57:34 -05:00
安正超 84cf0a5635
Add required $contentType arguments (#1225) 2024-01-27 18:23:12 +11:00
Joao Jacome f2ab3c5e1d
Adding 'all' as an option for disabling auto instrumentations (#1220) 2024-01-24 23:00:22 +11:00
Brett McBride 810aa2f95a
generate semconv 1.24.0 (#1219)
* generate semconv 1.24.0
generate latest semconv version, and add back Trace and Resource attribute values which
seem to have been dropped in a previous change.

* document source repo release urls

* remove redundant semconv deprecations
two trace attributes were deleted then added back to upstream semconv, so remove our ones.
2024-01-24 08:47:17 +11:00
Tobias Bachert 1af83342f7
Fix proto 1.1.0 trace flags (#1216) 2024-01-17 23:46:01 +11:00
Brett McBride 102f5dc187
update proto to 1.1.0 (#1215)
updates generated protobuf files to 1.1.0, and adds trace flags to OTLP-encoded spans and span links
2024-01-17 08:54:57 +11:00
Brett McBride 2390dc07b0
cache php extensions (#1213)
Optimize build times by caching php extensions for one week, particularly for 8.4/nightly which otherwise builds extensions from source each time.
This ended up being a little convoluted, since caching extensions does not run on failure. So, make all steps continue-on-failure for experimental builds, and add a final post job which checks the status of the steps and does a final fail.
2024-01-17 08:32:21 +11:00
Brett McBride 521940d988
optimize resource merging (#1214)
- do not revalidate/normalize resource attributes on merge, since they have already been validated/normalized
- string concat is about 10x faster than sprintf, so use it in ClassConstantAccessor since it's called many times
2024-01-16 08:33:18 +11:00
Brett McBride 3928b13152
optimize resource creation (#1210)
* reduce resource creation from sdk autoloader
- instead of creating new resources from various factories, create them once from sdk autoloader and
pass them to the factories (most of which already supported this).
- check env before php.ini for config, since this is the more popular approach and saves some cycles
- cache header from OtlpUtil, to save a couple of calls to Sdk detector
* adding benchmark for resource creation
2024-01-13 16:52:09 +11:00
Brett McBride 25726f6cb9
fixing deptrac complaints (#1211) 2024-01-13 16:51:17 +11:00
Tobias Bachert 925ae9b12f
Handle out-of-order destruction of Fibers/DebugScopes during final shutdown (#1209)
* Handle DebugScope out-of-order destruction during final shutdown
* Move debug traces from local scope storage to debug scope properties
* Fix phpstan error
2024-01-13 16:50:44 +11:00
Tobias Bachert 596d4a2cea
Add support for multi-instrument callbacks (#1202)
* Add support for multi-instrument callbacks

https://opentelemetry.io/docs/specs/otel/metrics/api/#multiple-instrument-callbacks

* Fix undefined offset on detach of batch callback with repeated instrument

* Unify BatchObservableCallback and ObservableCallback

* Add missing typehint

* Do not bump API dependency

Not required, SDK will continue to work with lower API versions, only `::batchObserve()` won't be usable.
2024-01-10 08:04:59 -05:00
Tobias Bachert 82c0f8ed59
Add option to disable debug scopes (#1205) 2024-01-09 11:33:41 +11:00
Tobias Bachert a196c13425
Fix delta storage failing to merge node under rare circumstances (#1201)
Only fails if a node that was created after exceeding 63 readers should be merged with a node that was created before exceeding 63 readers, resulting in an `GMP===int` comparison. Affected nodes were still merged on the next `::collect()` call -> solely internal change.
2023-12-29 09:10:34 +11:00
Brett McBride 7c45db059d
adding 8.3 to build matrix (#1189)
* adding 8.3 to build matrix

* add experimental 8.4
2023-12-25 12:58:29 +11:00
Tobias Bachert bf8119c420
Prevent propagator packages from throwing fatal error if sdk not installed (#1198)
* Prevent propagator extensions from failing if sdk not installed

* Remove KnownValues dependency

Also prevents failing for cloudtrace: sdk < 1.0.1 and jaeger: sdk < 1.0.3.
2023-12-25 10:31:33 +11:00
Przemyslaw Delewski 4ff6ae4dbe
Updating CONTRIBUTING.md (#1194) 2023-12-19 10:14:38 +11:00
Tobias Bachert d4149990a3
Serialize protobuf enums as integer (#1192)
Spec: "Values of enum fields MUST be encoded as integer values."
2023-12-18 10:25:22 +11:00
Weslen Teche d8827f9681
Add Jaeger Propagator (#1188)
* jaeger propagator

* adjust readme

* add baggage and debug flag

* add units tests

* code review fixs and baggage separator

* update readme and register

* improve more tests

* fix php ci

* fix knowvalues jaeger baggage
2023-12-16 10:12:26 +11:00
Tobias Bachert d3765662f9
Add instrument advisory parameter (#1186)
* Add instrument advisory parameter

* Undo bucket boundaries change to preserve BC

"SDKs SHOULD use the default value when boundaries are not explicitly provided, unless they have good reasons to use something different (e.g. for backward compatibility reasons in a stable SDK release)."

* Add note that passing callback instead of advisory is deprecated
2023-12-13 13:03:10 +11:00
Tobias Bachert a6d15cf26e
Fix typo and deptrac rule (#1156)
* Fix typo "interal" -> "internal"
* Remove semconv from API deptrac ruleset
Removed in https://github.com/open-telemetry/opentelemetry-php/pull/965.
2023-12-08 09:54:20 +11:00
Jeremy Nikitin a568dde3f3
Rename XCloudTrace to CloudTrace (#1142) 2023-11-27 15:26:07 +11:00
Brett McBride 28657a9ec1
generate semconv for 1.23.1 (#1145)
a bug in 1.23.0 meant that cloud, container and oci resource attributes were incorrectly published under trace attributes.
sort the attributes, so that future diffs are easier to read.
2023-11-22 09:12:22 +11:00
Jeremy Nikitin d6c4c89bf4
Implement GCP X-Cloud-Trace-Context Propagator (#1132) 2023-11-14 09:04:22 +11:00
Brett McBride 30b73d948c
generate semantic conventions for 1.23.0 (#1137) 2023-11-08 10:26:31 +11:00
Brett McBride 42a8b95501
adding 1.19->1.22 semconv traceattributes deprecations (#1129) 2023-10-20 07:10:44 +11:00
Brett McBride a325a8f0bd
update semconv to 1.22.0 (#1126)
* update semver to 1.22.0
Since 1.19.0, the source has been split out of opentelemetry-specifiction into semantic-conventions. Update the build script accordingly.
Update to latest generator.
Add 2 new deprecations for semconvs which were renamed since 1.19
* update telemetry semconv
2023-10-19 07:53:08 +11:00
Brett McBride 842aa4121d
update SemConv readme (#1128)
mention that tags align with the upstream semantic conventions repo
2023-10-19 07:49:03 +11:00
Weslen Teche f22ffa0137
improving more tests (#1127) 2023-10-15 12:06:52 +11:00
Weslen Teche ea86fe1891
fix: documentations links (#1125) 2023-10-13 11:48:23 +11:00
Roman Kovalev b5170bf202
chore: fix broken link to env specs (#1122) 2023-10-05 16:29:42 +11:00
Brett McBride 75bb45fa71
adding 8.2 + 8.3 to build matrix (#1107)
8.3 is in RC, so add it to the matrix.
bump 8.2 to non-experimental, which should have happened some time ago.
remove deprecated assert_options call from test bootstrap
2023-10-05 12:45:08 +11:00
Brett McBride 8809c2a0b5
remove global configuration resolver (#1118)
Exposing it through Globals can cause a race condition. If something (eg, a contrib module)
retrieves the configuration resolver from Globals too early during autoloading, then it
causes the rest of the objects from Globals to be initialized. This can happen before all
required modules have been registered (depending on autoload->files execution order, which
is variable). Instead, create a simple API config resolver which does the basics of what the
SDK one does (without all the type checking and validation).
2023-09-28 09:15:51 +10:00
Greg Pinnington 3032304c3b
Add 'Contributing' message (#1108)
Co-authored-by: RoBorg <roborg@gmail.com>
2023-09-05 13:38:44 +10:00
Brett McBride 1852d514ca
fixing some psalm 5 complaints (#1110)
Whilst investigating upgrading to psalm 5, I notice that it generates a lot of new complaints. This fixes the ones that looked legit and
require an API change, or were trivial. Does not upgrade to psalm 5 yet, though. That's a bigger job for another day.
2023-09-05 08:56:24 +10:00
Brett McBride 73ff5adcb8
refactor sdk/api logging (#1105)
send errors/warnings/etc by default through PHP's error_log. This gives more control to administrators, since error_log can
be configured to write to any stream (file, stderr, etc). I think it's also less surprising for people trying out otel (particularly
with development PHP settings, where trigger_error often breaks an application).
Adding a configuration value to control where logs go: OTEL_PHP_LOG_DESTINATION.
2023-08-31 09:39:33 +10:00
Brett McBride 197a7a4c2c
optional internal metrics (#1106)
adding a configuration option OTEL_PHP_INTERNAL_METRICS_ENABLED which
controls whether the SDK will emit its own metrics (eg batch processor
state).
2023-08-31 09:23:20 +10:00
Brett McBride 62a14d1c20
remove deprecated code and BC hacks (#1099)
in preparation for RC, removing deprecations and BC hacks so that we have a clean slate for 1.0.0
2023-08-16 21:51:46 +10:00
Brett McBride 82f0c4477e
move temporality into own interface (#1098)
per TC review, temporality is not part of MetricExporterInterface. Riffing on Java's solution, this moves
`temporality` into `AggregationTemporalitySelectorInterface`, and adds that interface to MetricExporter instances
that use it (everything except `NoopMetricExporter`).
2023-08-10 08:11:34 +10:00
Brett McBride 55c08f3f44
adding PushMetricExporterInterface (#1097)
https://github.com/open-telemetry/opentelemetry-specification/pull/3563 clarifies the behaviour of
forceFlush with push/non-push metric exporters.
Break forceFlush out into a PushMetricExporterInterface, and update ExportingReader to only collect/flush
if exporter is a push metric exporter.
2023-08-10 07:47:46 +10:00
Greg Pinnington 9f358617f1
Fix for maxRetries < 1 (#1094)
* Fix for maxRetries=0
* Don't loop infinitely for negative maxRetries
2023-08-08 14:12:26 +10:00
Greg Pinnington c61f148d64
OtlpHttpTransportFactory should pass all arguments to PsrTransportFactory (#1093)
Co-authored-by: RoBorg <roborg@gmail.com>
2023-08-02 21:26:10 +10:00
Brett McBride ff15cc7037
document that examplars are not stable (#1091)
noted in TC review. Java moved their examplar code into an internal package, and
documented that it may change. We don't have an internal package, so document
the warning in a few places.
2023-08-01 08:09:07 +10:00
Brett McBride 7b8daff5ef
adding configuration resolver (#1083)
adding a configuration resolver interface, and api+sdk implementations. the resolver is globally configured.
this allows contrib modules to fetch config if an SDK is installed, without directly using the SDK (per spec).
2023-07-31 13:43:09 +10:00
Levi Morrison 1905dbfcd5
fix: fiber observers by FFI are not safe on ZTS (#1090)
They aren't _truly_ safe on NTS builds either, as the functions used
are only expected to be set at certain times of the lifecycle, but in
practice it's safe enough on NTS.

However, for ZTS, these APIs are not safe to call at runtime at all.
2023-07-26 09:47:28 +10:00
Brett McBride 4d9720f19e
improving test coverage (#1084) 2023-07-20 09:31:32 +10:00
Brett McBride 29cff8b991
fixing minor static analysis complaints (#1080)
fixing static analysis complaints, most of which were from psalm
when run with --show-info
remove deprecated httplug discovery
static data providers (phpunit10 requirement)
2023-07-20 09:30:31 +10:00
Tobias Bachert 926f6e5583
Always weaken asynchronous callbacks (#1081)
* Always weaken asynchronous callbacks
* Update comment regarding weak callbacks
2023-07-17 08:42:06 +10:00
Tobias Bachert cf8be76463
Remove workaround for php GH-8995 (#1082) 2023-07-17 08:38:33 +10:00
Brett McBride a60d0ad80c
rename log record processors (#1073)
per TC review, align log record processor names with those used in the spec
2023-07-11 09:37:28 +10:00
Brett McBride da219a9829
handle KeyValue otlp attributes (#1077)
if an array is non-simple (has keys), it should be represented as a KeyValue in the generated
protobuf-encoded output.
Since we also need to support simple arrays of primitives, I've added a basic check so that
those are still represented as ArrayValue.
2023-07-11 09:36:39 +10:00
Brett McBride 5853adabf1
phpdocs and example of weakening metric observer (#1078) 2023-07-11 09:36:04 +10:00
Brett McBride c9c83117e7
refactor attribute validation (#1072)
moving private method into a testable class, introduce attribute validation class
which applies to most attribute. LogRecord attributes are allowed to be complex,
so introduce a validator for these which lets everything through.
2023-07-11 09:35:24 +10:00
Brett McBride 3246ca8e4d
set schemaUrl for logs output (#1071) 2023-07-11 09:26:40 +10:00
Brett McBride cc92a07eac
update proto files to 1.0.0 (#1070)
no change from 0.20.0 (which was a release candidate)
2023-07-05 08:02:44 -04:00
Brett McBride 638799275c
require google/protobuf (native) (#1067)
We made protobuf implementation optional back in #949 however it seems to be tripping up
a number of developers. Since native + extension can be installed at the same time (with
extension taking priority), I think that users will be less surprised when starting out
if there is a working implementation by default.
2023-07-04 14:47:34 +10:00
Brett McBride 5e827ab7fc
improve logs console output (#1060)
support multiple scopes in console log output, and update batch example to illustrate
2023-07-04 14:46:57 +10:00
Brett McBride cb45b4a75d
fixing homogenous check for attributes with non-numeric keys (#1057)
use reset() instead of trying to get zero array key
2023-06-28 08:25:27 +02:00
Brett McBride d6e0689604
readme badges and cleanup (#1053)
* adding badges to the various readme files to make more obvious the current versions
* list all packages and versions in main readme
* remove old README documentation (excluding development-specific), and direct users to opentelemetry.io
* link to opentelemetry.io where possible in package readme
* adding a badge to link to releases
releases are not easy to find, since they exist only in the subtree split repository
2023-06-26 21:10:20 +10:00
Brett McBride a0601c41ec
adding sdk console metrics exporter (#1055)
to make getting started easier (in opentelemetry.io docs), create an sdk-based metrics
exporter. this means we can export all signals without needing a protobuf implementation.
since console export is only useful for playing around, the change in format to a
simpler human-readable output seems reasonable.
2023-06-26 20:59:08 +10:00
Brett McBride dc9501e8a9
adding support info to composer.json files (#1054) 2023-06-26 20:57:52 +10:00
Brett McBride 49638eae02
deprecate sdk/common/dsn (#1037)
I can't find any usage of these classes anywhere in main or contrib repo. rather than delete, lets deprecate and remove closer to release candidate
2023-06-23 21:02:56 +10:00
Brett McBride 58e19760e3
fixing broken links (#1052)
* fixing broken link in logs readme
* typo
* another broken link
2023-06-23 21:00:17 +10:00
Brett McBride 51137bfea6
adding support info to sdk composer (#1036)
* adding some links to try to make it easier for users to find the right support/repositories etc
just doing one composer file to see if it works, and will follow-up with more in a later PR
* change forum to chat
2023-06-23 17:49:28 +10:00
Brett McBride fed6413a76
moving some otlp code out of sdk (#1039)
otlp exporter code belongs in contrib/otlp
2023-06-23 10:31:32 +10:00
Brett McBride 4913926ec1
error log backtrace and OTEL_LOG_LEVEL support (#1043)
* Adding a backtrace to the errors reported via error_log (which is the default)
* Implement OTEL_LOG_LEVEL, which can be used to control which errors are reported via error_log. Note that
this doesn't use configuration code from the SDK, as the usage is in the API (because messages are logged
from many packages) and deptrac rightly complains about the dependency on SDK.
2023-06-23 10:30:46 +10:00
Brett McBride 29dc1a414f
fixing http client implementation (#1041)
We do not actually require an async http client, so use psr/http-client-implementation instead.
We depend on the psr/http-client interface, so require it (which has a side-effect of un-breaking
the symfony http client which is frequently auto-installed by php-http/discovery's plugin)
2023-06-23 10:24:12 +10:00
Brett McBride 8fe898bdb4
adding batch span processor builder (#1046) 2023-06-23 10:22:49 +10:00
Brett McBride 1caf77b436
fixing backwards-compatibility (#1044)
- sdk BC was not being loaded at all in the sdk package (only in the monorepo), so add it to autoload->files
- fixing api/common BC layer (removing .php and fixing one of the FQCNs)
2023-06-20 16:43:03 +10:00
Brett McBride 1aea1f23b9
moving api/common classes up to api (#1033)
- apply TC review feedback to move Globals to top-level.
it was suggested to move Instrumentation into its own package, but I chose instead to just move that dir
up to the top level of API
- added a BC layer to alias the moved classes
- added some more examples
2023-06-16 08:51:03 +10:00
Brett McBride d81874ed11
allow http/message 2 (#1034) 2023-06-15 16:35:51 +02:00
Brett McBride ea09e53519
drop attributes with non-homogenous array values (#1023)
per spec, arrays MUST contain only the same types. I've allowed for numeric types
(integer + double) to be treated as equivalent.
2023-06-09 09:34:20 +10:00
Brett McBride 22542528af
adding meter provider builder example (#1026)
adding an example using the meter provider builder, and deprecating a redundant method, `registerMetricReader`
2023-06-09 09:32:18 +10:00
Brett McBride e8ee4363e7
update proto to 0.20.0 (#1029) 2023-06-09 09:25:59 +10:00
Brett McBride 2601eaafe8
move trace flags consts into TraceFlags interface (#1028) 2023-06-07 22:34:13 +10:00
Brett McBride 32c161b167
rename span builder parameter (#1024)
TC feedback suggested to rename param to hint at the type (nano seconds)
2023-06-07 13:51:31 +02:00
Brett McBride 6a77cf5ba4
improve documented scope return values (#1025)
TC review suggests that DETACHED and INACTIVE responses need clarification
2023-06-07 13:49:12 +02:00
Brett McBride 23cc194da1
psalm check examples (#1006)
Configure psalm to run over all examples, and fixing the issues it identified.
2023-05-31 08:13:35 +02:00
Brett McBride 1b63a3b1c3
adding console metric exporter (#1005)
allow the existing metric exporter to be created from env vars, by creating a factory
and registering it against 'console'. Now, OTEL_METRICS_EXPORTER=console will create
a metrics provider with console output. Note that it lives in contrib/otlp, since it
uses the existing otlp converters.
2023-05-17 10:41:55 +10:00
Brett McBride 82b30dc437
remove container detector (#1004)
per spec, container detector has been moved into contrib and is published as a composer package
2023-05-17 08:34:51 +10:00
Brett McBride 65491ab66b
adding resource detectors to registry (#999)
To enable registering non-SDK resource detectors within the SDK, extend the SDK Registry.
Detectors will be looked up by name and applied as part of 'all', or as part of a list
of detectors
2023-05-10 09:16:45 +10:00
Brett McBride 5d35c998e7
remove proprietary new relic exporters (#998)
New Relic now fully supports OTLP ingestion, and having proprietary exporters is no longer their strategy. The proprietary exporters have been marked as abandoned in packagist, and suggest exporter-otlp as a replacement.
2023-05-09 20:20:50 +10:00
Brett McBride 593fa344bc
removing prometheus example (#996)
the example is very old, does not work, and it doesn't look like the capability
is in the spec these days. Remove the code so that it doesn't cause confusion.
2023-05-08 19:51:22 +10:00
Tobias Bachert e7be05c73e
Fix `weaken()` scope not preserved for first class callables when scope not equals target class (#995) 2023-05-08 09:17:00 +10:00
Brett McBride bd02259089
resourceinfo spec compliance, instrumentation attribute (#989)
Introduce spec-compliant ResourceInfo::merge, and deprecate our current implementation.
When merging resources, later (updating) keys should override existing keys, per spec.
Reorganise detectors so that environment has highest priority (per spec, OTEL_SERVICE_NAME should be the highest priority built-in way of setting service name)
Adding the experimental telemetry.auto.version attribute, if the auto-instrumentation extension is installed.
2023-05-08 09:15:45 +10:00
Brett McBride efe696f285
temporality preference from env (#990)
Implement OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE, which controls the temporality of meters when creating from environment vars.
Add OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION to variables, although we do not yet have anything that uses it.
2023-05-05 09:32:14 +10:00
Brett McBride c701693c25
remove 'include context' parameter from logging examples (#992)
the param was removed from spec, and our API implementation recently, but
I missed these examples.
2023-05-04 16:35:24 +02:00
Brett McBride 952c069792
adding batch LogRecord processor env config (#991)
Adding new spec variables for configuring batch LogRecord processor from environment.
2023-05-04 10:58:07 +10:00
Tobias Bachert 1976f53f92
Add branch aliases (#988) 2023-05-03 08:59:57 +10:00
Brett McBride 4890bd4a27
dotenv file plus rector (#983)
use docker compose 'env_file' to include all .env file vars in container env
make the default rector action dry-run, which allows developers to inspect code changes
before applying them (and therefore giving the option to disable new rules before they
are applied to WIP).
2023-05-02 19:53:04 +10:00
Tobias Bachert 77da9503fb
Use noop staleness handler factory by default (#987) 2023-04-30 20:06:59 +10:00
Tobias Bachert a7a28616b2
Move metric collection to `MeterProvider`-wide registry (#979)
* Add metric registry
* Use metric registry to record and collect metrics
* Minor cleanup
2023-04-27 08:15:20 +10:00
Brett McBride 6fd6a3c180
adding local dev prefer-lowest (#976)
Adding some make targets which will install composer dependencies with the lowest
package versions. This highlights some small issues with older versions, so bump up
the minimums of a few dev dependencies.

Adding more make targets:
- all-lowest (run all checks after updating with --prefer-lowest)
- all-checks (run all checks without first running a composer update)
- update-lowest (update dependencies to lowest installable versions)

Quieten unit test output (the previous testdox output is available via `make test-verbose`)
2023-04-27 08:14:56 +10:00
Brett McBride 9bccde9f03
update semantic conventions to v1.19 (#965)
* update semantic conventions to v1.19
* updating semconv readme
* dropping attribute values
I can't find any usage of the various AttributeValues being used, and other SIGs
no longer generate them, so removing them
* removing semconv usage from API
allow deprecations of moved/removed attributes so that we don't break things across different
semconv versions (similar to how java does it, except I moved them into a file which is
imported
2023-04-27 08:13:26 +10:00
Brett McBride 80ac91fddd
fixing symfony link in readme (#982) 2023-04-26 07:13:23 +02:00
Brett McBride 659a705d95
relax default logging levels (#975)
without a psr-3 logger, we use trigger_error. Using this with E_USER_ERROR is fatal, so adjust the level down.
2023-04-19 17:21:16 +02:00
Brett McBride 8f70a6d19f
apply logging spec updates (#977)
Removing include_trace_context parameter
Set ObservedTimestamp on emit if not already set
Rename logRecord to emit
2023-04-18 14:43:09 +02:00
Tobias Bachert 0e61e95f3c
Fix otlp json trace id and span id (#973)
* Fix otlp json trace id and span id format

* Ignore unknown fields in otlp json response

* Suppress incorrect phan error
2023-04-18 14:08:20 +02:00
Tobias Bachert 23762dbbd3
Split metric collection from metric streams (#972)
Split metric collection from metric streams
2023-04-15 22:09:43 +10:00
Brett McBride a06e5e4e45
Multiple log processors (#967)
adding support for multiple log processors
2023-04-15 09:27:50 +10:00
Brett McBride c687df160d
report dropped counts in non-otel exporters (#966)
per spec, exporters MUST report on dropped attributes/links/events using keys defined in spec
2023-04-15 09:25:44 +10:00
Brett McBride e22007a98e
documenting logs bridge api, adding memory exporter (#959)
* implement bridge api

* adding logs memory exporter

* clarify bridge api not for developers

* adding logger provider builder

* review feedback

* removing Bridge and documenting what a bridge is
2023-04-12 08:06:41 -04:00
Brett McBride 653a726959
new rector rules (#964)
apply one new rector rule, and disable FlipTypeControlToUseExclusiveTypeRector (which changes about 40 files, and IMO makes it harder to comprehend)
2023-04-07 12:36:40 +10:00
Cedric Ziel ca2df9f307
Update publish-otel-php-base-docker-image.yml (#961)
Use correct arm64 platform for building docker images.

My previous PR in #960 used the wrong platform for M1/Apple silicon
2023-04-05 18:55:19 -04:00
Cedric Ziel 72e9f56fbb
Build arm64 base images (#960) 2023-04-05 14:58:02 -04:00
Brett McBride 502df0eded
adding LogRecord phpdocs (#956)
clarify that timestamps expect timestamp in nanoseconds, plus minor logging example fixes.
2023-04-05 22:42:42 +10:00
Piotr Antosik a3abdcdb0d
add composer resource detector defaults (#952)
- add composer to defaults
- update readme: missing info about container & composer
2023-04-05 12:18:57 +10:00
Brett McBride 0a6d7cb8e4
fail if no protobuf implementation found (#958)
the otlp exporters (logs, metrics, traces) will fail to export if there is no protobuf implementation (which we have
just made optional, to allow users to choose between extension and native). Add a check to
the constructors which will throw a runtime exception.
If creating the exporter directly, it will be uncaught. If using a factory, it will report a
warning and return a no-op exporter.
2023-04-05 10:02:44 +10:00
Brett McBride dd23c8d0ea
pre-GA doco cleanup (#946)
moving lots of documentation into opentelemetry.io, which is
the official source and where we should send people in the
first instance.
2023-04-02 21:00:34 +10:00
Sem Schilder 711ebf98c6
Rename extension (#955) 2023-04-01 12:48:42 +02:00
Sem Schilder 4544cbd94a
Make protobuf implementation optional (#949)
* Make google/protobuf an optional dependency
* Update the README with more information on installing protobuf implementation
* Add some extra documentation in the OTLP exporter library
* Update proto/otel/README.md
2023-03-30 20:16:18 +11:00
Brett McBride 83bacc9d40
remove create_releases script (#945)
create_releases has been replaced by an improved version in https://github.com/opentelemetry-php/dev-tools
2023-03-29 08:02:36 -04:00
Cedric Ziel a2a4d4d0a1
Ensure base64 encoded values can be used as headers from env (#943)
This change instructs explode to extract at most 2 parts.

Given an example value of 
```
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic bla64=
```

The config parser would have created the elements, where only two are required. The trailing `=` in base64 headers would then have been effectively discarded, leading to invalid configuration.
2023-03-27 09:16:47 +11:00
Brett McBride c899f08dc1
adding brettmc company affiliation (#942) 2023-03-25 08:16:07 -04:00
Brett McBride 41945220b9
do not gitsplit sdk-contrib or tags (#939)
sdk-contrib is abandoned in packagist, because we publish the packages individually
and at independent versions. for the same reason, do not gitsplit tags, only main
as we do the tagging in the read-only repos now
2023-03-23 20:56:35 +11:00
Przemyslaw Delewski ac1d03784f
open stream failure (#940)
* open stream failure

* Update src/SDK/Resource/Detectors/Container.php

Co-authored-by: Tobias Bachert <git@b-privat.de>

---------

Co-authored-by: Tobias Bachert <git@b-privat.de>
2023-03-22 19:31:01 +01:00
Brett McBride 615917f5d4
adding logs signal (#934)
* initial work on logs signal

* supressing psalm error

* "fixing" 7.4 segfault
through trial and error, I found that it was consistently segfaulting in the sdk autoloader
tests, but by running them in a different order, the failures went away.

* adding logs tests

* rename example per feedback

* move log context injection into processors, per spec

* correctly set context on logs

* update logger name per feedback

* adding variables, map psr3 to otel severity, fix timestamp

* psr-3 loggers

* tests, psr3 v3 fix

* remove LogRecordDate and refactor SDK log record classes

* tests, tidy, improvements

* remove todos

* documentation

* check for valid span context

* removing psr-3 compatibility, per spec and feedback

* use InstrumentationScopeFactoryInterface

* apply attribute limits on readablelogrecord creation
per feedback, this should be more memory efficient for the processors

* group log record by resource/scope

* remove psr3 references from readme

* ignoring psalm error

* add trace context in Logger rather than processors
per feedback, and following the example in java and python SIGs, we
can add trace context to logs once, in the logger, rather than having
processors do it. The Context passed to processors is no longer used,
but retained for spec compliance.
2023-03-22 08:11:51 -04:00
Brett McBride c058a646f6
upgrade rector (#938)
use latest version, and apply suggested updates
2023-03-21 13:35:20 +11:00
Brett McBride 0538a5a7c7
fixing empty tracestate header handling (#936)
if an empty tracestate header was passed, we were emitting a warning (discovered in the demo app after enabling logging).
to fix this, check for empty string as well as null.
2023-03-16 18:45:15 +11:00
Piotr Antosik 640b6f53a0
Update exporter path in docs & makefile (#935) 2023-03-13 17:52:28 +01:00
Brett McBride 88ea7c3024
adding container detector (#933)
detect container id from cgroup or mountinfo
2023-03-03 09:18:42 +11:00
Piotr Antosik 746d25a7d1
Move grpc/grpc to dev dependency (#930) 2023-02-28 07:44:41 -05:00
Brett McBride 20f39b6a74
script to identify required releases (#928)
a script to identify which of our git-split repos have changes which are not in a release.
also creates release notes for the release, which can be dropped into the github UI
* print new release url
* relax symfony/yaml requirement
* warn about rate limiting if no token provided
2023-02-28 19:55:23 +11:00
Brett McBride da05ab83ce
fixing otlp+json example (#927)
fixing otlp+json example
2023-02-27 21:38:51 +11:00
Brett McBride 2a0a9e33e6
fixes and tests for MetricExporterFactory (#926)
Fixing grpc path and allowing compression from MetricExporerFactory
2023-02-16 10:00:14 +11:00
Brett McBride 19b9326751
relax composer version requirements (#918)
using self.version does not work when we have different components being released individually. ^1.0 seems like a sensible initial setting now that we have reached beta.
2023-02-16 00:44:20 +11:00
Przemyslaw Delewski 5f3e9cae9d
Update CONTRIBUTING.md (#925) 2023-02-14 12:44:41 -05:00
Brett McBride c6b0be7c89
remove older BC implementations (#923)
These BC features have been in place for multiple releases, it's time for them to retire.
2023-02-14 10:56:50 +11:00
Brett McBride e59f2c3cff
fixing phpunit 9.6 deprecations (#922)
phpunit v9.6 introduces a bunch of deprecations for things that will break in v10. This fixes the tests that are currently complaining.
2023-02-13 18:43:57 +11:00
Piotr Antosik 24af6ac173
fix PHP 7.4 preload error (#919) 2023-02-05 21:59:01 +11:00
Ricardo Fontanelli c4161a0ebe
Add scheme to collector endpoint on traces example (#913)
Add scheme to collector endpoint on traces example docker-composer file
2023-01-20 08:20:51 +11:00
Brett McBride 4b9f1200bf
adding a configuration for disabling auto-instrumentations (#909)
* adding a configuration for disabling auto-instrumentations
addressing review feedback from pdelewski, provide a mechanism that can be used to disable auto-instrumentation packages
without actually uninstalling them.
A new variable, OTEL_PHP_DISABLED_INSTRUMENTATIONS, has been added which accepts a list of instrumentation names to be disabled.
Each instrumentation can call Instrumentation::isDisabled to determine if they should bail without registering hooks.

* moving instrumentation disabled into Sdk class
2023-01-12 10:55:48 +01:00
Brett McBride 7b5ca0ce97
allow OTEL_SDK_DISABLED to disable sdk autoloading (#902)
* allow OTEL_SDK_DISABLED to disable sdk autoloading
* review feedback
- test for sdk disabled in initializer
- sdk disabled does not disable propagator, per spec
2023-01-11 10:05:28 +11:00
Przemyslaw Delewski ee26eaa5d8
Remove JaegerExporter and update interface (#908) 2023-01-10 09:25:34 +11:00
Brett McBride 2bd6bc5ff7
do not export empty metrics (#907)
If no metrics have been generated, do not send an empty export request (except via forceFlush())

Closes 905
2023-01-10 09:23:54 +11:00
Brett McBride 558e7ce30e
default logging to console (#899)
Rather than log nothing by default, log warnings and greater to console.
By providing a psr-3 logger, users can gain greater control over logging, including disabling it (via NullLogger)
2022-12-22 09:39:27 +11:00
Brett McBride c98866b3fa
update gitsplit regex to match beta releases (#898) 2022-12-13 11:42:17 +11:00
Brett McBride 425ebaf4f9
doco updates for beta (#895) 2022-12-12 09:05:21 -05:00
Brett McBride 02c1782667
adding php8.2 to build matrix (#896)
* adding 8.2 to build matrix

* 8.2 experimental

* relax deptrac

* allow style check to fail if experimental

* bump checkout action version
2022-12-12 09:05:09 -05:00
Brett McBride 616b356b83
tracestate + baggage todos (#894)
- remove baggage TODOs which have since been done.
- implement TODOs from tracestate to log warnings.
- tidy up tracestate code, simplify some const names.
2022-12-12 14:16:41 +11:00
Brett McBride 602ea8539f
move LoggerHolder to API (#893)
there is a requirement (and some outstanding todo's) to log errors and warnings from the API, so move
logger setup into API to facilitate this.
2022-12-12 09:01:17 +11:00
Brett McBride 0073d6dfe6
create text map propagators from registry (#885)
* create text map propagators from registry
removing undocumented dependency between sdk and extension by adding text map propagators to a registry
as part of composer autoloading, similar to how exporters, transports etc are treated.
* remove TextMapPropagatorFactory instances and register the singletons directly
* rename FactoryRegistry to just Registry
2022-12-10 08:42:47 +11:00
Brett McBride 5a51249c6b
removing jaeger exporters (#890)
Jaeger has dropped support for the jaeger exporter in favour of opentelemetry exporter. The upstream repos are now archived.
Support has been dropped from the opentelemetry collector, and other SIGs should follow soon.
ref: https://github.com/open-telemetry/opentelemetry-specification/pull/2858 and https://github.com/open-telemetry/opentelemetry-specification/issues/2859
2022-12-09 14:25:42 +11:00
Brett McBride f5698c8864
implement retrieve span and trace id as binary (#883)
per spec, https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#retrieving-the-traceid-and-spanid allow retrieving span and trace id in binary form
remove hex2bin calls from otlp span converter and use new binary accessor
2022-12-08 12:55:29 +11:00
Przemyslaw Delewski 7bfc1218d6
allow setting service name from auto instrumentation context (#881) 2022-12-07 23:23:19 +01:00
Brett McBride 02d94216e1
span status compliance (#884)
implement spec-compliance for span status:
- Ok is final
- Unset should be ignored
- Error can be updated to Ok

ref: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#set-status
2022-12-07 14:07:33 +11:00
Brett McBride 311afa265a
fixing default service name (#887)
* fixing some sdk/default resource values
- default service name should contain runtime name if available; java just appends ":java" so I did the same

Co-authored-by: Tobias Bachert <git@b-privat.de>
2022-12-07 09:58:33 +11:00
Brett McBride dc5ef24bd3
adding baggage example usage (#888)
adding a baggage example
2022-12-07 09:52:21 +11:00
Brett McBride a1e8aff01e
move exporter examples (#886)
moving exporter examples up one directory, where I think they are more obvious to find.
remove some old and broken grpc examples.
remove unused interface.
2022-12-07 09:00:09 +11:00
Brett McBride 587bc5aaf0
fix stream transport factory creation (#882)
when creating a stream from an endpoint string, the factory wasn't returning the stream. fix and add tests.
Co-authored-by: Tobias Bachert <git@b-privat.de>
2022-12-05 22:02:12 +11:00
Tobias Bachert fd8ac30f07
Run exports with the `Context` the `SpanProcessor` was created in (#880)
* Run exports in spanprocessor construction context

* Resolve psalm issues
2022-12-02 13:31:42 -05:00
Przemyslaw Delewski 0ce2fda813
fixing typo in name (#877) 2022-12-01 09:08:50 +11:00
Brett McBride 2e96621b0f
allow 16 char b3 trace id (#869)
b3 spec allows trace id to be 16 or 32 char. other SIGs left-pad with zero to resolve this.
2022-11-30 14:03:18 +11:00
Brett McBride 80afb1d948
updating membership lists (#876)
adding pdelewski, our newest maintainer
moving some past members into a new 'emeritus' section
2022-11-30 13:39:00 +11:00
Brett McBride 017c3e1c76
update contrib autoloading and gitsplit (#875)
* update grpc gitsplit destination
match the gitsplit destination repo to match package name: 'transport-grpc'
* adding missing autoload files for exporters
2022-11-30 09:54:23 +11:00
Brett McBride c735471aef
improve and expand otlp benchmark (#874)
- remove Mocker mocks, which were contributing extra time, and replace with no-op implementations
- adding extra benchmarks (batch vs simple, protobuf vs json)
2022-11-30 09:53:28 +11:00
Brett McBride 1ffd7e80eb
migrate/remove swoole (#871)
contrib/swoole has been moved into the contrib repo: https://github.com/open-telemetry/opentelemetry-php-contrib
2022-11-29 14:36:58 +11:00
Brett McBride 17f2fac397
tests and benchmark for baggage parsing (#873)
* tests and benchmark for baggage parsing
* adding percent-encoded test case
2022-11-29 14:33:40 +11:00
Brett McBride d37d4490d9
decode OTEL_RESOURCE_ATTRIBUTES values (#872)
per spec, resource attributes coming from environment should be decoded in
the same way that they would be if coming from a header
2022-11-29 14:32:26 +11:00
Brett McBride 01378ecf8a
disallow non-standard boolean config values (#870)
per spec, only 'true', 'false' are valid boolean values. anything else should be
interpreted as false and a warning emitted.
2022-11-29 14:31:09 +11:00
Marcos Passos 22c78cfd3b
Remove internal tag from Context::setStorage (#867)
This allows custom storage (eg for Swoole) to be used.
2022-11-26 07:26:34 +11:00
Brett McBride 904da75ee6
adding exporter + transport registry (#862)
* adding exporter + transport registry
to remove the hidden dependency between SDK and contrib, move all of the exporter knowledge out of
exporter factory, and invent a registry to hold those values. The registry can be added to by contrib
modules as part of composer autoloading.
This also allows users to override things like transports (eg, provide their own grpc transport).
Remove exporter's fromConnectionString as it's not in spec, and I couldn't get it to work nicely with the
registry idea.

* fixing up examples

* allow callables to be registered as factories
adding an example of replacing a registered transport factory with another implementation

* Registry to FactoryRegistry

* new relic exporter factory, tests

* review suggestions

* tidy

* change fromEnvironment() to create() in factories
2022-11-23 14:39:24 -05:00
Brett McBride 116e46d964
sdk autoloading (#854)
* sdk autoloading
* use instrumentation initializers
* basic sdk + autoloading documentation
* exampler filter from config
* configuration default types
2022-11-14 08:52:35 +11:00
Brett McBride f083b10909
refactor environment configuration (#859)
refactoring Environment access to allow configuration from multiple sources. Initially, the sources are env ($_SERVER) and php.ini, but this should allow us to add more sources in future without changing the API.
do not modify OTEL_EXPORTER_OTLP_TRACES_PROTOCOL
allow resolvers to return mixed
2022-11-10 09:48:17 +11:00
Erdem Köse 92e7a0d070
Fix OTLP GRPC example (#856) 2022-11-05 09:10:14 +11:00
Brett McBride 0b43fac729
refactor otlp exporter (#838)
* merge otlp exporters
continuing on from Nevay's work, this removes the individual OtlpHttp and OtlpGrpc exporters, and replaces with
Otlp\Exporter using a transport to manage grpc and http/protobuf complexity.

* tidy

* use mockery overload instead of prototype clone

* making all smoke-test examples work

* removing startBatch
verified that the call attributes have the same values when using TraceServiceClient

* tidy

* tidy

* Revert "use mockery overload instead of prototype clone"

This reverts commit bbb685b4d1.
Mocking proto-generated files segfaults with ext-protobuf (which is harder to diagnose when running in a child process, which
was required for fancy mockery mocking of "new". So, back to the prototype approach, and skip the tests if ext-protobuf enabled.

* tests without mocking protobuf

* test

* typo

* reverting FromConnectionStringInterface

* grpc headers

* revert to dumb transports, handle multiple protocols

* tidy, adding initial otlp json support

* self-review

* linting

* remove redundant interface

* Revert "remove redundant interface"

This reverts commit 350d40cdfe.

* fix getFloat

Co-authored-by: Tobias Bachert <git@b-privat.de>

* move withSignal into otlp-specific interface

* moving exporter/transport env handling into a new factory

* linting

* remove unused code

* tidy

* moving OtlpHttp into Otlp

* removing OtlpTransportFactoryInterface

* fix style

* fixing psalm error

* addressing review feedback

* replacing removed code

* fixing example

Co-authored-by: Tobias Bachert <git@b-privat.de>
2022-11-02 08:31:48 -04:00
Brett McBride ba9899278f
Sdk builder (#845)
Adding an SDK builder and example usage.
2022-10-31 08:09:01 +11:00
Tom Carrio 87989731ed
refactor: static access for EnvironmentVariablesTrait methods (#850)
* refactor: provide EnvironmentVariables static class for friendly-typed access
utilizes Accessor and Variables under the hood to provide consistent default values
2022-10-27 10:29:24 +11:00
Tobias Bachert 32d04f6a1d
Add support for global instrumentation initializer (#849)
* Add support for global instrumentation initializer

* Add `Configurator::createNoop()` to simplify disabling instrumentation
2022-10-26 08:09:33 -04:00
Brett McBride 4489eeca2e
removing event dispatcher (#848)
* removing event dispatcher
discussed in SIG to remove this unused code. It was going to be infrastructure for emitting metrics from other parts of the code, but that's been done in a better way now.

* remove EventContextIntegrationTest
2022-10-26 08:07:14 -04:00
Reiley Yang f6777575de
Update README.md (#847) 2022-10-19 21:24:07 -04:00
Tobias Bachert f6671ddd79
Add alternative instrumentation abstraction (#822)
* Add alternative instrumentation abstraction
* Provide global access to providers
Remove logs for now, will be replaced with `LoggerProvider` in the future.
2022-10-17 08:57:57 +11:00
Tobias Bachert f73a835ed2
Add self-diagnostic metrics to `BatchSpanProcessor` (#828)
* Add self-diagnostic metrics to `BatchSpanProcessor`

* Removing unnecessary import

Co-authored-by: Bob Strecansky <bob.strecansky@gmail.com>
2022-10-12 11:02:34 -04:00
Brett McBride 10830f2683
resolve deptrac baseline (#844)
* resolve deptrac baseline
Nevay found that an @internal annotation in NonRecordingSpan was the cause of the violation, so
remove it.

* make psalm happy
2022-10-12 09:06:29 -04:00
Tobias Bachert 3866a82d92
Refactor transport layer (#831)
- move content type from `::send()` to transport property
- move otlp exporter to `Otlp\` namespace
2022-10-12 10:01:20 +11:00
Tobias Bachert a167add2df
Drop general identity attributes by default (#843) 2022-10-12 09:12:54 +11:00
Tobias Bachert 47f8ab977d
Add `trace` convenience function that encapsulates `try-catch-finally` boilerplate code (#841)
* Add `trace` convenience function that encapsulates common boilerplate code
2022-10-11 09:32:35 +11:00
Tobias Bachert 7940773a31
Fix process resource detector triggers warning if running with unknown uid (#840) 2022-10-10 09:18:32 +11:00
leo108 8562d0d510
Grpc metadata value must be an array (#839) 2022-10-10 09:17:43 +11:00
Brett McBride a3a47a6ba4
adding OTEL_SDK_DISABLED support (#833) 2022-10-07 16:47:54 +11:00
Brett McBride 0e0c67d326
docker compose v2 support (#834)
adding the ability to use compose v2 (via .env), and adding a makefile target to locally build dev image
2022-10-05 09:54:12 +11:00
Tobias Bachert 215731f639
Improve `open-telemetry/context` documentation (#830) 2022-09-23 14:15:46 -04:00
Amber c0a62795e4
Refactor span context (#801)
* Otel-php:632 Move stack trace formatting out of Span class

* added function usages

* fix linting errors

* Added documentation for adding Span Attributes

* removing TracingUtl class

* Refactor TraceState's __toString method

* Added path with @covers to remove warnings

* Added @coversDefaultClass annotation

* fix to check if iterable is empty

* fixed for faling test case

* unit test

* Resolved review Comments

* reverting changes

* removing check for empty iterable span list

* review changes for SpanProcessor incorrect calls to SpanExporter::forceFlush()

* updated test case

* resolved review comments

* reverted changes for batch span processors

* reverting changes for batch span proccessor

* merge upstream and changes

* updating changes

* Refactoring SpanContext

* updating changes

* updated test cases

* updated changes suggested after review

* Revert "Reverting back to previous commit"

This reverts commit 941f368da3.

* updating changes after review

* unused use statement

* added unit test and resolved review comments

* Removed Double underscores from constant variables

* Removed constants from SpanContext.php to remove duplicacy

* updated failing test

* Moving Factory Methods back into SpanContext.php

* modified constructor of SpanContext

* updated SpanContext

* Modified use of additional if statement

* corrected parsing error
2022-09-21 10:37:19 -04:00
Tobias Bachert be3f88fa6c
Fix fiber support not loaded in `open-telemetry/context` (#829)
* Add missing autoload entry
* Fix fiber tests
* Trigger error if fiber support cannot be loaded
2022-09-20 09:31:33 +10:00
Tobias Bachert deeb07a890
Add interfaces for `Context` and `ContextKey` (#820)
* Add `ContextKeyInterface`
* Add `ContextInterface`
* Combine `SpanBuilderInterface::setParent()` and `::setNoParent()`
* Remove `NullPropagator`
* Fix `Context::with()` typehint
* Remove `Context::withContextValue()` suggestion
2022-09-19 09:40:32 +10:00
Tobias Bachert 15ebaeb98c
Change `SpanExporter::export()` return value to boolean (#827) 2022-09-19 07:27:51 +10:00
Brett McBride b551294d3f
export otlp InstrumentationScope attributes (#825)
* export otlp InstrumentationScope attributes

* remove redundant setting of dropped attributes count
2022-09-14 20:59:51 -04:00
Tobias Bachert 84142d35e9
Rename `AbstractSpan` to `Span` for consistent access to static methods (#824)
* Rename `AbstractSpan` to `Span` for consistent access to static methods
* Add BC layer for `AbstractSpan`
2022-09-15 09:07:52 +10:00
Tobias Bachert c000590a53
Add intermediate transport layer between http/grpc client and exporter (#809)
* Add `Future::map()` to allow async processing without explicit async dependency

* Add `TransportInterface` abstraction

* Fix style

* Add transport and future tests

* Replace `HttpSpanExporterTrait` with `PsrTransport`

* Update transports

- ignore invalid compression
- add stream transport

* Handle partial success response
2022-09-14 08:36:49 -04:00
Tobias Bachert 6196d7a809
Use array lookup instead of recursion in `Context` (#821)
* Use array instead of recursion in `Context`

* Move span and baggage context key to context package

* Add additional context tests
2022-09-14 08:36:11 -04:00
Tobias Bachert ad3ccd8139
Add debug scope to warn on incorrect scope usage (#823)
* Add debug scope to warn on incorrect scope usage

* Enable assertions in unit tests
2022-09-12 22:34:52 -04:00
Brett McBride f5e66e91dd
require protobuf extension for otlp exporters (#818)
* require protobuf extension for otlp exporters
* adding grpc native library dependency
2022-09-12 10:11:10 +10:00
Tobias Bachert 776273ca8a
Remove scope bound example implementations (#819)
Removes ScopeBound... classes to reduce the API surface.

- ScopeBoundCallable: Was intended for event loops. Event loop decorators should instead implement this in a way that fits the specific loop API the best with regard to avoiding unnecessary references to arguments and error handling.
(The implementation was (mostly) sufficient for react/event-loop but shouldn't be used for revolt/event-loop.)
- ScopeBoundPromise: Was only intended as very basic example implementation. An actual implementation has to hook into the specific promise implementation to capture the context of the initial promise.
(I'm not sure how useful promise/future support is in general, there are scenarios where we cannot preserve the context association, e.g. when extracting/awaiting the value.)
2022-09-10 13:26:11 +10:00
Brett McBride 6e385b96f9
document exporters as installable packages (#817) 2022-09-08 16:18:56 +10:00
Brett McBride ac3a35d85c
fixing php8.2 string usage (#810)
This resolves some deprecation warnings in php 8.2:
Deprecated: Using ${var} in strings is deprecated, use {$var} instead
2022-09-07 23:03:20 +10:00
Kishan Sangani 651f949cd8
Updated readme (#816) 2022-09-07 09:01:54 -04:00
Brett McBride 2cb5d6b0df
ignore phpstan false positive (#813) 2022-09-07 22:42:38 +10:00
Bob Strecansky e6e13b2561
Update CODEOWNERS to use the @open-telemetry/php-approvers (#814) 2022-09-07 22:42:09 +10:00
Kishan Sangani c3170e3bd2
Update README to include extension packages (#812)
* Added extension packages search link on packagist
2022-09-07 13:50:46 +10:00
Brett McBride 9c8ce2fa91
gitsplit contrib components (#804)
* gitsplit exporters
* gitsplit swoole context
2022-09-06 22:51:24 +10:00
Brett McBride ea83a0cff3
bump protobuf to 0.19, handle grpc partial success (#806)
bump protobuf to 0.19, handle partial success for otlp+grpc (otlp+http to follow)
2022-09-06 22:50:17 +10:00
Tobias Bachert 77838b3b9c
Fix `Future<T>` should be covariant (#808) 2022-08-28 21:49:45 +10:00
Kishan Sangani 0f308492a1
Added B3Propagator for B3 Single Header (#691)
* Added B3Propagator Class to handle two configurations and storing debug flag in the returned context
* Updated B3Propagator extract according to the clarification in the specs; updated test cases
2022-08-24 22:56:49 +10:00
Tobias Bachert 2457c76015
Prevent concurrent `::export()` calls in span processor (#788)
* Prevent concurrent `::export()` calls in batch span processor
* Prevent concurrent `::export()` calls in simple span processor
* Allow disabling auto-flush in batch processor `::onEnd()`
* Include in-flight batches in queue limit
* Handle exporter exceptions to prevent termination of worker
* Use `LogsMessagesTrait`
2022-08-24 22:52:04 +10:00
Brett McBride 74eda3d89d
adding runkit to developer docker image (#800)
runkit7 is used by AWS instrumentation over in -contrib
in passing, bump ast to latest stable version
2022-08-19 10:22:03 -04:00
Brett McBride cb002a80b1
adding getTracerProvider to Instrumentation (#797) 2022-08-13 10:48:35 +10:00
Sumit Kashyap d05ea65186
Restructure contrib directory (#793)
* Restructure contrib directory
2022-08-13 10:37:42 +10:00
Brett McBride 4dd375fdb8
removing psalm security analysis workflow (#799)
we already run psalm in the php workflow. this one doesn't add much, and is more flaky. we have decided that the serif uploading is not very important since we have good makefile-based ability for devs to run this all locally before pushing
2022-08-12 20:10:39 -04:00
1336 changed files with 63586 additions and 27756 deletions

View File

@ -1,2 +1,5 @@
PHP_USER=php
XDEBUG_MODE=debug
PHP_CS_FIXER_IGNORE_ENV=true
#docker-compose or "docker compose" for v1/v2 respectively, note that v1 support ends 06/2023
DOCKER_COMPOSE=docker compose

View File

@ -17,3 +17,5 @@ What did you see instead?
**Additional context**
Add any other context about the problem here.
<sub>**Tip**: [React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>

View File

@ -17,3 +17,5 @@ Which alternative solutions or features have you considered?
**Additional context**
Add any other context about the feature request here.
<sub>**Tip**: [React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>

22
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,22 @@
---
version: 2
updates:
- package-ecosystem: "composer"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "docker"
directory: "/docker"
schedule:
interval: "daily"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "docker-compose"
directory: "/"
schedule:
interval: "daily"

20
.github/workflows/fossa.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: FOSSA scanning
on:
push:
branches:
- main
permissions:
contents: read
jobs:
fossa:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
- uses: fossas/fossa-action@3ebcea1862c6ffbd5cf1b4d0bd6b3fe7bd6f2cac # v1.7.0
with:
api-key: ${{secrets.FOSSA_API_KEY}}
team: OpenTelemetry

50
.github/workflows/ossf-scorecard.yml vendored Normal file
View File

@ -0,0 +1,50 @@
name: OSSF Scorecard
on:
push:
branches:
- main
schedule:
- cron: "17 0 * * 1" # once a week
workflow_dispatch:
permissions: read-all
jobs:
analysis:
runs-on: ubuntu-latest
permissions:
# Needed for Code scanning upload
security-events: write
# Needed for GitHub OIDC token if publish_results is true
id-token: write
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: ossf/scorecard-action@05b42c624433fc40578a4040d5cf5e36ddca8cde # v2.4.2
with:
results_file: results.sarif
results_format: sarif
publish_results: true
# file_mode is needed in this repo because .gitattributes excludes the .github directory
# (see https://github.com/ossf/scorecard/issues/4679#issuecomment-3013550752)
file_mode: git
# Upload the results as artifacts (optional). Commenting out will disable
# uploads of run results in SARIF format to the repository Actions tab.
# https://docs.github.com/en/actions/advanced-guides/storing-workflow-data-as-artifacts
- name: "Upload artifact"
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: SARIF file
path: results.sarif
retention-days: 5
# Upload the results to GitHub's code scanning dashboard (optional).
# Commenting out will disable upload of results to your repo's Code Scanning dashboard
- name: "Upload to code-scanning"
uses: github/codeql-action/upload-sarif@76621b61decf072c1cee8dd1ce2d2a82d33c17ed # v3.29.5
with:
sarif_file: results.sarif

View File

@ -6,20 +6,70 @@ on:
pull_request:
branches: [ main ]
permissions:
contents: read
jobs:
php:
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.experimental }}
strategy:
fail-fast: false
matrix:
php-version: ['7.4', '8.0', '8.1']
os: [ubuntu-latest]
extensions: ['ast, grpc', 'ast, grpc, protobuf-3.20.0']
php-version: ['8.1', '8.2', '8.3']
experimental: [false]
composer_args: [""]
include:
- php-version: 8.4
experimental: false
composer_args: "--ignore-platform-reqs"
- php-version: 8.5
experimental: true
composer_args: "--ignore-platform-reqs"
env:
extensions: ast, grpc, opentelemetry, protobuf
steps:
- uses: actions/checkout@v2
- name: Set cache key
id: key
run: |
echo "key=$(date +'%Y-%U')" >> $GITHUB_ENV
- uses: actions/checkout@v4
- uses: gacts/run-and-post-run@v1
id: post-run-command
with:
post: |
echo "::group::Steps"
echo "composer=${{steps.composer.outcome}}"
echo "style=${{steps.style.outcome}}"
echo "deps=${{steps.deps.outcome}}"
echo "phan=${{steps.phan.outcome}}"
echo "psalm=${{steps.psalm.outcome}}"
echo "phpstan=${{steps.phpstan.outcome}}"
echo "unit=${{steps.unit.outcome}}"
echo "integration=${{steps.integration.outcome}}"
echo "::endgroup::"
if [ ${{ steps.composer.outcome == 'failure' || steps.style.outcome == 'failure' || steps.deps.outcome == 'failure' || steps.phan.outcome == 'failure' || steps.psalm.outcome == 'failure' || steps.phpstan.outcome == 'failure' || steps.unit.outcome == 'failure' || steps.integration.outcome == 'failure' }} == true ]; then \
echo "::error::One or more steps failed"; \
fi
- name: Setup cache environment
id: extcache
uses: shivammathur/cache-extensions@v1
with:
php-version: ${{ matrix.php-version }}
extensions: ${{ env.extensions }}
key: ${{ env.key }}
- name: Cache extensions
uses: actions/cache@v4
with:
path: ${{ steps.extcache.outputs.dir }}
key: ${{ steps.extcache.outputs.key }}
restore-keys: ${{ steps.extcache.outputs.key }}
- name: Setup PHP
uses: shivammathur/setup-php@v2
@ -27,53 +77,99 @@ jobs:
php-version: ${{ matrix.php-version }}
coverage: xdebug
tools: php-cs-fixer
extensions: ${{ matrix.extensions }}
extensions: ${{ env.extensions }}
- name: Validate composer.json
run: composer validate
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
uses: actions/cache@v4
with:
path: vendor
key: ${{ runner.os }}-${{ matrix.php-version }}-php-${{ hashFiles('**/composer.json') }}
key: ${{ runner.os }}-${{ matrix.php-version }}-vendor-${{ hashFiles('composer.json') }}
restore-keys: |
${{ runner.os }}-${{ matrix.php-version }}-php-
${{ runner.os }}-${{ matrix.php-version }}-vendor-
- name: Cache test tools
id: test-tools-cache
uses: actions/cache@v4
with:
path: vendor-bin
key: ${{ runner.os }}-${{ matrix.php-version }}-vendor-bin-${{ hashFiles('vendor-bin/*/composer.json') }}
restore-keys: |
${{ runner.os }}-${{ matrix.php-version }}-vendor-bin-
- name: Install dependencies
id: composer
if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --prefer-dist --no-progress --no-suggest
run: |
composer --version
composer install --prefer-dist --no-progress ${{ matrix.composer_args }}
- name: Check Style
run: vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --dry-run --stop-on-violation --using-cache=no -vvv
id: style
continue-on-error: ${{ matrix.experimental }}
env:
PHP_CS_FIXER_IGNORE_ENV: 1
run: |
vendor-bin/php-cs-fixer/vendor/bin/php-cs-fixer --version
vendor-bin/php-cs-fixer/vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --dry-run --stop-on-violation --using-cache=no -vvv
- name: Check Dependencies
run: vendor/bin/deptrac --formatter=github-actions --report-uncovered
id: deps
continue-on-error: ${{ matrix.experimental }}
run: |
vendor-bin/deptrac/vendor/bin/deptrac --version
vendor-bin/deptrac/vendor/bin/deptrac --formatter=github-actions --report-uncovered
- name: Run Phan
id: phan
continue-on-error: ${{ matrix.experimental }}
env:
XDEBUG_MODE: off
PHAN_DISABLE_XDEBUG_WARN: 1
run: vendor/bin/phan
run: |
vendor-bin/phan/vendor/bin/phan --version
vendor-bin/phan/vendor/bin/phan
- name: Run Psalm
run: vendor/bin/psalm --output-format=github --php-version=${{ matrix.php-version }}
id: psalm
continue-on-error: ${{ matrix.experimental }}
run: |
vendor-bin/psalm/vendor/bin/psalm --version
vendor-bin/psalm/vendor/bin/psalm --output-format=github
- name: Run Phpstan
run: vendor/bin/phpstan analyse --error-format=github
id: phpstan
continue-on-error: ${{ matrix.experimental }}
run: |
vendor/bin/phpstan --version
vendor/bin/phpstan analyse --error-format=github
- name: Run PHPUnit (unit tests)
run: vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover --testsuite unit
id: unit
continue-on-error: ${{ matrix.experimental }}
run: |
vendor/bin/phpunit --version
php -dzend.assertions=1 vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover --testsuite unit
- name: Run PHPUnit (integration tests)
id: integration
continue-on-error: ${{ matrix.experimental }}
run: vendor/bin/phpunit --testsuite integration
- name: Code Coverage
run: bash <(curl -s https://codecov.io/bash) -F ${{ matrix.php-version }}
uses: codecov/codecov-action@v5
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./coverage.clover
flags: ${{ matrix.php-version }}
verbose: false
packages:
uses: opentelemetry-php/gh-workflows/.github/workflows/validate-packages.yml@main
needs: php
with:
matrix_extension: '["ast, json, grpc"]'
matrix_php_version: '["8.1", "8.2", "8.3"]'
install_directory: '~/.test/.packages'

View File

@ -0,0 +1,34 @@
name: "Generate API Documentation"
on:
push:
branches:
- "main"
workflow_dispatch:
permissions:
contents: read
jobs:
documentation:
permissions:
pages: write # required for GitHub Pages deployment
id-token: write # required for GitHub Pages deployment
name: "Documentation"
runs-on: "ubuntu-latest"
steps:
- name: "Checkout"
uses: "actions/checkout@v4"
- name: "Build"
uses: "phpDocumentor/phpDocumentor@v3.8.1"
with:
target: "docs/build"
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: 'docs/build'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

View File

@ -1,29 +0,0 @@
---
name: Psalm Security Analysis
on:
pull_request:
branches: [main]
paths-ignore:
- '**/*.md'
- '**/*.txt'
jobs:
psalm:
name: Psalm
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Psalm
uses: docker://vimeo/psalm-github-actions
with:
composer_require_dev: true
composer_ignore_platform_reqs: true
security_analysis: true
report_file: results.sarif
- name: Upload Security Analysis results to GitHub
uses: github/codeql-action/upload-sarif@v1
with:
sarif_file: results.sarif

View File

@ -3,35 +3,57 @@ on:
schedule:
- cron: "0 0 * * 0"
workflow_dispatch:
push:
paths:
- docker/Dockerfile
- .github/workflows/publish-otel-php-base-docker-image.yml
pull_request:
paths:
- docker/Dockerfile
- .github/workflows/publish-otel-php-base-docker-image.yml
permissions:
contents: read
jobs:
push_to_registry:
name: OpenTelemetry PHP base docker image creation
strategy:
matrix:
php-version: ['7.4', '8.0', '8.1']
php-version: ['8.1', '8.2', '8.3', '8.4']
runs-on: ubuntu-latest
permissions:
packages: write
contents: read
timeout-minutes: 500
steps:
- name: check out the repo
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
uses: docker/setup-buildx-action@v3
- name: Login to GitHub Container Registry
uses: docker/login-action@v1
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push ${{ matrix.php-version }} to ghcr.io
uses: docker/build-push-action@v2
uses: docker/build-push-action@v6
if: github.ref != 'refs/heads/main'
with:
push: false
file: docker/Dockerfile
build-args: PHP_VERSION=${{ matrix.php-version }}
platforms: linux/amd64,linux/arm/v8,linux/arm64
- name: Build and push ${{ matrix.php-version }} to ghcr.io
uses: docker/build-push-action@v6
if: github.ref == 'refs/heads/main'
with:
push: true
file: docker/Dockerfile
build-args: PHP_VERSION=${{ matrix.php-version }}
platforms: linux/amd64,linux/arm/v8,linux/arm64
tags: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${{ matrix.php-version }}

22
.github/workflows/shellcheck.yml vendored Normal file
View File

@ -0,0 +1,22 @@
name: Shellcheck
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
permissions:
contents: read
jobs:
shellcheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install shellcheck
run: sudo apt update && sudo apt install --assume-yes shellcheck
- name: Run shellcheck
run: find . -name \*.sh | xargs shellcheck --severity=warning

View File

@ -9,6 +9,9 @@ on:
create:
workflow_dispatch:
permissions:
contents: read
jobs:
gitsplit:
runs-on: ubuntu-latest

8
.gitignore vendored
View File

@ -2,6 +2,8 @@ composer.phar
composer.lock
var/
vendor/
vendor-bin/**/vendor/
vendor-bin/**/composer.lock
coverage.clover
tests/coverage
.php-cs-fixer.cache
@ -28,3 +30,9 @@ tests/TraceContext/W3CTestService/trace-context
# deptrac cache
/.deptrac.cache
# output from phpdoc
docs/build
# cache from phpdoc
.phpdoc

View File

@ -8,8 +8,6 @@ project_url: "https://github.com/open-telemetry/opentelemetry-php.git"
splits:
- prefix: "proto/otel"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/gen-otlp-protobuf.git"
- prefix: "thrift/jaeger"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/gen-jaeger-thrift.git"
- prefix: "src/Context"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/context.git"
- prefix: "src/SemConv"
@ -18,13 +16,22 @@ splits:
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/api.git"
- prefix: "src/SDK"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/sdk.git"
- prefix: "src/Contrib"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/sdk-contrib.git"
- prefix: "src/Config/SDK"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/config-sdk.git"
- prefix: "src/Contrib/Otlp"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/exporter-otlp.git"
- prefix: "src/Contrib/Grpc"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/transport-grpc.git"
- prefix: "src/Contrib/Zipkin"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/exporter-zipkin.git"
- prefix: "src/Extension/Propagator/B3"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/extension-propagator-b3.git"
- prefix: "src/Extension/Propagator/CloudTrace"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/extension-propagator-cloudtrace.git"
- prefix: "src/Extension/Propagator/Jaeger"
target: "https://${GH_TOKEN}@github.com/opentelemetry-php/extension-propagator-jaeger.git"
# List of references to split (defined as regexp)
origins:
- ^main$
- ^test$
- ^split$
- ^v\d+\.\d+\.\d+$
- ^\d+\.\d+\.\d+$

View File

@ -44,7 +44,7 @@ return [
//
// Note that the **only** effect of choosing `'5.6'` is to infer that functions removed in php 7.0 exist.
// (See `backward_compatibility_checks` for additional options)
'target_php_version' => '7.4',
'target_php_version' => '8.1',
// If enabled, missing properties will be created when
// they are first seen. If false, we'll report an
@ -284,6 +284,9 @@ return [
'PhanAccessClassInternal',
'PhanAccessMethodInternal',
'PhanAccessPropertyInternal',
'PhanTypeMismatchPropertyReal',
'PhanTemplateTypeNotUsedInFunctionReturn',
'PhanUndeclaredClassAttribute',
],
// A regular expression to match files to be excluded
@ -318,7 +321,7 @@ return [
'exclude_analysis_directory_list' => [
'vendor/',
'proto/',
'thrift/',
'src/Config/SDK',
],
// Enable this to enable checks of require/include statements referring to valid paths.
@ -369,18 +372,17 @@ return [
'src',
'proto/otel/GPBMetadata',
'proto/otel/Opentelemetry',
'thrift',
'vendor/packaged/thrift',
'vendor/composer',
'vendor/grpc/grpc/src/lib',
'vendor/guzzlehttp',
'vendor/tbachert/spi/src',
'vendor/psr',
'vendor/php-http',
'vendor/phan/phan/src/Phan',
'vendor/phpunit/phpunit/src',
'vendor/promphp/prometheus_client_php/src',
'vendor/google/protobuf/src',
'vendor/cloudevents/sdk-php/src',
'vendor/ramsey/uuid/src',
'vendor/nyholm/psr7-server/src',
'vendor/symfony/config',
],
// A list of individual files to include in analysis

View File

@ -25,10 +25,11 @@ return $config->setRules([
'blank_line_before_statement' => true,
'cast_spaces' => true,
'declare_strict_types' => true,
'function_typehint_space' => true,
'type_declaration_spaces' => true,
'include' => true,
'lowercase_cast' => true,
'new_with_braces' => true,
'new_with_parentheses' => true,
'no_blank_lines_after_class_opening' => true,
'no_extra_blank_lines' => true,
'no_leading_import_slash' => true,
'no_trailing_whitespace' => true,
@ -41,9 +42,9 @@ return $config->setRules([
'phpdoc_scalar' => true,
'phpdoc_types' => true,
'short_scalar_cast' => true,
'single_blank_line_before_namespace' => true,
'blank_lines_before_namespace' => true,
'single_quote' => true,
'trailing_comma_in_multiline' => true,
'trailing_comma_in_multiline' => ['elements' => ['arrays', 'parameters', 'match']],
])
->setRiskyAllowed(true)
->setFinder($finder);

View File

@ -12,4 +12,4 @@
# https://help.github.com/en/articles/about-code-owners
#
* @bobstrecansky @zsistla @tidal @brettmc
* @open-telemetry/php-approvers

View File

@ -1,37 +1,307 @@
# Contributing Guide
## Introduction
Welcome to the OpenTelemetry PHP repository! We appreciate your interest in contributing and helping improve this project. No contribution is too small—whether you're fixing a typo, improving documentation, or implementing a major feature, we value your help.
This repository is part of the larger OpenTelemetry ecosystem, aimed at providing observability solutions for PHP applications. If you have any questions, feel free to ask in our community channels (See further help below). Your contributions make a difference!
## Pre-requisites
To contribute effectively, ensure you have the following tools installed:
* PHP 8.1 or higher (Check supported PHP versions)
We aim to support officially supported PHP versions, according to https://www.php.net/supported-versions.php. The
developer image `ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base` is tagged as `8.1`, `8.2` and `8.3`
respectively, with `8.1` being the default. You can execute the test suite against other PHP versions by running the
following command:
```bash
PHP_VERSION=8.1 make all
#or
PHP_VERSION=8.3 make all
```
For repeatability and consistency across different operating systems, we use the [3 Musketeers pattern](https://3musketeers.pages.dev/). If you're on Windows, it might be a good idea to use Git bash for following the steps below.
**Note: After cloning the repository, copy `.env.dist` to `.env`.**
Skipping the step above would result in a "`The "PHP_USER" variable is not set. Defaulting to a blank string`" warning
We use `docker` and `docker compose` to perform a lot of our static analysis and testing. If you're planning to develop for this library, it'll help to install
[docker engine](https://docs.docker.com/engine/install/) and the [compose plugin](https://docs.docker.com/compose/install/).
Development tasks are generally run through a `Makefile`. Running `make` or `make help` will list available targets.
## Workflow
### Pull Requests
To propose changes to the codebase, you need
to [open a pull request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request)
to the opentelemetry-php project.
After you open the pull request, the CI will run all the
associated [github actions](https://github.com/open-telemetry/opentelemetry-php/actions/workflows/php.yml).
To ensure your PR doesn't emit a failure with GitHub actions, it's recommended that you run the important CI tests locally with the following command:
```bash
make all # composer update, then run all checks
make all-lowest # composer update to lowest dependencies, then run all checks
```
This does the following things:
* Installs/updates all the required dependencies for the project
* Uses [Rector](https://github.com/rectorphp/rector) to refactor your code according to our standards.
* Uses [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) to style your code using our style preferences.
* Uses [Deptrac](https://github.com/qossmic/deptrac) to check for dependency violations inside our code base
* Makes sure the composer files for the different components are valid
* Runs all of our [phpunit](https://phpunit.de/) unit tests.
* Performs static analysis with [Phan](https://github.com/phan/phan), [Psalm](https://psalm.dev/)
and [PHPStan](https://phpstan.org/user-guide/getting-started)
## Local Run/Build
To ensure you have all the correct packages installed locally in your dev environment, you can run
```bash
make install
```
This will install all the library dependencies to
the `/vendor` directory.
To update these dependencies, you can run
```bash
make update
```
To downgrade to the lowest dependencies, you can run
```shell
make update-lowest
```
To run all checks without doing a composer update:
```shell
make all-checks
```
## Testing
To make sure the tests in this repo work as you expect, you can use the included docker test wrapper.
To run the test suite, execute
```bash
make test
```
This will output the test output as well as a test coverage analysis (text + html - see `tests/coverage/html`). Code
that doesn't pass our currently defined tests will emit a failure in CI
## Contributing Rules
Even though it may not be reflected everywhere in the codebase yet, we aim to provide software which is easy to read and change.
The methods described in Clean Code book(s) by Robert C. Martin (Uncle Bob) are a de facto industry standards nowadays.
Reading those books is highly recommended, however you can take a look at the examples given at [Clean Code PHP](https://github.com/jupeter/clean-code-php).
While we have no rule to strictly follow said methods and patterns, they are highly recommended as an orientation for
your pull requests and to be referenced in reviews.
We might add additional guidelines regarding for example testing in the future.
## Additional Information
### Automatic Refactoring and Upgrading
We use [Rector](https://github.com/rectorphp/rector) to automatically refactor our code according to given standards
and upgrade the code to supported PHP versions.
The associated configuration can be found [here](./.rector.php)
If you want to check what changes would be applied by rector, you can run:
```bash
make rector
```
This command will simply print out the changes `rector` would make without actually changing any code.
To refactor your code following our given standards, you can run:
```bash
make rector-write
```
This command applies the changes to the code base.
Make sure to run `make style` (see below) after running the `rector`command as the changes might not follow our coding standard.
### Styling
We use [PHP-CS-Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) for our code linting and standards fixer. The
associated configuration can be found [here](./.php-cs-fixer.php)
To ensure that your code follows our coding standards, you can run:
```bash
make style
```
This command executes a required check that also runs during CI. This process performs the required fixes and prints them
out. Code that doesn't meet the style pattern will emit a failure with GitHub actions.
### Static Analysis
We use [Phan](https://github.com/phan/phan/) for static analysis. Currently, our phan configuration is just a standard
default analysis configuration. You can use our phan docker wrapper to easily perform static analysis on your changes.
To run Phan, one can run the following command:
```bash
make phan
```
This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs
during CI and is a required check. Code that doesn't match the standards that we have defined in
our [phan config](https://github.com/open-telemetry/opentelemetry-php/blob/master/.phan/config.php) will emit a failure
in CI.
We also use [Psalm](https://psalm.dev/) as a second static analysis tool.
You can use our psalm docker wrapper to easily perform static analysis on your changes.
To run Psalm, one can run the following command:
```bash
make psalm
```
This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs
during CI and is a required check. Code that doesn't match the standards that we have defined in
our [psalm config](https://github.com/open-telemetry/opentelemetry-php/blob/main/psalm.xml.dist) will emit a failure in
CI.
We use [PHPStan](https://github.com/phpstan/phpstan) as our third tool for static analysis. You can use our PHPStan
docker wrapper to easily perform static analysis on your changes.
To perform static analysis with PHPStan run:
```bash
make phpstan
```
This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs
during CI and is a required check. Code that doesn't match the standards that we have defined in
our [PHPStan config](https://github.com/open-telemetry/opentelemetry-php/blob/main/phpstan.neon.dist) will emit a
failure in CI.
### Code Coverage
We use [codecov.io](https://about.codecov.io/) to track code coverage for this repo. This is configured in the [php.yaml github action](https://github.com/open-telemetry/opentelemetry-php/blob/main/.github/workflows/php.yml#L71-L72). We don't require a specific level of code coverage for PRs to pass - we just use this tool in order to understand how a PR will potentially change the amount of code coverage we have across the code base. This tool isn't perfect - sometimes we'll see small deltas in code coverage where there shouldn't be any - this is nothing to fret about.
If code coverage does decrease on a pull request, you will see a red X in the CI for the repo, but that's ok - the reviewer will use their judgement to determine whether or not we have sufficient code coverage for the change.
### Dependency Validation
To make sure the different components of the library are distributable as separate packages, we have to check
for dependency violations inside the code base. Dependencies must create a [DAC](https://en.wikipedia.org/wiki/Directed_acyclic_graph) in order to not create recursive dependencies.
For this purpose we use [Deptrac](https://github.com/qossmic/deptrac) and the respective configuration can be found
[here](./deptrac.yaml)
To validate the dependencies inside the code base, you can run:
```bash
make deptrac
```
This command will create an error for any violation of the defined dependencies. If you add new dependencies to the code base,
please configure them in the rector configuration.
## PhpMetrics
To generate a report showing a variety of metrics for the library and its classes, you can run:
```bash
make phpmetrics
```
This will generate a HTML PhpMetrics report in the `var/metrics` directory. Make sure to run `make test` before to
create the test log-file, used by the metrics report.
### Proto Generation
Our protobuf files are committed to the repository into the `/proto` folder. These are used in gRPC connections to the
upstream. These get updated when the [opentelemetry-proto](https://github.com/open-telemetry/opentelemetry-proto)
repo has a meaningful update. The maintainer SIG is discussing a way to make this more automatic in the future.
To generate protobuf files for use with this repository, you can run the following command:
```bash
make protobuf
```
This will replace `proto/otel/Opentelemetry` and `proto/otel/GPBMetadata` with freshly generated code based on the
latest tag from `opentelemetry-proto`, which can then be committed.
### Semantic Conventions Generation
Autogenerated semantic convention files are committed to the repository in the `/src/SemConv` directory. These files are
updated manually when a new version of [semantic-conventions](https://github.com/open-telemetry/semantic-conventions) is
released.
```bash
SEMCONV_VERSION=1.8.0 make semconv
```
Run this command in the root of this repository.
### API Documentation
We use [phpDocumentor](https://phpdoc.org/) to automatically generate API documentation from DocBlocks in the code.
To generate a recent version of the API documentation, you can run:
```bash
make phpdoc
```
To preview the documentation and changes you might expect, you can run:
```bash
make phpdoc-preview
```
This will start a HTTP server running at <http://localhost:8080> serving the updated documentation files.
## Maintainers
[@open-telemetry/php-maintainers](https://github.com/orgs/open-telemetry/teams/php-maintainers)
- [Bob Strecansky](https://github.com/bobstrecansky)
- [Timo Michna](https://github.com/tidal/)
- [Brett McBride](https://github.com/brettmc/)
Find more about the maintainer role in [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#maintainer)
- [Bob Strecansky](https://github.com/bobstrecansky), Intuit
- [Brett McBride](https://github.com/brettmc/), Deakin University
For more information about the maintainer role, see the [community repository](https://github.com/open-telemetry/community/blob/main/community-membership.md#maintainer).
## Approvers
[@open-telemetry/php-approvers](https://github.com/orgs/open-telemetry/teams/php-approvers)
- [Levi Morrison](https://github.com/morrisonlevi)
- [Beniamin Calota](https://github.com/beniamin)
- [Fahmy Mohammed](https://github.com/Fahmy-Mohammed)
- [Amber Zsistla](https://github.com/zsistla)
- [Ago Allikmaa](https://github.com/agoallikmaa)
- [Cedriz Ziel](https://github.com/cedricziel)
- [Chris Lightfoot-Wild](https://github.com/ChrisLightfootWild)
Find more information about the approver role in the [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#approver)
For more information about the approver role, see the [community repository](https://github.com/open-telemetry/community/blob/main/community-membership.md#approver).
## Triagers
[@open-telemetry/php-triagers](https://github.com/orgs/open-telemetry/teams/php-triagers)
For more information about the triager role, see the [community repository](https://github.com/open-telemetry/community/blob/main/community-membership.md#triagers).
## Emeritus maintainers/approvers/triagers
- [Amber Zsistla](https://github.com/zsistla)
- [Beniamin Calota](https://github.com/beniamin)
- [Fahmy Mohammed](https://github.com/Fahmy-Mohammed)
- [Jodee Varney](https://github.com/jodeev)
- [Levi Morrison](https://github.com/morrisonlevi)
- [Przemek Delewski](https://github.com/pdelewski)
- [Timo Michna](https://github.com/tidal/)
Find more information about the triager role in the [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#triager)
For more information about the emeritus role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#emeritus-maintainerapprovertriager).
## Members
- [Kishan Sangani](https://github.com/kishannsangani)
Find more information about the member role in the [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#member)
## Communication
## Further Help
Most of our communication is done on CNCF Slack in the channel [otel-php](https://cloud-native.slack.com/archives/C01NFPCV44V).
To sign up, create a CNCF Slack account [here](http://slack.cncf.io/)
@ -46,4 +316,4 @@ Our open issues can all be found in the [GitHub issues tab](https://github.com/o
<a href="https://github.com/open-telemetry/opentelemetry-php/graphs/contributors">
<img src="https://contributors-img.web.app/image?repo=open-telemetry/opentelemetry-php" />
</a>
</a>

View File

@ -1,226 +0,0 @@
## [Development](DEVELOPMENT.md)
For repeatability and consistency across different operating systems, we use the [3 Musketeers pattern](https://3musketeers.io/). If you're on Windows, it might be a good idea to use Git bash for following the steps below.
**Note: After cloning the repository, copy `.env.dist` to `.env`.**
Skipping the step above would result in a "`The "PHP_USER" variable is not set. Defaulting to a blank string`" warning
We use `docker` and `docker-compose` to perform a lot of our static analysis and testing. If you're planning to develop for this library, it'll help to install `docker engine` and `docker-compose`.
The installation instructions for these tools are [here](https://docs.docker.com/install/), under the `Docker Engine` and `Docker Compose` submenus respectively.
Development tasks are generally run through a `Makefile`. Running `make` or `make help` will list available targets.
To ensure you have all the correct packages installed locally in your dev environment, you can run
```bash
make install
```
This will install all the library dependencies to
the `/vendor` directory.
To update these dependencies, you can run
```bash
make update
```
## Coding Guidelines
Even though it may not be reflected everywhere in the codebase yet, we aim to provide software which is easy to read and change.
The methods described in Clean Code book(s) by Robert C. Martin (Uncle Bob) are a de facto industry standards nowadays.
Reading those books is highly recommended, however you can take a look at the examples given at [Clean Code PHP](https://github.com/jupeter/clean-code-php).
While we have no rule to strictly follow said methods and patterns, they are highly recommended as an orientation for
your pull requests and to be referenced in reviews.
We might add additional guidelines regarding for example testing in the future.
## Pull Requests
To propose changes to the codebase, you need
to [open a pull request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request)
to the opentelemetry-php project.
After you open the pull request, the CI will run all the
associated [github actions](https://github.com/open-telemetry/opentelemetry-php/actions/workflows/php.yml).
To ensure your PR doesn't emit a failure with GitHub actions, it's recommended that you run important the CI tests
locally with the following command:
```bash
make all
```
This does the following things:
* Installs/updates all the required dependencies for the project
* Uses [Rector](https://github.com/rectorphp/rector) to refactor your code according to our standards.
* Uses [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) to style your code using our style preferences.
* Uses [Deptrac](https://github.com/qossmic/deptrac) to check for dependency violations inside our code base
* Makes sure the composer files for the different components are valid
* Runs all of our [phpunit](https://phpunit.de/) unit tests.
* Performs static analysis with [Phan](https://github.com/phan/phan), [Psalm](https://psalm.dev/)
and [PHPStan](https://phpstan.org/user-guide/getting-started)
### Other PHP versions
We aim to support officially supported PHP versions, according to https://www.php.net/supported-versions.php. The
developer image `ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base` is tagged as `7.4`, `8.0` and `8.1`
respectively, with `7.4` being the default. You can execute the test suite against other PHP versions by running the
following command:
```bash
PHP_VERSION=8.0 make all
#or
PHP_VERSION=8.1 make all
```
## Proto Generation
Our protobuf files are committed to the repository into the `/proto` folder. These are used in gRPC connections to the
upstream. These get updated when the [opentelemetry-proto](https://github.com/open-telemetry/opentelemetry-proto)
repo has a meaningful update. The maintainer SIG is discussing a way to make this more automatic in the future.
To generate protobuf files for use with this repository, you can run the following command:
```bash
make protobuf
```
This will replace `proto/otel/Opentelemetry` and `proto/otel/GPBMetadata` with freshly generated code based on the
latest tag from `opentelemetry-proto`, which can then be committed.
## Semantic Conventions Generation
Autogenerated semantic convention files are committed to the repository in the `/src/SemConv` directory. These files get
updated when new version of [opentelemetry-specification](https://github.com/open-telemetry/opentelemetry-specification)
released.
```bash
SEMCONV_VERSION=1.8.0 make semconv
```
Run this command in the root of this repository.
## Automatic Refactoring and Upgrading
We use [Rector](https://github.com/rectorphp/rector) to automatically refactor our code according to given standards
and upgrade the code to supported PHP versions.
The associated configuration can be found [here](./.rector.php)
To refactor your code following our given standards, you can run:
```bash
make rector
```
This command applies the changes to the code base.
Make sure to run `make style` (see below) after running the `rector`command as the changes might not follow our coding standard.
If you want to simply check what changes would be applied by rector, you can run:
```bash
make rector-dry
```
This command will simply print out the changes `rector`would make without actually changing any code.
## Styling
We use [PHP-CS-Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) for our code linting and standards fixer. The
associated configuration can be found [here](./.php-cs-fixer.php)
To ensure that your code follows our coding standards, you can run:
```bash
make style
```
This command executes a required check that also runs during CI. This process performs the required fixes and prints them
out. Code that doesn't meet the style pattern will emit a failure with GitHub actions.
## Static Analysis
We use [Phan](https://github.com/phan/phan/) for static analysis. Currently, our phan configuration is just a standard
default analysis configuration. You can use our phan docker wrapper to easily perform static analysis on your changes.
To run Phan, one can run the following command:
```bash
make phan
```
This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs
during CI and is a required check. Code that doesn't match the standards that we have defined in
our [phan config](https://github.com/open-telemetry/opentelemetry-php/blob/master/.phan/config.php) will emit a failure
in CI.
We also use [Psalm](https://psalm.dev/) as a second static analysis tool.
You can use our psalm docker wrapper to easily perform static analysis on your changes.
To run Psalm, one can run the following command:
```bash
make psalm
```
This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs
during CI and is a required check. Code that doesn't match the standards that we have defined in
our [psalm config](https://github.com/open-telemetry/opentelemetry-php/blob/main/psalm.xml.dist) will emit a failure in
CI.
We use [PHPStan](https://github.com/phpstan/phpstan) as our third tool for static analysis. You can use our PHPStan
docker wrapper to easily perform static analysis on your changes.
To perform static analysis with PHPStan run:
```bash
make phpstan
```
This process will return 0 on success. Usually this process is performed as part of a code checkin. This process runs
during CI and is a required check. Code that doesn't match the standards that we have defined in
our [PHPStan config](https://github.com/open-telemetry/opentelemetry-php/blob/main/phpstan.neon.dist) will emit a
failure in CI.
## Testing
To make sure the tests in this repo work as you expect, you can use the included docker test wrapper.
To run the test suite, execute
```bash
make test
```
This will output the test output as well as a test coverage analysis (text + html - see `tests/coverage/html`). Code
that doesn't pass our currently defined tests will emit a failure in CI
## Code Coverage
We use [codecov.io](https://about.codecov.io/) to track code coverage for this repo. This is configured in the [php.yaml github action](https://github.com/open-telemetry/opentelemetry-php/blob/main/.github/workflows/php.yml#L71-L72). We don't require a specific level of code coverage for PRs to pass - we just use this tool in order to understand how a PR will potentially change the amount of code coverage we have across the code base. This tool isn't perfect - sometimes we'll see small deltas in code coverage where there shouldn't be any - this is nothing to fret about.
If code coverage does decrease on a pull request, you will see a red X in the CI for the repo, but that's ok - the reviewer will use their judgement to determine whether or not we have sufficient code coverage for the change.
## Dependency Validation
To make sure the different components of the library are distributable as separate packages, we have to check
for dependency violations inside the code base. Dependencies must create a [DAC](https://en.wikipedia.org/wiki/Directed_acyclic_graph) in order to not create recursive dependencies.
For this purpose we use [Deptrac](https://github.com/qossmic/deptrac) and the respective configuration can be found
[here](./deptrac.yaml)
To validatethe dependencies inside the code base, you can run:
```bash
make deptrac
```
This command will create an error for any violation of the defined dependencies. If you add new dependencies to the code base,
please configure them in the rector configuration.
## PhpMetrics
To generate a report showing a variety of metrics for the library and its classes, you can run:
```bash
make phpmetrics
```
This will generate a HTML PhpMetrics report in the `var/metrics` directory. Make sure to run `make test` before to
create the test log-file, used by the metrics report.

View File

@ -1,23 +1,35 @@
PHP_VERSION ?= 7.4
DC_RUN_PHP = docker-compose run --rm php
include .env
PHP_VERSION ?= 8.1
DOCKER_COMPOSE ?= docker compose
DC_RUN_PHP = $(DOCKER_COMPOSE) run --rm php
.DEFAULT_GOAL : help
.PHONY: deptrac
help: ## Show this help
@printf "\033[33m%s:\033[0m\n" 'Available commands'
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z0-9_-]+:.*?## / {printf " \033[32m%-18s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
all: update rector style deptrac packages-composer phan psalm phpstan test ## Run all tests, linting, checks
all: update all-checks ## Update to latest and run all checks
all-lowest: update-lowest all-checks ## Update to lowest dependencies and run all checks
all-checks: rector style deptrac packages-composer phan psalm phpstan test ## Run all checks
pull: ## Pull latest developer image
docker-compose pull php
$(DOCKER_COMPOSE) pull php
build: ## Build developer image locally
docker build docker/ --build-arg PHP_VERSION=${PHP_VERSION} -t ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION}
install: ## Install dependencies
$(DC_RUN_PHP) env XDEBUG_MODE=off composer install
update: ## Update dependencies
$(DC_RUN_PHP) env XDEBUG_MODE=off composer update
update-lowest: ## Update dependencies to lowest supported versions
$(DC_RUN_PHP) env XDEBUG_MODE=off composer update --prefer-lowest
test: test-unit test-integration ## Run unit and integration tests
test-unit: ## Run unit tests
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --testsuite unit --colors=always --coverage-text --testdox --coverage-clover coverage.clover --coverage-html=tests/coverage/html --log-junit=junit.xml
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --testsuite unit --colors=always
test-integration: ## Run integration tests
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/phpunit --testsuite integration --colors=always
test-verbose: ## Run unit tests with verbose (testdox) output
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --testsuite unit --colors=always --testdox --coverage-clover coverage.clover --coverage-html=tests/coverage/html --log-junit=junit.xml
test-coverage: ## Run units tests and generate code coverage
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --testsuite unit --coverage-html=tests/coverage/html
test-compliance: ## Run compliance tests
@ -25,28 +37,32 @@ test-compliance: ## Run compliance tests
test-trace-compliance: ## Run trace compliance tests
$(DC_RUN_PHP) env XDEBUG_MODE=coverage vendor/bin/phpunit --group trace-compliance
phan: ## Run phan
$(DC_RUN_PHP) env XDEBUG_MODE=off env PHAN_DISABLE_XDEBUG_WARN=1 vendor/bin/phan
$(DC_RUN_PHP) env XDEBUG_MODE=off env PHAN_DISABLE_XDEBUG_WARN=1 vendor-bin/phan/vendor/bin/phan
psalm: ## Run psalm
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/psalm --threads=1 --no-cache
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/psalm/vendor/bin/psalm --threads=1 --no-cache
psalm-info: ## Run psalm and show info
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/psalm --show-info=true --threads=1
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/psalm/vendor/bin/psalm --show-info=true --threads=1
phpdoc: ## Run phpdoc
$(DOCKER_COMPOSE) -f docker-compose.phpDocumentor.yaml run --rm phpdoc
phpdoc-preview:
$(DOCKER_COMPOSE) -f docker-compose.phpDocumentor.yaml run --service-ports --rm preview
phpstan: ## Run phpstan
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/phpstan analyse --memory-limit=256M
infection: ## Run infection (mutation testing)
$(DC_RUN_PHP) env XDEBUG_MODE=coverage php -d memory_limit=1024M vendor-bin/infection/vendor/bin/infection --threads=max
packages-composer: ## Validate composer packages
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/otel packages:composer:validate
benchmark: ## Run phpbench
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/phpbench run --report=default
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/phpbench/vendor/bin/phpbench run --report=default
phpmetrics: ## Run php metrics
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/phpmetrics --config=./phpmetrics.json --junit=junit.xml
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/phpmetrics/vendor/bin/phpmetrics --config=./phpmetrics.json --junit=junit.xml
smoke-test-examples: smoke-test-isolated-examples smoke-test-exporter-examples smoke-test-collector-integration smoke-test-prometheus-example ## Run smoke test examples
smoke-test-isolated-examples: ## Run smoke test isolated examples
$(DC_RUN_PHP) php ./examples/traces/getting_started.php
$(DC_RUN_PHP) php ./examples/traces/features/always_off_trace_example.php
$(DC_RUN_PHP) php ./examples/traces/features/batch_exporting.php
$(DC_RUN_PHP) php ./examples/traces/features/concurrent_spans.php
$(DC_RUN_PHP) php ./examples/traces/features/configuration_from_environment.php
$(DC_RUN_PHP) php ./examples/traces/features/creating_a_new_trace_in_the_same_process.php
$(DC_RUN_PHP) php ./examples/traces/features/parent_span_example.php
$(DC_RUN_PHP) php ./examples/traces/features/resource_detectors.php
$(DC_RUN_PHP) php ./examples/traces/features/span_resources.php
$(DC_RUN_PHP) php ./examples/traces/troubleshooting/air_gapped_trace_debugging.php
@ -54,52 +70,45 @@ smoke-test-isolated-examples: ## Run smoke test isolated examples
$(DC_RUN_PHP) php ./examples/traces/troubleshooting/setting_up_logging.php
smoke-test-exporter-examples: FORCE ## Run (some) exporter smoke test examples
# Note this does not include every exporter at the moment
docker-compose up -d --remove-orphans
$(DC_RUN_PHP) php ./examples/traces/features/exporters/zipkin.php
$(DC_RUN_PHP) php ./examples/traces/features/always_off_trace_example.php
$(DC_RUN_PHP) php ./examples/traces/features/exporters/jaeger.php
# The following examples do not use the DC_RUN_PHP global because they need environment variables.
docker-compose run -e NEW_RELIC_ENDPOINT -e NEW_RELIC_INSERT_KEY --rm php php ./examples/traces/features/exporters/newrelic.php
docker-compose run -e NEW_RELIC_ENDPOINT -e NEW_RELIC_INSERT_KEY --rm php php ./examples/traces/features/exporters/zipkin_to_newrelic.php
docker-compose stop
$(DOCKER_COMPOSE) up -d --remove-orphans
$(DC_RUN_PHP) php ./examples/traces/exporters/zipkin.php
$(DC_RUN_PHP) php ./examples/traces/features/parent_span_example.php
smoke-test-collector-integration: ## Run smoke test collector integration
docker-compose -f docker-compose.collector.yaml up -d --remove-orphans
# This is slow because it's building the image from scratch (and parts of that, like installing the gRPC extension, are slow)
# This can be sped up by switching to the pre-built images hosted on ghcr.io (and referenced in other docker-compose**.yaml files)
docker-compose -f docker-compose.collector.yaml run -e OTEL_EXPORTER_OTLP_ENDPOINT=collector:4317 --rm php php ./examples/traces/features/exporters/otlp_grpc.php
docker-compose -f docker-compose.collector.yaml stop
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml up -d --remove-orphans
sleep 5
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml run --rm php php ./examples/traces/exporters/otlp_grpc.php
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml run --rm php php ./examples/traces/exporters/otlp_http.php
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml stop
smoke-test-collector-metrics-integration:
docker-compose -f docker-compose.collector.yaml up -d --force-recreate collector
COMPOSE_IGNORE_ORPHANS=TRUE docker-compose -f docker-compose.yaml run --rm php php ./examples/metrics/features/exporters/otlp.php
docker-compose -f docker-compose.collector.yaml logs collector
docker-compose -f docker-compose.collector.yaml stop collector
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml up -d --force-recreate collector
COMPOSE_IGNORE_ORPHANS=TRUE $(DOCKER_COMPOSE) -f docker-compose.yaml run --rm php php ./examples/metrics/features/exporters/otlp_http.php
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml logs collector
$(DOCKER_COMPOSE) -f docker-compose.collector.yaml stop collector
smoke-test-prometheus-example: metrics-prometheus-example stop-prometheus
metrics-prometheus-example:
@docker-compose -f docker-compose.prometheus.yaml -p opentelemetry-php_metrics-prometheus-example up -d web
@$(DOCKER_COMPOSE) -f docker-compose.prometheus.yaml -p opentelemetry-php_metrics-prometheus-example up -d web
# This is slow because it's building the image from scratch (and parts of that, like installing the gRPC extension, are slow)
@docker-compose -f docker-compose.prometheus.yaml -p opentelemetry-php_metrics-prometheus-example run --rm php php examples/metrics/prometheus/prometheus_metrics_example.php
@$(DOCKER_COMPOSE) -f docker-compose.prometheus.yaml -p opentelemetry-php_metrics-prometheus-example run --rm php php examples/metrics/prometheus/prometheus_metrics_example.php
stop-prometheus:
@docker-compose -f docker-compose.prometheus.yaml -p opentelemetry-php_metrics-prometheus-example stop
@$(DOCKER_COMPOSE) -f docker-compose.prometheus.yaml -p opentelemetry-php_metrics-prometheus-example stop
fiber-ffi-example:
@docker-compose -f docker-compose.fiber-ffi.yaml -p opentelemetry-php_fiber-ffi-example up -d web
@$(DOCKER_COMPOSE) -f docker-compose.fiber-ffi.yaml -p opentelemetry-php_fiber-ffi-example up -d web
protobuf: ## Generate protobuf files
./script/proto_gen.sh
thrift: ## Generate thrift files
./script/thrift_gen.sh
bash: ## bash shell into container
$(DC_RUN_PHP) bash
style: ## Run style check/fix
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --using-cache=no -vvv
rector: ## Run rector
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/rector process src
rector-dry: ## Run rector (dry-run)
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/rector process src --dry-run
$(DC_RUN_PHP) env XDEBUG_MODE=off env PHP_CS_FIXER_IGNORE_ENV=1 vendor-bin/php-cs-fixer/vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --using-cache=no -vvv
rector-write: ## Run rector
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/rector/vendor/bin/rector process
rector: ## Run rector (dry-run)
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/rector/vendor/bin/rector process --dry-run
deptrac: ## Run deptrac
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor/bin/deptrac --formatter=table --report-uncovered --no-cache
$(DC_RUN_PHP) env XDEBUG_MODE=off vendor-bin/deptrac/vendor/bin/deptrac --formatter=table --report-uncovered --no-cache
w3c-test-service:
@docker-compose -f docker-compose.w3cTraceContext.yaml run --rm php ./tests/TraceContext/W3CTestService/trace-context-test.sh
@$(DOCKER_COMPOSE) -f docker-compose.w3cTraceContext.yaml run --rm php ./tests/TraceContext/W3CTestService/trace-context-test.sh
semconv: ## Generate semconv files
./script/semantic-conventions/semconv.sh
split: ## Run git split
docker-compose -f docker/gitsplit/docker-compose.yaml --env-file ./.env up
$(DOCKER_COMPOSE) -f docker/gitsplit/docker-compose.yaml --env-file ./.env up
FORCE:

360
README.md
View File

@ -1,354 +1,56 @@
# OpenTelemetry php library
# OpenTelemetry for PHP
![CI Build](https://github.com/open-telemetry/opentelemetry-php/workflows/PHP%20QA/badge.svg)
[![codecov](https://codecov.io/gh/open-telemetry/opentelemetry-php/branch/master/graph/badge.svg)](https://codecov.io/gh/open-telemetry/opentelemetry-php)
[![Slack](https://img.shields.io/badge/slack-@cncf/otel--php-brightgreen.svg?logo=slack)](https://cloud-native.slack.com/archives/D03FAB6GN0K)
<details>
<summary>Table of Contents</summary>
This is the **[monorepo](https://en.wikipedia.org/wiki/Monorepo)** for the **main** components of [OpenTelemetry](https://opentelemetry.io/) for PHP.
<!-- toc -->
## Documentation
- [Introduction](#introduction)
- [Project status](#project-status)
- [Specification conformance](#specification-conformance)
- [Backwards compatibility](#backwards-compatibility)
- [Requirements](#requirements)
- [Required dependencies](#required-dependencies)
- [Optional dependencies](#optional-dependencies)
- [Installation](#installation)
- [Getting started](#getting-started)
- [Instrumenting an application](#using-opentelemetry-in-an-application)
- [Instrumenting a library](#using-opentelemetry-to-instrument-a-library)
- [Trace signals](#trace-signals)
- [Auto-instrumentation](#auto-instrumentation)
- [Framework instrumentation](#framework-instrumentation)
- [Manual instrumentation](#manual-instrumentation)
- [Set up a tracer](#set-up-a-tracer)
- [Creating spans](#creating-spans)
- [Nesting spans](#nesting-spans)
- [Distributed tracing](#distributed-tracing)
- [Examples](#metrics-examples)
- [Metrics signals](#metrics-signals)
- [Examples](#trace-examples)
- [Log signals](#log-signals)
- [User Quickstarts](#user-quickstarts)
- [Versioning](#versioning)
- [Contributing](#contributing)
<!-- tocstop -->
Please read the official documentation: https://opentelemetry.io/docs/instrumentation/php/
</details>
API Documentation is available here: https://open-telemetry.github.io/opentelemetry-php/
# Introduction
## Packages and versions
This is the **[monorepo](https://en.wikipedia.org/wiki/Monorepo)** for the **main** components of **[OpenTelemetry](https://opentelemetry.io/) PHP**.
| Package | Latest |
|----------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| API | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/api/v/stable)](https://packagist.org/packages/open-telemetry/api/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/api/v/unstable)](https://packagist.org/packages/open-telemetry/api/) |
| SDK | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/sdk/v/stable)](https://packagist.org/packages/open-telemetry/sdk/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/sdk/v/unstable)](https://packagist.org/packages/open-telemetry/sdk/) |
| Context | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/context/v/stable)](https://packagist.org/packages/open-telemetry/context/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/context/v/unstable)](https://packagist.org/packages/open-telemetry/context/) |
| Semantic Conventions | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/sem-conv/v/stable)](https://packagist.org/packages/open-telemetry/sem-conv/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/sem-conv/v/unstable)](https://packagist.org/packages/open-telemetry/sem-conv/) |
| OTLP Exporter | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/exporter-otlp/v/stable)](https://packagist.org/packages/open-telemetry/exporter-otlp/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/exporter-otlp/v/unstable)](https://packagist.org/packages/open-telemetry/exporter-otlp/) |
| gRPC Transport | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/transport-grpc/v/stable)](https://packagist.org/packages/open-telemetry/transport-grpc/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/transport-grpc/v/unstable)](https://packagist.org/packages/open-telemetry/transport-grpc/) |
| OTLP Protobuf Files | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/gen-otlp-protobuf/v/stable)](https://packagist.org/packages/open-telemetry/gen-otlp-protobuf/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/gen-otlp-protobuf/v/unstable)](https://packagist.org/packages/open-telemetry/gen-otlp-protobuf/) |
| B3 Propagator | [![Latest Stable Version](https://poser.pugx.org/open-telemetry/extension-propagator-b3/v/stable)](https://packagist.org/packages/open-telemetry/extension-propagator-b3/) [![Latest Unstable Version](https://poser.pugx.org/open-telemetry/extension-propagator-b3/v/unstable)](https://packagist.org/packages/open-telemetry/extension-propagator-b3/) |
All OpenTelemetry libraries are distributed via packagist, notably:
Releases for both this repository and [contrib](https://github.com/open-telemetry/opentelemetry-php-contrib) are
based on read-only [git subtree splits](https://github.com/splitsh/lite) from our monorepo. You should refer to
[packagist.org](https://packagist.org/packages/open-telemetry/) for all packages, their versions and details.
- API: [open-telemetry/api](https://packagist.org/packages/open-telemetry/api)
- SDK: [open-telemetry/sdk](https://packagist.org/packages/open-telemetry/sdk)
- Semantic Conventions: [open-telemetry/sem-conv](https://packagist.org/packages/open-telemetry/sem-conv)
- Context: [open-telemetry/context](https://packagist.org/packages/open-telemetry/context)
- Contrib: [open-telemetry/sdk-contrib](https://packagist.org/packages/open-telemetry/sdk-contrib)
You can also look at the read-only repositories, which live in the
[opentelemetry-php](https://github.com/opentelemetry-php) organization.
The [open-telemetry/opentelemetry](https://packagist.org/packages/open-telemetry/opentelemetry) package contains all of the above and is the easiest way to try out OpenTelemetry.
## Contributing
---
This repository also hosts and distributes generated client code used by individual components as separate packages. These packages are:
- Generated [OTLP](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md) ProtoBuf files:
[open-telemetry/gen-otlp-protobuf](https://packagist.org/packages/open-telemetry/gen-otlp-protobuf)
- Generated [Jaeger](https://github.com/jaegertracing/jaeger-idl) Thrift files:
[open-telemetry/gen-jaeger-thrift](https://packagist.org/packages/open-telemetry/gen-jaeger-thrift)
[![GitHub repo Good Issues for newbies](https://img.shields.io/github/issues/open-telemetry/opentelemetry-php/good%20first%20issue?style=flat&logo=github&logoColor=green&label=Good%20First%20issues)](https://github.com/open-telemetry/opentelemetry-php/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) [![GitHub Help Wanted issues](https://img.shields.io/github/issues/open-telemetry/opentelemetry-php/help%20wanted?style=flat&logo=github&logoColor=b545d1&label=%22Help%20Wanted%22%20issues)](https://github.com/open-telemetry/opentelemetry-php/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) [![GitHub Help Wanted PRs](https://img.shields.io/github/issues-pr/open-telemetry/opentelemetry-php/help%20wanted?style=flat&logo=github&logoColor=b545d1&label=%22Help%20Wanted%22%20PRs)](https://github.com/open-telemetry/opentelemetry-php/pulls?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) [![GitHub repo Issues](https://img.shields.io/github/issues/open-telemetry/opentelemetry-php?style=flat&logo=github&logoColor=red&label=Issues)](https://github.com/open-telemetry/opentelemetry-php/issues?q=is%3Aopen)
For now the generated code packages are meant to be only used by library components internally.
---
The [OpenTelemetry PHP Contrib repository](https://github.com/open-telemetry/opentelemetry-php-contrib/) hosts contributions that are not part of the core
distribution or components of the library. Typically, these contributions are vendor specific receivers/exporters and/or
components that are only useful to a relatively small number of users.
Additional packages, demos and tools are hosted or distributed in the [OpenTelemetry PHP organization](https://github.com/opentelemetry-php).
# Project Status
![Current Version](https://img.shields.io/github/v/tag/open-telemetry/opentelemetry-php)
This project currently lives in a **alpha status**. Our current release is not production ready; it has been created in order to receive feedback from the community. \
As long as this project is in alpha status, things may and probably will break once in a while.
We would love to have you on board, please see our [Contributing README](./CONTRIBUTING.md)
## Specification conformance
We attempt to keep the [OpenTelemetry Specification Matrix](https://github.com/open-telemetry/opentelemetry-specification/blob/master/spec-compliance-matrix.md) up to date in order to show which features are available and which have not yet been implemented.
If you find an inconsistency in the data in the matrix vs. the data in this repository, please let us know in our slack channel and we'll get it rectified.
If you find an inconsistency in the data in the matrix, please let us know in our slack channel and we'll get it rectified.
---
## Backwards compatibility
## Backwards Compatibility
We aim to provide backward compatibility (without any guarantee) even for alpha releases, however the library will raise notices indicating breaking changes and what to do about them. \
If you don't want these notices to appear or change the error message level, you can do so by calling:
```php
OpenTelemetry\SDK\Common\Dev\Compatibility\Util::setErrorLevel(0)
```
to turn messages off completely, or (for example)
```php
OpenTelemetry\SDK\Common\Dev\Compatibility\Util::setErrorLevel(E_USER_DEPRECATED)
```
to trigger only deprecation notices. Valid error levels are `0` (none), `E_USER_DEPRECATED`, `E_USER_NOTICE`, `E_USER_WARNING` and `E_USER_ERROR` \
However (as long as in alpha) it is safer to pin a dependency on the library to a specific version and/or make the adjustments
mentioned in the provided messages, since doing otherwise may break things completely for you in the future!
See [compatibility readme](src/SDK/Common/Dev/Compatibility/README.md).
# Requirements
## Versioning
The library and all separate packages requires a PHP version of 7.4.x, 8.0.x or 8.1.x
## Required dependencies
### 1) Install PSR17/18 implementations
The **SDK** and **Contrib** packages have a dependency on both a [HTTP Factories (PSR17)](https://www.php-fig.org/psr/psr-17/)
and a [php-http/async-client](https://docs.php-http.org/en/latest/clients.html) implementation.
You can find appropriate composer packages implementing given standards on [packagist.org](https://packagist.org/).
Follow [this link](https://packagist.org/providers/psr/http-factory-implementation) to find a `PSR17 (HTTP factories)` implementation,
and [this link](https://packagist.org/providers/php-http/async-client-implementation) to find a `php-http/async-client` implementation.
---
## Optional dependencies
### 1) Install PHP [ext-grpc](https://pecl.php.net/package/gRPC)
**The PHP gRPC extension is only needed, if you want to use the OTLP GRPC Exporter from the Contrib package.**
Three ways to install the gRPC extension are described below. Keep in mind, that whatever way
to install the extension you choose, the compilation can take up to 10-15 minutes. (As an alternative you can search for
a pre-compiled extension binary for your OS and PHP version, or you might be lucky and the package manager of your OS
provides a package for the extension)
- **Installation with pecl installer** (which should come with your PHP installation):
```bash
[sudo] pecl install grpc
```
- **Installation with pickle installer** (which you can find [here](https://github.com/FriendsOfPHP/pickle)):
```bash
[sudo] pickle install grpc
```
- **Manually compiling the extension**, which is not really complicated either, but you should know
what you are doing, so we won't cover it here.
> Notice: The artifact of the gRPC extension can be as large as 100mb (!!!), Some 'hacks' to reduce that size,
>are mentioned [in this thread](https://github.com/grpc/grpc/issues/23626). **Use at your own risk.**
### 2) Install PHP [ext-mbstring](https://www.php.net/manual/en/book.mbstring.php)
The library's components will load the `symfony/polyfill-mbstring` package, but for better performance you should install
the PHP mbstring extension. You can use the same install methods as described for the gRPC extension above,
however most OS` package managers provide a package for the extension.
### 3) Install PHP [ext-zlib](https://www.php.net/manual/en/book.zlib.php)
In order to use compression in HTTP requests you should install
the PHP zlib extension. You can use the same install methods as described for the gRPC extension above,
however most OS` package managers provide a package for the extension.
### 4) Install PHP [ext-ffi](https://www.php.net/manual/en/book.ffi.php)
_Experimental_ support for using fibers in PHP 8.1 for Context storage requires the `ffi` extension, and can
be enabled by setting the `OTEL_PHP_FIBERS_ENABLED` environment variable to a truthy value (`1`, `true`, `on`).
Using fibers with non-`CLI` SAPIs may require preloading of bindings. One way to achieve this is setting [`ffi.preload`](https://www.php.net/manual/en/ffi.configuration.php#ini.ffi.preload) to `src/Context/fiber/zend_observer_fiber.h` and setting [`opcache.preload`](https://www.php.net/manual/en/opcache.preloading.php) to `vendor/autoload.php`.
### 5) Install PHP [ext-protobuf](https://pecl.php.net/package/protobuf)
**The PHP protobuf extension is optional when using either the `OTLPHttp` or `OTLPGrpc` exporters from the Contrib package.**
The protobuf extension makes both exporters more performant. _Note that protobuf 3.20.0+ is required for php 8.1 support_
---
# Installation
The recommended way to install the library's packages is through [Composer](http://getcomposer.org):
Install Composer using the [installation instructions](https://getcomposer.org/doc/00-intromd#installation-linux-unix-macos) and add
```bash
"minimum-stability": "dev"
```
To your project's `composer.json` file, as this library has not reached a stable release status yet.
To install the complete library with all packages you can run:
```bash
$ composer require open-telemetry/opentelemetry
```
This is perfect for trying out our examples or demos.
# Getting Started
You can find a getting started guide on [opentelemetry.io](https://opentelemetry.io/docs/php/getting-started/)
OpenTelemetry's goal is to provide a single set of APIs to capture _signals_, such as distributed traces and metrics, from your application and send them to an observability platform. This project allows you to do just that for applications written in PHP. There are two steps to this process: instrument your application, and configure an exporter.
To start capturing signals from your application it first needs to be instrumented.
## Using OpenTelemetry in an Application
Your application should only depend on Interfaces provided by the API package:
```bash
$ composer require open-telemetry/api
```
In the best case you will use [Dependency Inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle) and write an adapter to not depend on the API directly.
Make sure your application works with a dependency on the API only, however to make full use of the library you want to install the **SDK** package and probably the **Contrib** package as well:
```bash
$ composer require open-telemetry/sdk
```
or
```bash
$ composer require open-telemetry/sdk open-telemetry/sdk-contrib
```
Make sure any **SDK** or **Contrib** code is set up by your configuration, bootstrap, dependency injection, etc.
## Using OpenTelemetry to instrument a Library
Your library should only depend on Interfaces provided by the API package:
```bash
$ composer require open-telemetry/api
```
For development and testing purposes you also want to install **SDK** and **Contrib** packages:
```bash
$ composer require --dev open-telemetry/sdk open-telemetry/sdk-contrib
```
## Trace signals
### Auto-instrumentation
_We do not currently support auto-instrumentation, but are internally discussing how to implement it_
### Framework instrumentation
* [Symfony SDK Bundle](https://github.com/open-telemetry/opentelemetry-php-contrib/tree/main/src/Symfony/OtelSdkBundle) is the recommended way to use opentelemetry-php with symfony
### Manual instrumentation
If you wish to build your own instrumentation for your application, you will need to use the API, the SDK, and probably the contrib module (which contains most of the exporters).
#### Set up a tracer
Tracers must be obtained from a `TracerProvider`:
```php
$tracerProvider = new \OpenTelemetry\SDK\Trace\TracerProvider(
new \OpenTelemetry\SDK\Trace\SpanProcessor\BatchSpanProcessor(
new \OpenTelemetry\Contrib\OtlpGrpc\Exporter('otel-collector:4317')
)
);
\OpenTelemetry\SDK\Common\Util\ShutdownHandler::register([$tracerProvider, 'shutdown']);
$tracer = $tracerProvider->getTracer('example');
```
It's important to run the tracer provider's `shutdown()` method when the PHP process ends, to enable flushing of any enqueued telemetry.
The shutdown process is blocking, so consider running it in an async process. Otherwise, you can use the `ShutdownHandler` to register the shutdown function as part of PHP's shutdown process, as demonstrated above.
#### Creating spans
```php
$span = $tracer->spanBuilder('root')->startSpan();
//do some work
$span->end();
```
#### Nesting spans
You can _activate_ a span, so that it will be the parent of future spans.
When you activate a span, it's critical that you also _detach_ it when done. We recommend doing this in a `finally` block:
```php
$root = $tracer->spanBuilder('root')->startSpan();
$scope = $root->activate();
try {
$child = $tracer->spanBuilder('child')->startSpan();
$child->end();
} finally {
$root->end();
$scope->detach();
}
```
When an active span is deactivated (scope detached), the previously active span will become the active span again.
#### Distributed tracing
OpenTelemetry supports distributed tracing via [Context Propagation](https://opentelemetry.io/docs/concepts/signals/traces/#context-propagation), where traces can be correlated across multiple services. To enable this, outgoing HTTP requests must be injected with standardized headers which are understood by other OTEL-enabled services.
```php
$request = new Request('GET', 'https://www.example.com');
$carrier = [];
TraceContextPropagator::getInstance()->inject($carrier);
foreach ($carrier as $name => $value) {
$request = $request->withAddedHeader($name, $value);
}
$response = $client->send($request);
```
See [examples/traces/demo](examples/traces/demo) for a working example.
### Trace examples
You can use the [zipkin](/examples/traces/exporters/zipkin.php) or [jaeger](/examples/traces/exporters/jaeger.php) example to test out the reference
implementations. This example performs a sample trace with a grouping of 5 spans and exports the result
to a local zipkin or jaeger instance.
If you'd like a no-fuss way to test this out with docker and docker-compose, you can perform the following simple steps:
1) Install the necessary dependencies by running `make install`.
2) Execute the example trace using `make smoke-test-exporter-examples:`.
Exported spans can be seen in zipkin at [http://127.0.0.1:9411](http://127.0.0.1:9411)
Exported spans can also be seen in jaeger at [http://127.0.0.1:16686](http://127.0.0.1:16686)
## Metrics signals
_coming soon_
### Metrics examples
<details>
<summary>This section is deprecated, we have a new metrics implementation in development</summary>
You can use the [examples/prometheus/PrometheusMetricsExample.php](/examples/prometheus/PrometheusMetricsExample.php)
file to test out the reference implementation we have. This example will create a counter that will be scraped by local
Prometheus instance.
The easy way to test the example out with docker and docker-compose is:
1) Run `make metrics-prometheus-example`. Make sure that local ports 8080, 6379 and 9090 are available.
2) Open local Prometheus instance: http://localhost:9090
3) Go to Graph section, type "opentelemetry_prometheus_counter" in the search field or select it in the dropdown menu.
You will see the counter value. Every other time you run `make metrics-prometheus-example` will increment the counter
but remember that Prometheus scrapes values once in 10 seconds.
4) In order to stop docker containers for this example just run `make stop-prometheus`
</details>
## Log signals
_frozen pending delivery of tracing and metrics_
# User Quickstarts
* [Exploring OpenTelemetry in Laravel Applications](./docs/laravel-quickstart.md)
# Versioning
OpenTelemetry for PHP aims to support all officially supported PHP versions according to https://www.php.net/supported-versions.php, and
support will be dropped for PHP versions within 12 months of that version going _End of life_.
Versioning rationale can be found in the [Versioning Documentation](/docs/versioning.md)
# Contributing
We would love to have you on board, please see our [Development README](./DEVELOPMENT.md) and [Contributing README](./CONTRIBUTING.md).

View File

@ -7,103 +7,202 @@
"readme": "./README.md",
"license": "Apache-2.0",
"require": {
"php": "^7.4 || ^8.0",
"cloudevents/sdk-php": "^v1.0.1",
"ext-json": "*",
"google/protobuf": "^3.3.0",
"grpc/grpc": "^1.30",
"packaged/thrift": "^0.15.0",
"php-http/async-client-implementation": "^1.0",
"php": "^8.1",
"google/protobuf": "^3.22 || ^4.0",
"nyholm/psr7-server": "^1.1",
"php-http/discovery": "^1.14",
"promphp/prometheus_client_php": "^2.2.1",
"psr/http-client": "^1.0",
"psr/http-client-implementation": "^1.0",
"psr/http-factory-implementation": "^1.0",
"psr/http-message": "^1.0.1|^2.0",
"psr/log": "^1.1|^2.0|^3.0",
"ramsey/uuid": "^3.0 || ^4.0",
"symfony/config": "^5.4 || ^6.4 || ^7.0",
"symfony/polyfill-mbstring": "^1.23",
"symfony/polyfill-php80": "^1.26",
"symfony/polyfill-php81": "^1.26",
"symfony/polyfill-php82": "^1.26"
"symfony/polyfill-php82": "^1.26",
"symfony/polyfill-php83": "^1.32",
"symfony/polyfill-php84": "^1.32",
"tbachert/spi": "^1.0.1"
},
"config": {
"sort-packages": true,
"allow-plugins": {
"bamarni/composer-bin-plugin": true,
"composer/package-versions-deprecated": true,
"symfony/runtime": true
"php-http/discovery": true,
"symfony/runtime": true,
"tbachert/spi": true
}
},
"authors": [
{
"name": "Bob Strecansky",
"email": "bob.strecansky@gmail.com"
},
{
"name": "Dmitry Krokhin",
"email": "nekufa@gmail.com"
},
{
"name": "Levi Morrison",
"email": "levim@php.net"
"name": "opentelemetry-php contributors",
"homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors"
}
],
"replace": {
"open-telemetry/api": "self.version",
"open-telemetry/context": "self.version",
"open-telemetry/gen-jaeger-thrift": "self.version",
"open-telemetry/gen-otlp-protobuf": "self.version",
"open-telemetry/sdk": "self.version",
"open-telemetry/sdk-contrib": "self.version",
"open-telemetry/sem-conv": "self.version"
"open-telemetry/api": "1.0.x-dev",
"open-telemetry/context": "1.0.x-dev",
"open-telemetry/exporter-otlp": "1.0.x-dev",
"open-telemetry/exporter-zipkin": "1.0.x-dev",
"open-telemetry/extension-propagator-b3": "1.0.x-dev",
"open-telemetry/extension-propagator-cloudtrace": "1.0.x-dev",
"open-telemetry/extension-propagator-jaeger": "0.0.2",
"open-telemetry/gen-otlp-protobuf": "1.0.x-dev",
"open-telemetry/sdk": "1.0.x-dev",
"open-telemetry/sdk-configuration": "0.1.x-dev",
"open-telemetry/sdk-contrib": "1.0.x-dev",
"open-telemetry/sem-conv": "1.0.x-dev",
"open-telemetry/transport-grpc": "1.0.x-dev"
},
"autoload": {
"psr-4": {
"OpenTelemetry\\": "src/",
"Opentelemetry\\Proto\\": "proto/otel/Opentelemetry/Proto/",
"GPBMetadata\\Opentelemetry\\": "proto/otel/GPBMetadata/Opentelemetry/",
"Jaeger\\Thrift\\": "thrift/jaeger/"
"GPBMetadata\\Opentelemetry\\": "proto/otel/GPBMetadata/Opentelemetry/"
},
"files": [
"src/Context/fiber/initialize_fiber_handler.php",
"src/API/Trace/functions.php",
"src/Contrib/Otlp/_register.php",
"src/Contrib/Grpc/_register.php",
"src/Contrib/Zipkin/_register.php",
"src/Extension/Propagator/B3/_register.php",
"src/Extension/Propagator/CloudTrace/_register.php",
"src/Extension/Propagator/Jaeger/_register.php",
"src/SDK/Logs/Exporter/_register.php",
"src/SDK/Metrics/MetricExporter/_register.php",
"src/SDK/Propagation/_register.php",
"src/SDK/Trace/SpanExporter/_register.php",
"src/SDK/Common/Dev/Compatibility/_load.php",
"src/SDK/Common/Util/functions.php"
"src/SDK/Common/Util/functions.php",
"src/SDK/_autoload.php"
]
},
"autoload-dev": {
"psr-4": {
"OpenTelemetry\\Tests\\": "tests/"
"OpenTelemetry\\Tests\\": "tests/",
"OpenTelemetry\\Example\\": "examples/src/",
"ExampleSDK\\ComponentProvider\\": "tests/Unit/Config/SDK/Configuration/ExampleSdk/"
}
},
"require-dev": {
"ext-grpc": "*",
"assertwell/phpunit-global-state": "^0.2.1",
"composer/xdebug-handler": "^2.0",
"dg/bypass-finals": "^1.3",
"friendsofphp/php-cs-fixer": "^3.4",
"bamarni/composer-bin-plugin": "^1.8",
"dg/bypass-finals": "^1.4",
"grpc/grpc": "^1.30",
"guzzlehttp/guzzle": "^7.4",
"guzzlehttp/psr7": "^2.1",
"mikey179/vfsstream": "^1.6",
"mockery/mockery": "^1.4",
"monolog/monolog": "^2.3",
"mikey179/vfsstream": "^1.6.11",
"mockery/mockery": "^1.5.1",
"monolog/monolog": "^3.0",
"nyholm/psr7": "^1.4",
"open-telemetry/dev-tools": "dev-main",
"phan/phan": "^5.0",
"php-http/mock-client": "^1.5",
"phpbench/phpbench": "^1.2",
"phpmetrics/phpmetrics": "^2.7",
"phpspec/prophecy-phpunit": "^2.0",
"phpstan/phpstan": "^1.1",
"phpstan/phpstan-mockery": "^1.0",
"phpstan/phpstan-phpunit": "^1.0",
"phpunit/phpunit": "^9.3",
"psalm/plugin-mockery": "^0.9",
"psalm/plugin-phpunit": "^0.16",
"psalm/psalm": "^4.0",
"qossmic/deptrac-shim": "^0.22.1",
"rector/rector": "^0.13.7",
"symfony/http-client": "^5.2"
"phpdocumentor/reflection-docblock": "^5.3",
"phpspec/prophecy": "^1.22",
"phpspec/prophecy-phpunit": "^2",
"phpstan/phpstan": "^1.10.13",
"phpstan/phpstan-mockery": "^1.1",
"phpstan/phpstan-phpunit": "^1.3",
"phpunit/phpunit": "^10 || ^11",
"sebastian/exporter": "<= 6.0.1 || >= 6.1.3",
"symfony/http-client": "^5.2",
"symfony/var-exporter": "^5.4 || ^6.4 || ^7.0",
"symfony/yaml": "^5.4 || ^6.4 || ^7.0"
},
"conflict": {
"mockery/mockery": "1.6.12"
},
"suggest": {
"ext-gmp": "To support unlimited number of synchronous metric readers",
"ext-grpc": "To use the OTLP GRPC Exporter",
"ext-protobuf": "For more performant protobuf/grpc exporting",
"ext-sockets": "To use the Thrift UDP Exporter for the Jaeger Agent"
"ext-yaml": "Allows loading config from yaml files",
"symfony/yaml": "Allows loading config from yaml files"
},
"extra": {
"bamarni-bin": {
"bin-links": false,
"target-directory": "vendor-bin",
"forward-command": true
},
"spi": {
"OpenTelemetry\\API\\Configuration\\Config\\ComponentProvider": [
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorB3",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorB3Multi",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorBaggage",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorComposite",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorJaeger",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Propagator\\TextMapPropagatorTraceContext",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SamplerAlwaysOff",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SamplerAlwaysOn",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SamplerParentBased",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SamplerTraceIdRatioBased",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterConsole",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterMemory",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterOtlpFile",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterOtlpGrpc",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterOtlpHttp",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanExporterZipkin",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanProcessorBatch",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Trace\\SpanProcessorSimple",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\AggregationResolverDefault",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterConsole",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterMemory",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterOtlpFile",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterOtlpGrpc",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricExporterOtlpHttp",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Metrics\\MetricReaderPeriodic",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterConsole",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterMemory",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterOtlpFile",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterOtlpGrpc",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordExporterOtlpHttp",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordProcessorBatch",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Logs\\LogRecordProcessorSimple",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Detector\\Composer",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Detector\\Host",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Detector\\Process",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Instrumentation\\General\\HttpConfigProvider",
"OpenTelemetry\\Config\\SDK\\ComponentProvider\\Instrumentation\\General\\PeerConfigProvider",
"OpenTelemetry\\Example\\ExampleConfigProvider",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Detector\\Container",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Detector\\Os",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Metrics\\AggregationResolverExplicitBucketHistogram",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Metrics\\MetricExporterPrometheus",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Metrics\\MetricReaderPull",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Propagator\\TextMapPropagatorXray",
"OpenTelemetry\\Tests\\Integration\\Config\\ComponentProvider\\Propagator\\TextMapPropagatorOtTrace"
],
"OpenTelemetry\\API\\Configuration\\ConfigEnv\\EnvComponentLoader": [
"OpenTelemetry\\API\\Instrumentation\\Configuration\\General\\ConfigEnv\\EnvComponentLoaderHttpConfig",
"OpenTelemetry\\API\\Instrumentation\\Configuration\\General\\ConfigEnv\\EnvComponentLoaderPeerConfig",
"OpenTelemetry\\Example\\ExampleConfigLoader"
],
"OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [
"OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager"
],
"OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\Instrumentation": [
"OpenTelemetry\\Example\\ExampleInstrumentation"
],
"OpenTelemetry\\SDK\\Common\\Configuration\\Resolver\\ResolverInterface": [
"OpenTelemetry\\SDK\\Common\\Configuration\\Resolver\\SdkConfigurationResolver"
],
"OpenTelemetry\\Config\\SDK\\Configuration\\Environment\\EnvSourceProvider": [
"OpenTelemetry\\Config\\SDK\\Configuration\\Environment\\Adapter\\SymfonyDotenvProvider",
"OpenTelemetry\\Config\\SDK\\Configuration\\Environment\\Adapter\\VlucasPhpdotenvProvider",
"OpenTelemetry\\Tests\\Integration\\SDK\\Common\\Configuration\\TestEnvSourceProvider"
]
}
}
}

View File

@ -1,4 +1,14 @@
deptrac:
skip_violations:
OpenTelemetry\SDK\Trace\Span:
- OpenTelemetry\API\Trace\NonRecordingSpan
/src/Extension/Propagator/B3/_register.php:
- OpenTelemetry\SDK\Registry
/src/Extension/Propagator/CloudTrace/_register.php:
- OpenTelemetry\SDK\Registry
/src/Extension/Propagator/Jaeger/_register.php:
- OpenTelemetry\SDK\Registry
OpenTelemetry\API\Configuration\Config\ComponentProvider:
- Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
- Symfony\Component\Config\Definition\Builder\NodeBuilder
OpenTelemetry\API\Configuration\Config\ComponentProviderRegistry:
- Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition
- Symfony\Component\Config\Definition\Builder\NodeDefinition

View File

@ -13,37 +13,44 @@ deptrac:
paths:
- ./src
- ./proto
- ./thrift
- ./tests
- ./deptrac/polyfills
- ./vendor/symfony/polyfill-php83/Resources/stubs
exclude_files:
- '#.*test.*#'
layers:
- name: API
collectors:
- type: className
regex: ^OpenTelemetry\\API\\*
- type: directory
value: src/API/.*
- name: SDK
collectors:
- type: className
regex: ^OpenTelemetry\\SDK\\*
- type: directory
value: src/SDK/.*
- name: ConfigSDK
collectors:
- type: directory
value: src/Config/SDK/.*
- name: Context
collectors:
- type: className
regex: ^OpenTelemetry\\Context\\*
- type: directory
value: src/Context/.*
- name: SemConv
collectors:
- type: className
regex: ^OpenTelemetry\\SemConv\\*
- type: directory
value: src/SemConv/.*
- name: Contrib
collectors:
- type: className
regex: ^OpenTelemetry\\Contrib\\*
- type: directory
value: src/Contrib/.*
- name: Extension
collectors:
- type: directory
value: src/Extension/.*
- name: OtelProto
collectors:
- type: className
regex: ^OpenTelemetry\\Proto\\*
- type: className
regex: ^GPBMetadata\\Opentelemetry\\*
- type: directory
value: proto/otel/.*
- name: GoogleProtobuf
collectors:
- type: className
@ -76,47 +83,86 @@ deptrac:
collectors:
- type: className
regex: ^Composer\\*
- name: Thrift
- name: HttpClients
collectors:
- type: className
regex: ^Thrift\\*
- name: JaegerThrift
value: ^Symfony\\Component\\HttpClient\\*
- type: className
value: ^GuzzleHttp\\*
- type: className
value: ^Buzz\\*
- name: SPI
collectors:
- type: className
regex: ^Jaeger\\Thrift\\*
- name: Swoole
value: ^Nevay\\SPI\\*
- name: SymfonyConfig
collectors:
- type: className
regex: ^Swoole\\*
- name: CloudEvents
value: ^Symfony\\Component\\Config\\*
- type: className
value: ^Symfony\\Component\\Yaml\\*
- type: className
value: ^Symfony\\Component\\VarExporter\\*
- name: RamseyUuid
collectors:
- type: className
regex: ^CloudEvents\\*
regex: ^Ramsey\\Uuid\\*
- name: NyholmPsr7Server
collectors:
- type: className
regex: ^Nyholm\\Psr7Server\\*
- name: Polyfills
collectors:
- type: directory
value: deptrac/polyfills/.*
- type: directory
value: vendor/symfony/polyfill-php83
- name: DotenvProvider
collectors:
- type: className
regex: ^Symfony\\Component\\Dotenv\\*
- type: className
regex: ^Dotenv\\*
ruleset:
Context:
- FFI
- Polyfills
SemConv: ~
ConfigSDK:
- SymfonyConfig
- API
- SDK
- SPI
- PsrLog
- Composer
- Context
- Contrib
- Extension
- Polyfills
- DotenvProvider
API:
- Context
- SemConv
- PsrLog
- CloudEvents
- SPI
- Polyfills
SDK:
- +API
- ConfigSDK
- SemConv
- PsrHttp
- HttpPlug
- Composer
- HttpClients
- SPI
- RamseyUuid
- NyholmPsr7Server
Contrib:
- +SDK
- OtelProto
- +OtelProto
- Grpc
- Prometheus
- Thrift
- JaegerThrift
- Swoole
Extension:
- +API
OtelProto:
- GoogleProtobuf
- Grpc
JaegerThrift:
- Thrift

View File

@ -0,0 +1,5 @@
<?php
namespace OpenTelemetry\Config\SDK\Configuration;
class ComponentPlugin {}

View File

@ -0,0 +1,5 @@
<?php
namespace OpenTelemetry\Config\SDK\Configuration;
class ComponentProvider {}

View File

@ -0,0 +1,5 @@
<?php
namespace OpenTelemetry\Config\SDK\Configuration;
class ComponentProviderRegistry {}

View File

@ -0,0 +1,5 @@
<?php
namespace OpenTelemetry\Config\SDK\Configuration;
class Context {}

View File

@ -0,0 +1,3 @@
Polyfills for deptrac, which represent classes missing from some PHP versions, or classes
that deptrac does not understand.
We also use some symfony polyfills for deptrac, under `vendor/symfony/polyfill-*`.

View File

@ -1,9 +1,7 @@
version: '3.7'
services:
php:
build:
context: .
dockerfile: docker/Dockerfile
image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-8.1}
volumes:
- ./:/usr/src/myapp
depends_on:

View File

@ -0,0 +1,11 @@
services:
phpdoc:
image: phpdoc/phpdoc:3
volumes:
- ./:/data
preview:
image: nginx:alpine
ports:
- 8080:80
volumes:
- ./docs/build:/usr/share/nginx/html

View File

@ -23,7 +23,7 @@ services:
context: .
dockerfile: docker/examples/Dockerfile
args:
- PHP_VERSION=7.4-fpm
- PHP_VERSION=8.0-fpm
- EXT_ENABLE=redis
volumes:
- ./examples/prometheus/index.php:/var/www/public/index.php

View File

@ -1,7 +1,7 @@
version: '3.7'
services:
php:
image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-7.4}
image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-8.1}
volumes:
- ./:/usr/src/myapp
- ./:/usr/src/open-telemetry/

View File

@ -1,13 +1,11 @@
version: '3.7'
services:
php:
image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-7.4}
image: ghcr.io/open-telemetry/opentelemetry-php/opentelemetry-php-base:${PHP_VERSION:-8.1}
volumes:
- ./:/usr/src/myapp
user: "${PHP_USER}:root"
environment:
XDEBUG_MODE: ${XDEBUG_MODE:-off}
XDEBUG_CONFIG: ${XDEBUG_CONFIG:-''}
env_file:
- .env
zipkin:
image: openzipkin/zipkin-slim
ports:
@ -19,3 +17,8 @@ services:
ports:
- 9412:9412
- 16686:16686
collector:
image: otel/opentelemetry-collector-contrib
command: [ "--config=/etc/otel-collector-config.yml" ]
volumes:
- ./files/collector/otel-collector-config.yml:/etc/otel-collector-config.yml

View File

@ -1,34 +1,46 @@
ARG PHP_VERSION=7.4
FROM php:${PHP_VERSION}-cli-alpine as php_build
ADD https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions /usr/local/bin/
RUN chmod +x /usr/local/bin/install-php-extensions; \
apk add --update binutils; \
install-php-extensions \
ast-1.0.14 \
xdebug \
zip \
pcntl \
grpc \
sockets \
intl \
@composer \
; \
# strip debug symbols from extensions to reduce size
find /usr/local/lib/php/extensions -name "*.so" -exec strip --strip-debug {} \;;
FROM php_build
FROM composer:2.8 AS composer
FROM debian:bullseye
WORKDIR /usr/src/myapp
RUN apk add --no-cache bash git; \
find /usr/local/lib/php/extensions -type d -exec chmod +x -R {} \;; \
addgroup -g "1000" -S php; \
adduser --system \
--gecos "" \
--ingroup "php" \
--uid "1000" \
"php";
RUN apt-get update \
&& apt-get install -y --no-install-recommends git wget gnupg2 \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd --gid 1000 php \
&& useradd --system --uid 1000 --gid php --shell /bin/bash --create-home php
RUN apt-get update && apt-get install -y lsb-release apt-transport-https ca-certificates \
&& echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list \
&& wget -qO - https://packages.sury.org/php/apt.gpg | apt-key add - \
&& apt-get update
ARG PHP_VERSION=8.3
RUN apt-get install -y \
php${PHP_VERSION}-ast \
php${PHP_VERSION}-cli \
php${PHP_VERSION}-curl \
php${PHP_VERSION}-dev \
php${PHP_VERSION}-grpc \
php${PHP_VERSION}-intl \
php${PHP_VERSION}-mbstring \
php${PHP_VERSION}-opcache \
php${PHP_VERSION}-opentelemetry \
php${PHP_VERSION}-protobuf \
php${PHP_VERSION}-simplexml \
php${PHP_VERSION}-sockets \
php${PHP_VERSION}-xdebug \
php${PHP_VERSION}-zip \
php${PHP_VERSION}-mongodb \
php${PHP_VERSION}-amqp \
php${PHP_VERSION}-rdkafka \
php${PHP_VERSION}-mysqli \
php${PHP_VERSION}-pgsql \
unzip
COPY --from=composer /usr/bin/composer /usr/local/bin/composer
RUN echo "grpc.enable_fork_support = 1" > $(php-config --ini-dir)/40-otel-dev.ini \
&& echo "grpc.poll_strategy = epoll1" >> $(php-config --ini-dir)/40-otel-dev.ini \
&& echo "zend.assertions = 1" >> $(php-config --ini-dir)/40-otel-dev.ini
USER php

View File

@ -129,11 +129,11 @@ the `use` keyword. This is what our list of open-telemetry imported classes shou
```php
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use OpenTelemetry\API\Trace\AbstractSpan;
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\API\Trace\TracerInterface;
use OpenTelemetry\Contrib\Jaeger\Exporter as JaegerExporter;
use OpenTelemetry\Contrib\Zipkin\Exporter as ZipkinExporter;
use OpenTelemetry\SDK\Common\Export\Http\PsrTransportFactory;
use OpenTelemetry\SDK\Trace\Sampler\AlwaysOnSampler;
use OpenTelemetry\SDK\Trace\SpanProcessor\BatchSpanProcessor;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
@ -154,21 +154,8 @@ $httpFactory = new HttpFactory();
$tracer = (new TracerProvider(
[
new SimpleSpanProcessor(
new OpenTelemetry\Contrib\Jaeger\Exporter(
'Hello World Web Server Jaeger',
'http://localhost:9412/api/v2/spans',
$httpClient,
$httpFactory,
$httpFactory,
),
),
new BatchSpanProcessor(
new OpenTelemetry\Contrib\Zipkin\Exporter(
'Hello World Web Server Zipkin',
'http://localhost:9411/api/v2/spans',
$httpClient,
$httpFactory,
$httpFactory,
new OpenTelemetry\Contrib\Zipkin\Exporter(
PsrTransportFactory::discover()->create('http://zipkin:9411/api/v2/spans', 'application/json')
),
),
],
@ -255,7 +242,7 @@ child span of the rootSpan. We can do the same as follows:
- Import the required functions on top of the file:
```php
use OpenTelemetry\API\Trace\AbstractSpan;
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\SDK\Trace\TracerProvider;
```
@ -267,7 +254,7 @@ use OpenTelemetry\SDK\Trace\TracerProvider;
$tracer = TracerProvider::getDefaultTracer();
if ($tracer) {
/** @var Span $span */
$span = AbstractSpan::getCurrent();
$span = Span::getCurrent();
$span->setAttribute('foo', 'bar');
$span->setAttribute('Application', 'Laravel');

26
examples/autoload_sdk.php Normal file
View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
putenv('OTEL_PHP_AUTOLOAD_ENABLED=true');
putenv('OTEL_TRACES_EXPORTER=otlp');
putenv('OTEL_METRICS_EXPORTER=otlp');
putenv('OTEL_LOGS_EXPORTER=otlp');
putenv('OTEL_EXPORTER_OTLP_PROTOCOL=grpc');
putenv('OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317');
putenv('OTEL_PROPAGATORS=b3,baggage,tracecontext');
echo 'autoloading SDK example starting...' . PHP_EOL;
// Composer autoloader will execute SDK/_autoload.php which will register global instrumentation from environment configuration
require dirname(__DIR__) . '/vendor/autoload.php';
$instrumentation = new \OpenTelemetry\API\Instrumentation\CachedInstrumentation('demo');
$instrumentation->tracer()->spanBuilder('root')->startSpan()->end();
$instrumentation->meter()->createCounter('cnt')->add(1);
$instrumentation->eventLogger()->emit('foo', 'hello, otel');
echo 'Finished!' . PHP_EOL;

View File

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
putenv('OTEL_PHP_AUTOLOAD_ENABLED=true');
putenv('OTEL_TRACES_EXPORTER=otlp');
putenv('OTEL_EXPORTER_OTLP_PROTOCOL=grpc');
putenv('OTEL_METRICS_EXPORTER=otlp');
putenv('OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=grpc');
putenv('OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317');
putenv('OTEL_PHP_TRACES_PROCESSOR=batch');
echo 'autoloading SDK example starting...' . PHP_EOL;
// Composer autoloader will execute SDK/_autoload.php which will register global instrumentation from environment configuration
require dirname(__DIR__) . '/vendor/autoload.php';
/**
* create a transport factory to override the default grpc one (for both traces and metrics):
* @psalm-suppress InvalidReturnType
* @psalm-suppress InvalidReturnStatement
* @psalm-suppress MissingTemplateParam
*/
$factory = new class() implements \OpenTelemetry\SDK\Common\Export\TransportFactoryInterface {
#[\Override]
public function create(string $endpoint, string $contentType, array $headers = [], $compression = null, float $timeout = 10., int $retryDelay = 100, int $maxRetries = 3, ?string $cacert = null, ?string $cert = null, ?string $key = null): \OpenTelemetry\SDK\Common\Export\TransportInterface
{
return new class() implements \OpenTelemetry\SDK\Common\Export\TransportInterface {
#[\Override]
public function contentType(): string
{
return 'application/x-protobuf';
}
#[\Override]
public function send(string $payload, ?\OpenTelemetry\SDK\Common\Future\CancellationInterface $cancellation = null): \OpenTelemetry\SDK\Common\Future\FutureInterface
{
return new \OpenTelemetry\SDK\Common\Future\CompletedFuture(null);
}
#[\Override]
public function shutdown(?\OpenTelemetry\SDK\Common\Future\CancellationInterface $cancellation = null): bool
{
return true;
}
#[\Override]
public function forceFlush(?\OpenTelemetry\SDK\Common\Future\CancellationInterface $cancellation = null): bool
{
return true;
}
};
}
};
\OpenTelemetry\SDK\Registry::registerTransportFactory('grpc', $factory, true);
$instrumentation = new \OpenTelemetry\API\Instrumentation\CachedInstrumentation('demo');
$instrumentation->tracer()->spanBuilder('root')->startSpan()->end();
$instrumentation->meter()->createCounter('cnt')->add(1);
echo 'Finished!' . PHP_EOL;

View File

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../vendor/autoload.php';
echo 'Starting baggage example' . PHP_EOL;
$propagator = \OpenTelemetry\API\Baggage\Propagation\BaggagePropagator::getInstance();
$scopes = [];
//extract baggage from a carrier (eg, inbound http request headers), and store in context
$carrier = [
'baggage' => 'key1=value1,key2=value2;property1',
];
echo 'Initial baggage input: ' . json_encode($carrier) . PHP_EOL;
echo 'Extracting baggage from carrier...' . PHP_EOL;
$context = $propagator->extract($carrier);
$scopes[] = $context->activate();
//get the baggage, and extract values from it
echo 'Retrieving baggage values...' . PHP_EOL;
$baggage = \OpenTelemetry\API\Baggage\Baggage::getCurrent();
echo 'key1: ' . $baggage->getValue('key1') . PHP_EOL;
echo 'key2: ' . $baggage->getValue('key2') . PHP_EOL;
$entry = $baggage->getEntry('key2');
echo 'key2 metadata: ' . ($entry !== null ? $entry->getMetadata()->getValue() : '-unset-') . PHP_EOL;
//remove a value from baggage and add a value
echo 'removing key1, adding key3 to baggage...' . PHP_EOL;
$scopes[] = $baggage->toBuilder()->remove('key1')->set('key3', 'value3')->build()->activate();
//extract baggage from context, and store in a different carrier (eg, outbound http request headers)
$out = [];
$propagator->inject($out);
echo 'Extracted baggage: ' . json_encode($out) . PHP_EOL;
//clear baggage (to avoid sending to an untrusted process), see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/baggage/api.md#clear-baggage-in-the-context
echo 'Clearing baggage...' . PHP_EOL;
$scopes[] = \OpenTelemetry\API\Baggage\Baggage::getEmpty()->activate();
$cleared = [];
$propagator->extract($cleared);
echo 'Extracted baggage: ' . json_encode($cleared) . PHP_EOL;
//detach scopes
foreach (array_reverse($scopes) as $scope) {
$scope->detach();
}
echo 'Finished baggage example' . PHP_EOL;

View File

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../vendor/autoload.php';
use OpenTelemetry\API\Baggage\Baggage;
use OpenTelemetry\API\Baggage\Propagation\BaggagePropagator;
use OpenTelemetry\Context\Propagation\EnvironmentGetterSetter;
$propagator = BaggagePropagator::getInstance();
$envGetterSetter = EnvironmentGetterSetter::getInstance();
$isChild = isset($argv[1]) && $argv[1] === 'child';
if (!$isChild) {
$baggage = Baggage::getBuilder()
->set('key1', 'value1')
->set('key2', 'value2')
->build();
$baggageScope = $baggage->activate();
// Inject baggage into environment variables
$carrier = [];
$propagator->inject($carrier, $envGetterSetter);
// Execute child process
$command = sprintf('%s %s %s', PHP_BINARY, escapeshellarg(__FILE__), 'child');
$handle = popen($command, 'w');
if ($handle === false) {
echo 'Failed to execute child process.' . PHP_EOL;
} else {
pclose($handle);
}
$baggageScope->detach();
} else {
// Extract baggage from environment variables
$context = $propagator->extract([], $envGetterSetter);
$scope = $context->activate();
// Get values from baggage
$baggage = Baggage::getCurrent();
echo 'key1: ' . $baggage->getValue('key1') . PHP_EOL;
echo 'key2: ' . $baggage->getValue('key2') . PHP_EOL;
$scope->detach();
}

View File

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Common\Export\Stream\StreamTransportFactory;
use OpenTelemetry\SDK\Common\Instrumentation\InstrumentationScopeFactory;
use OpenTelemetry\SDK\Metrics\Exemplar\ExemplarFilter\WithSampledTraceExemplarFilter;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Metrics\StalenessHandler\ImmediateStalenessHandlerFactory;
use OpenTelemetry\SDK\Metrics\View\CriteriaViewRegistry;
use OpenTelemetry\SDK\Resource\ResourceInfoFactory;
use OpenTelemetry\SDK\Trace\TracerProvider;
require __DIR__ . '/../vendor/autoload.php';
//@see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#general-sdk-configuration
putenv('OTEL_SDK_DISABLED=true');
echo 'Creating (disabled) signals' . PHP_EOL;
//trace
$tracer = (new TracerProvider())->getTracer('io.opentelemetry.contrib.php');
echo get_class($tracer) . PHP_EOL;
//metrics
$clock = Clock::getDefault();
$reader = new ExportingReader(new MetricExporter((new StreamTransportFactory())->create(STDOUT, 'application/x-ndjson')));
$views = new CriteriaViewRegistry();
$meterProvider = new MeterProvider(
null,
ResourceInfoFactory::emptyResource(),
$clock,
Attributes::factory(),
new InstrumentationScopeFactory(Attributes::factory()),
[$reader],
$views,
new WithSampledTraceExemplarFilter(),
new ImmediateStalenessHandlerFactory(),
);
$meter = $meterProvider->getMeter('io.opentelemetry.contrib.php');
echo get_class($meter) . PHP_EOL;

View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Globals;
/**
* The OpenTelemetry SDK is able to emit some metrics about its internal state. For example,
* batch span and log processor state.
* This feature can be enabled via the OTEL_PHP_INTERNAL_METRICS_ENABLED setting.
*/
putenv('OTEL_PHP_INTERNAL_METRICS_ENABLED=true');
putenv('OTEL_PHP_AUTOLOAD_ENABLED=true');
putenv('OTEL_TRACES_EXPORTER=console');
putenv('OTEL_METRICS_EXPORTER=console');
putenv('OTEL_LOGS_EXPORTER=console');
require __DIR__ . '/../vendor/autoload.php';
$tracerProvider = Globals::tracerProvider();
$tracerProvider->getTracer('demo')->spanBuilder('root')->startSpan()->end();

View File

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Instrumentation\Configurator;
use OpenTelemetry\SDK\Trace\SpanExporter\ConsoleSpanExporterFactory;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
require __DIR__ . '/../vendor/autoload.php';
/**
* Example of globally registering <Signal>Provider instances.
* Generally this is hidden inside the SDK builder or SDK autoloading,
* but you can also do it manually. The providers are stored in
* context, and reset to previous values or defaults when the
* scope is detached.
*/
//before, a no-op provider is provided by default
echo 'Before: ' . get_class(Globals::tracerProvider()) . PHP_EOL;
$tracerProvider = TracerProvider::builder()->addSpanProcessor(
new SimpleSpanProcessor(
(new ConsoleSpanExporterFactory())->create()
)
)->build();
$configurator = Configurator::create()
->withTracerProvider($tracerProvider);
$scope = $configurator->activate();
//activated, now our $tracerProvider is globally available
echo 'During: ' . get_class(Globals::tracerProvider()) . PHP_EOL;
$scope->detach();
//after scope detached, back to default no-op providers:
echo 'After: ' . get_class(Globals::tracerProvider()) . PHP_EOL;

View File

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace _;
use Nevay\SPI\ServiceLoader;
use OpenTelemetry\API\Configuration\Context;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Instrumentation\AutoInstrumentation\ExtensionHookManager;
use OpenTelemetry\API\Instrumentation\AutoInstrumentation\Instrumentation;
use OpenTelemetry\Config\SDK\Configuration;
use OpenTelemetry\Example\Example;
use const PHP_EOL;
/**
* This example uses SPI (see root composer.json extra.spi) to configure an example auto-instrumentation from a YAML file
*/
// EXAMPLE_INSTRUMENTATION_SPAN_NAME=test1234 php examples/instrumentation/configure_instrumentation.php
require __DIR__ . '/../../vendor/autoload.php';
Configuration::parseFile(__DIR__ . '/otel-sdk.yaml')->create(new Context())->setAutoShutdown(true)->buildAndRegisterGlobal();
$configuration = \OpenTelemetry\Config\SDK\Instrumentation::parseFile(__DIR__ . '/otel-sdk.yaml')->create();
$hookManager = new ExtensionHookManager();
$context = new \OpenTelemetry\API\Instrumentation\AutoInstrumentation\Context(Globals::tracerProvider(), Globals::meterProvider(), Globals::loggerProvider(), Globals::propagator());
foreach (ServiceLoader::load(Instrumentation::class) as $instrumentation) {
$instrumentation->register($hookManager, $configuration, $context);
}
echo (new Example())->test(), PHP_EOL;

View File

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace _;
use OpenTelemetry\Example\Example;
use const PHP_EOL;
use function putenv;
/**
* This example uses SPI (see root composer.json extra.spi) to configure an example auto-instrumentation from environment variables.
*/
// php examples/instrumentation/configure_instrumentation_env.php
putenv('OTEL_PHP_AUTOLOAD_ENABLED=true');
putenv('OTEL_PHP_EXAMPLE_INSTRUMENTATION_SPAN_NAME=example span');
putenv('OTEL_TRACES_EXPORTER=console');
putenv('OTEL_METRICS_EXPORTER=none');
putenv('OTEL_LOGS_EXPORTER=none');
require __DIR__ . '/../../vendor/autoload.php';
echo (new Example())->test(), PHP_EOL;

View File

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace _;
use OpenTelemetry\Example\Example;
use const PHP_EOL;
/**
* This example uses SPI (see root composer.json extra.spi) to configure an example auto-instrumentation from a YAML file.
* The YAML file paths are relative to the current working directory.
*/
// EXAMPLE_INSTRUMENTATION_SPAN_NAME=test1234 php examples/instrumentation/configure_instrumentation_global.php
putenv('OTEL_PHP_AUTOLOAD_ENABLED=true');
putenv('OTEL_EXPERIMENTAL_CONFIG_FILE=examples/instrumentation/otel-sdk.yaml');
require __DIR__ . '/../../vendor/autoload.php';
echo (new Example())->test(), PHP_EOL;

View File

@ -0,0 +1,18 @@
file_format: '0.4'
propagator:
composite: []
tracer_provider:
processors:
- simple:
exporter:
console:
sampler:
always_on:
instrumentation:
general:
php:
example_instrumentation:
span_name: ${EXAMPLE_INSTRUMENTATION_SPAN_NAME:-example span}

29
examples/load_config.php Normal file
View File

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
use OpenTelemetry\Config\SDK\Configuration;
require __DIR__ . '/../vendor/autoload.php';
echo 'load config SDK example starting...' . PHP_EOL;
$config = Configuration::parseFile(__DIR__ . '/load_config.yaml');
$sdk = $config
->create()
->setAutoShutdown(true)
->build();
$tracer = $sdk->getTracerProvider()->getTracer('demo');
$meter = $sdk->getMeterProvider()->getMeter('demo');
$eventLogger = $sdk->getEventLoggerProvider()->getEventLogger('demo');
$span = $tracer->spanBuilder('root')->startSpan();
$scope = $span->activate();
$meter->createCounter('cnt')->add(1);
$eventLogger->emit('foo', 'hello, otel');
$scope->detach();
$span->end();
echo 'Finished!' . PHP_EOL;

46
examples/load_config.yaml Normal file
View File

@ -0,0 +1,46 @@
file_format: '0.3'
resource:
attributes:
- name: service.name
value: opentelemetry-demo
attributes_list: service.name=unused,example.foo=foo_value,example.bar=bar_value
propagators:
composite: [ tracecontext, baggage ]
exporters:
otlp: &otlp-exporter
protocol: http/protobuf
endpoint: http://collector:4318
tracer_provider:
sampler:
parent_based:
root:
always_on:
processors:
- simple:
exporter:
console:
- batch:
exporter:
otlp: *otlp-exporter
meter_provider:
readers:
- periodic:
exporter:
console:
- periodic:
exporter:
otlp:
<<: *otlp-exporter
temporality_preference: lowmemory
logger_provider:
processors:
- simple:
exporter:
console:
- batch:
exporter:
otlp: *otlp-exporter

View File

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
use OpenTelemetry\Config\SDK\Configuration;
require __DIR__ . '/../vendor/autoload.php';
echo 'load config SDK example starting...' . PHP_EOL;
$_SERVER['OTEL_SERVICE_NAME'] = 'opentelemetry-demo';
$_SERVER['OTEL_EXPORTER_OTLP_PROTOCOL'] = 'http/protobuf';
$_SERVER['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://collector:4318';
$_SERVER['OTEL_TRACES_SAMPLER_ARG'] = '0.5';
$config = Configuration::parseFile(__DIR__ . '/load_config_env.yaml');
$sdk = $config
->create()
->setAutoShutdown(true)
->build();
$tracer = $sdk->getTracerProvider()->getTracer('demo');
$meter = $sdk->getMeterProvider()->getMeter('demo');
$eventLogger = $sdk->getEventLoggerProvider()->getEventLogger('demo');
$tracer->spanBuilder('root')->startSpan()->end();
$meter->createCounter('cnt')->add(1);
$eventLogger->emit('foo', 'hello, otel');
echo 'Finished!' . PHP_EOL;

View File

@ -0,0 +1,50 @@
file_format: '0.3'
disabled: ${OTEL_SDK_DISABLED}
resource:
attributes:
- name: service.name
value: ${OTEL_SERVICE_NAME}
propagators:
composite: [ tracecontext, baggage ]
attribute_limits:
attribute_value_length_limit: ${OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT}
attribute_count_limit: ${OTEL_ATTRIBUTE_COUNT_LIMIT}
exporters:
otlp: &otlp-exporter
protocol: ${OTEL_EXPORTER_OTLP_PROTOCOL}
endpoint: ${OTEL_EXPORTER_OTLP_ENDPOINT}
certificate: ${OTEL_EXPORTER_OTLP_CERTIFICATE}
client_key: ${OTEL_EXPORTER_OTLP_CLIENT_KEY}
client_certificate: ${OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE}
compression: ${OTEL_EXPORTER_OTLP_COMPRESSION}
timeout: ${OTEL_EXPORTER_OTLP_TIMEOUT}
tracer_provider:
sampler:
parent_based:
root:
trace_id_ratio_based:
ratio: ${OTEL_TRACES_SAMPLER_ARG}
limits:
attribute_value_length_limit: ${OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT}
attribute_count_limit: ${OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT}
event_count_limit: ${OTEL_SPAN_EVENT_COUNT_LIMIT}
link_count_limit: ${OTEL_SPAN_LINK_COUNT_LIMIT}
event_attribute_count_limit: ${OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT}
link_attribute_count_limit: ${OTEL_LINK_ATTRIBUTE_COUNT_LIMIT}
processors:
- simple:
exporter:
console: {}
- batch:
schedule_delay: ${OTEL_BSP_SCHEDULE_DELAY}
export_timeout: ${OTEL_BSP_EXPORT_TIMEOUT}
max_queue_size: ${OTEL_BSP_MAX_QUEUE_SIZE}
max_export_batch_size: ${OTEL_BSP_MAX_EXPORT_BATCH_SIZE}
exporter:
otlp: *otlp-exporter

View File

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\API\Logs\Severity;
use OpenTelemetry\API\Signals;
use OpenTelemetry\Contrib\Grpc\GrpcTransportFactory;
use OpenTelemetry\Contrib\Otlp\LogsExporter;
use OpenTelemetry\Contrib\Otlp\OtlpUtil;
use OpenTelemetry\SDK\Common\Instrumentation\InstrumentationScopeFactory;
use OpenTelemetry\SDK\Logs\EventLoggerProvider;
use OpenTelemetry\SDK\Logs\LoggerProvider;
use OpenTelemetry\SDK\Logs\LogRecordLimitsBuilder;
use OpenTelemetry\SDK\Logs\Processor\BatchLogRecordProcessor;
require __DIR__ . '/../../../vendor/autoload.php';
$transport = (new GrpcTransportFactory())->create('http://collector:4317' . OtlpUtil::method(Signals::LOGS));
$exporter = new LogsExporter($transport);
$loggerProvider = new LoggerProvider(
new BatchLogRecordProcessor(
$exporter,
Clock::getDefault()
),
new InstrumentationScopeFactory(
(new LogRecordLimitsBuilder())->build()->getAttributeFactory()
)
);
$eventLoggerProvider = new EventLoggerProvider($loggerProvider);
$eventLogger = $eventLoggerProvider->getEventLogger('demo', '1.0', 'http://schema.url', ['foo' => 'bar']);
$eventLogger->emit(
name: 'foo',
body: ['foo' => 'bar', 'baz' => 'bat', 'msg' => 'hello world'],
severityNumber: Severity::INFO
);
$eventLogger->emit(
'bar',
'otel is great'
);
$loggerProvider->shutdown();

View File

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Logs\LogRecord;
use OpenTelemetry\API\Logs\Severity;
use OpenTelemetry\Contrib\Otlp\LogsExporter;
use OpenTelemetry\Contrib\Otlp\OtlpHttpTransportFactory;
use OpenTelemetry\SDK\Common\Instrumentation\InstrumentationScopeFactory;
use OpenTelemetry\SDK\Logs\EventLoggerProvider;
use OpenTelemetry\SDK\Logs\LoggerProvider;
use OpenTelemetry\SDK\Logs\LogRecordLimitsBuilder;
use OpenTelemetry\SDK\Logs\Processor\SimpleLogRecordProcessor;
require __DIR__ . '/../../../vendor/autoload.php';
$transport = (new OtlpHttpTransportFactory())->create('http://collector:4318/v1/logs', 'application/json');
$exporter = new LogsExporter($transport);
$loggerProvider = new LoggerProvider(
new SimpleLogRecordProcessor(
$exporter
),
new InstrumentationScopeFactory(
(new LogRecordLimitsBuilder())->build()->getAttributeFactory()
)
);
$eventLoggerProvider = new EventLoggerProvider($loggerProvider);
$eventLogger = $eventLoggerProvider->getEventLogger('demo', '1.0', 'https://opentelemetry.io/schemas/1.7.1', ['foo' => 'bar']);
$eventLogger->emit(
name: 'foo',
body: ['foo' => 'bar', 'baz' => 'bat', 'msg' => 'hello world'],
timestamp: (new \DateTime())->getTimestamp() * LogRecord::NANOS_PER_SECOND,
severityNumber: Severity::INFO,
);

View File

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\API\Logs\Severity;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Common\Instrumentation\InstrumentationScopeFactory;
use OpenTelemetry\SDK\Logs\EventLogger;
use OpenTelemetry\SDK\Logs\EventLoggerProvider;
use OpenTelemetry\SDK\Logs\Exporter\ConsoleExporterFactory;
use OpenTelemetry\SDK\Logs\LoggerProvider;
use OpenTelemetry\SDK\Logs\Processor\BatchLogRecordProcessor;
require __DIR__ . '/../../../vendor/autoload.php';
$loggerProvider = new LoggerProvider(
new BatchLogRecordProcessor(
(new ConsoleExporterFactory())->create(),
Clock::getDefault()
),
new InstrumentationScopeFactory(Attributes::factory())
);
$eventLoggerProvider = new EventLoggerProvider($loggerProvider);
//get a logger, and emit a log record from an EventLogger.
$eventLoggerOne = $eventLoggerProvider->getEventLogger('demo', '1.0');
$eventLoggerTwo = $eventLoggerProvider->getEventLogger('demo', '2.0');
$payload = ['foo' => 'bar', 'baz' => 'bat', 'msg' => 'hello world'];
$eventLoggerOne->emit(name: 'foo', body: $payload, severityNumber: Severity::INFO);
$eventLoggerOne->emit('bar', 'hello world');
$eventLoggerTwo->emit(name: 'foo', body: $payload, severityNumber: Severity::INFO);
//shut down logger provider
$loggerProvider->shutdown();

View File

@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\LogRecord as MonologLogRecord;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Logs\LoggerInterface;
use OpenTelemetry\API\Logs\LoggerProviderInterface;
use OpenTelemetry\API\Logs\LogRecord;
use OpenTelemetry\API\Logs\Severity;
use Psr\Log\LogLevel;
/**
* This example creates a monolog handler which integrates with opentelemetry. In this example, the logger is
* configured from environment, and autoloaded as part of composer where is can be retrieved from `Globals`.
*
* @see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/logs/bridge-api.md#usage
*
* We have an official monolog handler, @see https://packagist.org/packages/open-telemetry/opentelemetry-logger-monolog
*/
// create env vars before requiring composer
putenv('OTEL_PHP_AUTOLOAD_ENABLED=true');
putenv('OTEL_METRICS_EXPORTER=none');
putenv('OTEL_LOGS_EXPORTER=otlp');
putenv('OTEL_LOGS_PROCESSOR=batch');
putenv('OTEL_EXPORTER_OTLP_PROTOCOL=grpc');
putenv('OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317');
require __DIR__ . '/../../../vendor/autoload.php';
$streamHandler = new StreamHandler(STDOUT, LogLevel::DEBUG);
$tracer = Globals::tracerProvider()->getTracer('monolog-demo');
//otel handler for Monolog v3
$otelHandler = new class(LogLevel::INFO) extends AbstractProcessingHandler {
private LoggerInterface $logger;
/**
* @psalm-suppress ArgumentTypeCoercion
*/
public function __construct(string $level, bool $bubble = true, ?LoggerProviderInterface $provider = null)
{
parent::__construct($level, $bubble);
$provider ??= Globals::loggerProvider();
$this->logger = $provider->getLogger('monolog-demo', null, null, ['logging.library' => 'monolog']);
}
#[\Override]
protected function write(MonologLogRecord $record): void
{
$this->logger->emit($this->convert($record));
}
private function convert(MonologLogRecord $record): LogRecord
{
return (new LogRecord($record['message']))
->setSeverityText($record->level->toPsrLogLevel())
->setTimestamp((int) (microtime(true) * (float) LogRecord::NANOS_PER_SECOND))
->setObservedTimestamp((int) $record->datetime->format('U') * LogRecord::NANOS_PER_SECOND)
->setSeverityNumber(Severity::fromPsr3($record->level->toPsrLogLevel()))
->setAttributes($record->context + $record->extra);
}
};
//start a span so that logs contain span context
$span = $tracer->spanBuilder('foo')->startSpan();
$scope = $span->activate();
$monolog = new Logger('otel-php-monolog', [$otelHandler, $streamHandler]);
$monolog->debug('debug message');
$monolog->info('hello world', ['extra_one' => 'value_one']);
$monolog->alert('foo', ['extra_two' => 'value_two']);
$scope->detach();
$span->end();

View File

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
use OpenTelemetry\API\Logs\Severity;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Common\Instrumentation\InstrumentationScopeFactory;
use OpenTelemetry\SDK\Logs\EventLoggerProvider;
use OpenTelemetry\SDK\Logs\Exporter\ConsoleExporterFactory;
use OpenTelemetry\SDK\Logs\LoggerProvider;
use OpenTelemetry\SDK\Logs\Processor\SimpleLogRecordProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
require __DIR__ . '/../../vendor/autoload.php';
/**
* Example of logging used in conjunction with tracing. The trace id and span id
* will be injected into the logged record.
* Note that logging output is human-readable JSON, and is not compatible with the
* OTEL format.
*/
$loggerProvider = new LoggerProvider(
new SimpleLogRecordProcessor(
(new ConsoleExporterFactory())->create()
),
new InstrumentationScopeFactory(Attributes::factory())
);
$eventLoggerProvider = new EventLoggerProvider($loggerProvider);
$tracerProvider = new TracerProvider();
$tracer = $tracerProvider->getTracer('demo-tracer');
//start and activate a span
$span = $tracer->spanBuilder('root')->startSpan();
$scope = $span->activate();
echo 'Trace id: ' . $span->getContext()->getTraceId() . PHP_EOL;
echo 'Span id: ' . $span->getContext()->getSpanId() . PHP_EOL;
//get an event logger, and emit an event. The active context (trace id + span id) will be
//attached to the log record
$eventLogger = $eventLoggerProvider->getEventLogger('demo', '1.0', 'http://schema.url', ['foo' => 'bar']);
$payload = ['foo' => 'bar', 'baz' => 'bat', 'msg' => 'hello world'];
$eventLogger->emit(name: 'foo', body: $payload, severityNumber: Severity::INFO);
//end span
$span->end();
$scope->detach();

View File

@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
use OpenTelemetry\API\Logs\LogRecord;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Logs\Exporter\ConsoleExporterFactory;
use OpenTelemetry\SDK\Logs\LoggerProvider;
use OpenTelemetry\SDK\Logs\Processor\SimpleLogRecordProcessor;
use OpenTelemetry\SDK\Resource\ResourceInfo;
require __DIR__ . '/../../vendor/autoload.php';
$loggerProvider = LoggerProvider::builder()
->addLogRecordProcessor(
new SimpleLogRecordProcessor(
(new ConsoleExporterFactory())->create()
)
)
->setResource(ResourceInfo::create(Attributes::create(['foo' => 'bar'])))
->build();
$logger = $loggerProvider->getLogger('demo', '1.0', 'http://schema.url', ['foo' => 'bar']);
$record = (new LogRecord(['foo' => 'bar', 'baz' => 'bat', 'msg' => 'hello world']))
->setSeverityText('INFO')
->setSeverityNumber(9);
/**
* Note that Loggers should only be used directly by a log appender.
* @see https://github.com/open-telemetry/opentelemetry-specification/blob/v1.32.0/specification/logs/bridge-api.md#logs-bridge-api
*/
$logger->emit($record);
$loggerProvider->shutdown();

View File

@ -3,12 +3,15 @@
// Example based on https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/supplementary-guidelines.md#synchronous-example
declare(strict_types=1);
namespace OpenTelemetry\Example;
require_once __DIR__ . '/../../vendor/autoload.php';
use OpenTelemetry\Contrib\Otlp\StreamMetricExporter;
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Common\Export\Stream\StreamTransportFactory;
use OpenTelemetry\SDK\Common\Instrumentation\InstrumentationScopeFactory;
use OpenTelemetry\SDK\Common\Time\ClockFactory;
use OpenTelemetry\SDK\Metrics\Aggregation\ExplicitBucketHistogramAggregation;
use OpenTelemetry\SDK\Metrics\Exemplar\ExemplarFilter\WithSampledTraceExemplarFilter;
use OpenTelemetry\SDK\Metrics\MeterProvider;
@ -19,8 +22,8 @@ use OpenTelemetry\SDK\Metrics\View\SelectionCriteria\InstrumentNameCriteria;
use OpenTelemetry\SDK\Metrics\View\ViewTemplate;
use OpenTelemetry\SDK\Resource\ResourceInfoFactory;
$clock = ClockFactory::getDefault();
$reader = new ExportingReader(new StreamMetricExporter(STDOUT, /*Temporality::CUMULATIVE*/), $clock);
$clock = Clock::getDefault();
$reader = new ExportingReader(new MetricExporter((new StreamTransportFactory())->create(STDOUT, 'application/x-ndjson'), /*Temporality::CUMULATIVE*/));
// Let's imagine we export the metrics as Histogram, and to simplify the story we will only have one histogram bucket (-Inf, +Inf):
$views = new CriteriaViewRegistry();

View File

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\SDK\Metrics\MeterProviderFactory;
require __DIR__ . '/../../../vendor/autoload.php';
/**
* Create a console exporter from environment variables, and generate a histogram.
*/
putenv('OTEL_METRICS_EXPORTER=console');
$meterProvider = (new MeterProviderFactory())->create();
$meter = $meterProvider->getMeter('io.opentelemetry.contrib.php');
$hist = $meter ->createHistogram('example', 'bytes', 'The number of bytes received.');
for ($i=0; $i<=5000; $i++) {
$hist->record(rand(0, 1024));
}
$meterProvider->shutdown();

View File

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\API\Signals;
use OpenTelemetry\Contrib\Grpc\GrpcTransportFactory;
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\Contrib\Otlp\OtlpUtil;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
$clock = Clock::getDefault();
$reader = new ExportingReader(
new MetricExporter(
(new GrpcTransportFactory())->create('http://collector:4317' . OtlpUtil::method(Signals::METRICS))
)
);
$metricsGenerator = new ExampleMetricsGenerator($reader, $clock);
$metricsGenerator->generate();

View File

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\SDK\Common\Export\Http\PsrTransportFactory;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
$clock = Clock::getDefault();
$reader = new ExportingReader(
new MetricExporter(
(new PsrTransportFactory())->create('http://collector:4318/v1/metrics', \OpenTelemetry\Contrib\Otlp\ContentTypes::JSON)
)
);
$metricsGenerator = new ExampleMetricsGenerator($reader, $clock);
$metricsGenerator->generate();

View File

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\SDK\Common\Export\Stream\StreamTransportFactory;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
$clock = Clock::getDefault();
// @psalm-suppress InternalMethod
$reader = new ExportingReader(
new MetricExporter(
(new StreamTransportFactory())->create(STDOUT, 'application/x-ndjson')
)
);
$metricsGenerator = new ExampleMetricsGenerator($reader, $clock);
$metricsGenerator->generate();

View File

@ -1,75 +0,0 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use OpenTelemetry\API\Metrics\ObserverInterface;
use OpenTelemetry\Contrib\OtlpHttp\MetricExporter;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Common\Instrumentation\InstrumentationScopeFactory;
use OpenTelemetry\SDK\Common\Time\ClockFactory;
use OpenTelemetry\SDK\Metrics\Exemplar\ExemplarFilter\WithSampledTraceExemplarFilter;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Metrics\StalenessHandler\ImmediateStalenessHandlerFactory;
use OpenTelemetry\SDK\Metrics\View\CriteriaViewRegistry;
use OpenTelemetry\SDK\Resource\ResourceInfoFactory;
$clock = ClockFactory::getDefault();
$reader = new ExportingReader(MetricExporter::create(
new Client(),
new HttpFactory(),
new HttpFactory(),
'http://collector:4318/v1/metrics',
), $clock);
$meterProvider = new MeterProvider(
null,
ResourceInfoFactory::defaultResource(),
$clock,
Attributes::factory(),
new InstrumentationScopeFactory(Attributes::factory()),
[$reader],
new CriteriaViewRegistry(),
new WithSampledTraceExemplarFilter(),
new ImmediateStalenessHandlerFactory(),
);
$meter = $meterProvider->getMeter('io.opentelemetry.contrib.php');
$meter
->createObservableUpDownCounter('process.memory.usage', 'By', 'The amount of physical memory in use.')
->observe(static function (ObserverInterface $observer): void {
$observer->observe(memory_get_usage(true));
});
$serverDuration = $meter
->createHistogram('http.server.duration', 'ms', 'measures the duration inbound HTTP requests');
// During the time range (T0, T1]:
$serverDuration->record(50, ['http.method' => 'GET', 'http.status_code' => 200]);
$serverDuration->record(100, ['http.method' => 'GET', 'http.status_code' => 200]);
$serverDuration->record(1, ['http.method' => 'GET', 'http.status_code' => 500]);
$reader->collect();
// During the time range (T1, T2]:
$reader->collect();
// During the time range (T2, T3]:
$serverDuration->record(5, ['http.method' => 'GET', 'http.status_code' => 500]);
$serverDuration->record(2, ['http.method' => 'GET', 'http.status_code' => 500]);
$reader->collect();
// During the time range (T3, T4]:
$serverDuration->record(100, ['http.method' => 'GET', 'http.status_code' => 200]);
$reader->collect();
// During the time range (T4, T5]:
$serverDuration->record(100, ['http.method' => 'GET', 'http.status_code' => 200]);
$serverDuration->record(30, ['http.method' => 'GET', 'http.status_code' => 200]);
$serverDuration->record(50, ['http.method' => 'GET', 'http.status_code' => 200]);
$reader->collect();
$meterProvider->shutdown();

View File

@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
use OpenTelemetry\API\Metrics\ObserverInterface;
use OpenTelemetry\SDK\Metrics\Data\Temporality;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricExporter\ConsoleMetricExporter;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Resource\ResourceInfoFactory;
require_once __DIR__ . '/../../vendor/autoload.php';
/**
* Basic async/observable metrics generation example. This uses the console
* metrics exporter to print metrics out in a human-readable format (but does
* not require protobuf or the OTLP exporter)
*/
$reader = new ExportingReader(
new ConsoleMetricExporter(Temporality::DELTA)
);
$meterProvider = MeterProvider::builder()
->setResource(ResourceInfoFactory::emptyResource())
->addReader($reader)
->build();
$meterProvider
->getMeter('demo_meter')
->createObservableGauge('number', 'items', 'Random number')
->observe(static function (ObserverInterface $observer): void {
$observer->observe(random_int(0, 256));
});
//metrics are collected every time `collect()` is called
$reader->collect();

View File

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Metrics\ObserverInterface;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricExporter\ConsoleMetricExporterFactory;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
require_once __DIR__ . '/../../vendor/autoload.php';
/**
* This example uses the meter provider builder, then two different methods to achieve a
* similar result: export metrics about the length of a job queue.
*
* First, an up/down meter is manually increased/decreased (eg as jobs are added/removed)
* Second, an async callback is used to generate a point-in-time observation of the queue
* length. The callback is executed when `reader::collect()` is called.
*/
$reader = new ExportingReader((new ConsoleMetricExporterFactory())->create());
$meterProvider = MeterProvider::builder()
->addReader($reader)
->build();
//example 1: manually adjust an up/down counter to track job queue length
$up_down = $meterProvider
->getMeter('demo')
->createUpDownCounter('queued', 'jobs', 'The number of jobs enqueued (non-async)');
$up_down->add(3); //jobs added
$up_down->add(-1); //job completed
$up_down->add(1); //job added
//example 2: observe the "queue", which happens every time `$reader->collect()` is called
$queue = [
'job1',
'job2',
'job3',
];
$meterProvider
->getMeter('demo')
->createObservableGauge('queued', 'jobs', 'The number of jobs enqueued (async)')
->observe(static function (ObserverInterface $observer) use ($queue): void {
$observer->observe(count($queue));
});
$reader->collect();
array_pop($queue); //job completed
$reader->collect();
$meterProvider->shutdown();

View File

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/../../vendor/autoload.php';
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\SDK\Common\Export\Stream\StreamTransportFactory;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
/**
* @psalm-suppress InternalMethod
*/
$reader = new ExportingReader(new MetricExporter((new StreamTransportFactory())->create(STDOUT, 'application/x-ndjson'), /*Temporality::CUMULATIVE*/));
$meterProvider = MeterProvider::builder()
->addReader($reader)
->build();
$histogram = $meterProvider->getMeter('io.opentelemetry.contrib.php')->createHistogram('demo');
$histogram->record(50);
$histogram->record(7);
$reader->collect();
$meterProvider->shutdown();

View File

@ -1,22 +0,0 @@
<?php
declare(strict_types=1);
\Prometheus\Storage\Redis::setDefaultOptions(
[
'host' => 'redis',
'port' => 6379,
'password' => null,
'timeout' => 0.1, // in seconds
'read_timeout' => '10', // in seconds
'persistent_connections' => false,
]
);
$registry = \Prometheus\CollectorRegistry::getDefault();
$renderer = new \Prometheus\RenderTextFormat();
$result = $renderer->render($registry->getMetricFamilySamples());
header('Content-type: ' . \Prometheus\RenderTextFormat::MIME_TYPE);
echo $result;

View File

@ -1,20 +0,0 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../vendor/autoload.php';
use Prometheus\Storage\Redis;
Redis::setDefaultOptions(
[
'host' => 'redis',
'port' => 6379,
'password' => null,
'timeout' => 0.1, // in seconds
'read_timeout' => '10', // in seconds
'persistent_connections' => false,
]
);
trigger_error('Prometheus exporter currently not supported', E_USER_WARNING);

View File

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
use OpenTelemetry\API\Metrics\ObserverInterface;
use OpenTelemetry\SDK\Metrics\Data\Temporality;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricExporter\ConsoleMetricExporter;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Resource\ResourceInfoFactory;
require 'vendor/autoload.php';
/**
* Example of using weakly referenced observer callbacks. Binds the lifetime of
* a callback to its bound object, the returned `ObserverCallbackInterface` is
* ignored to automatically detach the callback once the original object is
* garbage collected.
*/
$reader = new ExportingReader(
new ConsoleMetricExporter(Temporality::DELTA)
);
$meterProvider = MeterProvider::builder()
->setResource(ResourceInfoFactory::emptyResource())
->addReader($reader)
->build();
$callback = new class() {
public function __invoke(ObserverInterface $observer)
{
$observer->observe(random_int(1, 10));
}
};
$meterProvider
->getMeter('demo_meter')
->createObservableGauge('number', 'items', 'Random number')
->observe($callback); //weak-ref to callback
$reader->collect(); //metrics (data-points) collected (callback invoked)
unset($callback);
$reader->collect(); //no metrics (data-points) collected, because the callback was garbage-collected due to weak-ref

82
examples/sdk_builder.php Normal file
View File

@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
use OpenTelemetry\API\Instrumentation\CachedInstrumentation;
use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\SDK\Common\Export\Http\PsrTransportFactory;
use OpenTelemetry\SDK\Logs\LoggerProvider;
use OpenTelemetry\SDK\Logs\Processor\SimpleLogRecordProcessor;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Resource\ResourceInfoFactory;
use OpenTelemetry\SDK\Sdk;
use OpenTelemetry\SDK\Trace\Sampler\AlwaysOnSampler;
use OpenTelemetry\SDK\Trace\Sampler\ParentBased;
use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter;
use OpenTelemetry\SDK\Trace\SpanProcessor\BatchSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
require __DIR__ . '/../vendor/autoload.php';
echo 'Starting SDK builder example' . PHP_EOL;
$resource = ResourceInfoFactory::defaultResource();
$spanExporter = new InMemoryExporter();
$logRecordExporter = new \OpenTelemetry\SDK\Logs\Exporter\InMemoryExporter();
$reader = new ExportingReader(
new MetricExporter(
(new PsrTransportFactory())->create('http://collector:4318/v1/metrics', 'application/x-protobuf')
)
);
$meterProvider = MeterProvider::builder()
->setResource($resource)
->addReader($reader)
->build();
$loggerProvider = LoggerProvider::builder()
->addLogRecordProcessor(
new SimpleLogRecordProcessor($logRecordExporter)
)
->build();
$tracerProvider = TracerProvider::builder()
->addSpanProcessor(
BatchSpanProcessor::builder($spanExporter)
->setMeterProvider($meterProvider)
->build()
)
->setResource($resource)
->setSampler(new ParentBased(new AlwaysOnSampler()))
->build();
Sdk::builder()
->setTracerProvider($tracerProvider)
->setMeterProvider($meterProvider)
->setLoggerProvider($loggerProvider)
->setPropagator(TraceContextPropagator::getInstance())
->setAutoShutdown(true)
->buildAndRegisterGlobal();
$instrumentation = new CachedInstrumentation('example');
$tracer = $instrumentation->tracer();
$root = $tracer->spanBuilder('root')->startSpan();
$scope = $root->activate();
for ($i=0; $i < 100; $i++) {
if ($i%8 === 0) {
$reader->collect();
}
$tracer->spanBuilder('span-' . $i)
->startSpan()
->end();
usleep(50000);
}
$scope->detach();
$root->end();
$reader->shutdown();
echo 'Finished SDK builder example' . PHP_EOL;

13
examples/src/Example.php Normal file
View File

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
final class Example
{
public function test(): int
{
return 42;
}
}

View File

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Instrumentation\AutoInstrumentation\InstrumentationConfiguration;
final class ExampleConfig implements InstrumentationConfiguration
{
public function __construct(
public readonly string $spanName = 'example',
public readonly bool $enabled = true,
) {
}
}

View File

@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Configuration\ConfigEnv\EnvComponentLoader;
use OpenTelemetry\API\Configuration\ConfigEnv\EnvComponentLoaderRegistry;
use OpenTelemetry\API\Configuration\ConfigEnv\EnvResolver;
use OpenTelemetry\API\Configuration\Context;
use OpenTelemetry\API\Instrumentation\AutoInstrumentation\InstrumentationConfiguration;
/**
* @implements EnvComponentLoader<InstrumentationConfiguration>
*/
final class ExampleConfigLoader implements EnvComponentLoader
{
#[\Override]
public function load(EnvResolver $env, EnvComponentLoaderRegistry $registry, Context $context): InstrumentationConfiguration
{
return new ExampleConfig(
spanName: $env->string('OTEL_PHP_EXAMPLE_INSTRUMENTATION_SPAN_NAME') ?? 'example',
);
}
#[\Override]
public function name(): string
{
return ExampleConfig::class;
}
}

View File

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Configuration\Config\ComponentProvider;
use OpenTelemetry\API\Configuration\Config\ComponentProviderRegistry;
use OpenTelemetry\API\Configuration\Context;
use OpenTelemetry\API\Instrumentation\AutoInstrumentation\InstrumentationConfiguration;
use OpenTelemetry\Config\SDK\Configuration\Validation;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
/**
* @implements ComponentProvider<InstrumentationConfiguration>
*/
final class ExampleConfigProvider implements ComponentProvider
{
/**
* @psalm-suppress MoreSpecificImplementedParamType
* @param array{
* span_name: string,
* enabled: bool,
* } $properties
*/
#[\Override]
public function createPlugin(array $properties, Context $context): InstrumentationConfiguration
{
return new ExampleConfig(
spanName: $properties['span_name'],
enabled: $properties['enabled'],
);
}
/**
* @psalm-suppress UndefinedInterfaceMethod,PossiblyNullReference
*/
#[\Override]
public function getConfig(ComponentProviderRegistry $registry, NodeBuilder $builder): ArrayNodeDefinition
{
$node = $builder->arrayNode('example_instrumentation');
$node
->children()
->scalarNode('span_name')->isRequired()->validate()->always(Validation::ensureString())->end()->end()
->end()
->canBeDisabled()
;
return $node;
}
}

View File

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Configuration\ConfigProperties;
use OpenTelemetry\API\Instrumentation\AutoInstrumentation\Context as InstrumentationContext;
use OpenTelemetry\API\Instrumentation\AutoInstrumentation\HookManagerInterface;
use OpenTelemetry\API\Instrumentation\AutoInstrumentation\Instrumentation;
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\Context\Context;
final class ExampleInstrumentation implements Instrumentation
{
#[\Override]
public function register(HookManagerInterface $hookManager, ConfigProperties $configuration, InstrumentationContext $context): void
{
$config = $configuration->get(ExampleConfig::class) ?? new ExampleConfig();
if (!$config->enabled) {
return;
}
$tracer = $context->tracerProvider->getTracer('example-instrumentation');
$hookManager->hook(
Example::class,
'test',
static function () use ($tracer, $config): void {
$context = Context::getCurrent();
$span = $tracer
->spanBuilder($config->spanName)
->setParent($context)
->startSpan();
Context::storage()->attach($span->storeInContext($context));
},
static function (): void {
if (!$scope = Context::storage()->scope()) {
return;
}
$scope->detach();
$span = Span::fromContext($scope->context());
$span->end();
}
);
}
}

View File

@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Common\Time\ClockInterface;
use OpenTelemetry\API\Metrics\ObserverInterface;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Common\Instrumentation\InstrumentationScopeFactory;
use OpenTelemetry\SDK\Metrics\Exemplar\ExemplarFilter\WithSampledTraceExemplarFilter;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Metrics\StalenessHandler\ImmediateStalenessHandlerFactory;
use OpenTelemetry\SDK\Metrics\View\CriteriaViewRegistry;
use OpenTelemetry\SDK\Resource\ResourceInfoFactory;
class ExampleMetricsGenerator
{
private ExportingReader $reader;
private ClockInterface $clock;
public function __construct(ExportingReader $reader, ClockInterface $clock)
{
$this->reader = $reader;
$this->clock = $clock;
}
public function generate(): void
{
$meterProvider = new MeterProvider(
null,
ResourceInfoFactory::defaultResource(),
$this->clock,
Attributes::factory(),
new InstrumentationScopeFactory(Attributes::factory()),
[$this->reader],
new CriteriaViewRegistry(),
new WithSampledTraceExemplarFilter(),
new ImmediateStalenessHandlerFactory(),
);
$meter = $meterProvider->getMeter('io.opentelemetry.contrib.php');
$meter
->createObservableUpDownCounter('process.memory.usage', 'By', 'The amount of physical memory in use.')
->observe(static function (ObserverInterface $observer): void {
$observer->observe(memory_get_usage(true));
});
$serverDuration = $meter
->createHistogram('http.server.duration', 'ms', 'measures the duration inbound HTTP requests');
// During the time range (T0, T1]:
$serverDuration->record(50, ['http.method' => 'GET', 'http.status_code' => 200]);
$serverDuration->record(100, ['http.method' => 'GET', 'http.status_code' => 200]);
$serverDuration->record(1, ['http.method' => 'GET', 'http.status_code' => 500]);
$this->reader->collect();
// During the time range (T1, T2]:
$this->reader->collect();
// During the time range (T2, T3]:
$serverDuration->record(5, ['http.method' => 'GET', 'http.status_code' => 500]);
$serverDuration->record(2, ['http.method' => 'GET', 'http.status_code' => 500]);
$this->reader->collect();
// During the time range (T3, T4]:
$serverDuration->record(100, ['http.method' => 'GET', 'http.status_code' => 200]);
$this->reader->collect();
// During the time range (T4, T5]:
$serverDuration->record(100, ['http.method' => 'GET', 'http.status_code' => 200]);
$serverDuration->record(30, ['http.method' => 'GET', 'http.status_code' => 200]);
$serverDuration->record(50, ['http.method' => 'GET', 'http.status_code' => 200]);
$this->reader->collect();
$meterProvider->shutdown();
}
}

View File

@ -4,8 +4,8 @@ receivers:
grpc:
exporters:
logging:
logLevel: debug
debug:
verbosity: detailed
zipkin:
endpoint: "http://zipkin:9411/api/v2/spans"
jaeger:
@ -19,6 +19,6 @@ service:
receivers:
- otlp
exporters:
- logging
- debug
- zipkin
- jaeger

View File

@ -4,7 +4,7 @@ x-otel-common:
OTEL_TRACES_SAMPLER: parentbased_always_on
OTEL_TRACES_EXPORTER: otlp
OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: grpc
OTEL_EXPORTER_OTLP_ENDPOINT: collector:4317
OTEL_EXPORTER_OTLP_ENDPOINT: http://collector:4317
OTEL_PHP_TRACES_PROCESSOR: simple
version: '3.7'
@ -41,7 +41,7 @@ services:
OTEL_SERVICE_NAME: service-three
collector:
image: otel/opentelemetry-collector-contrib:0.39.0
image: otel/opentelemetry-collector-contrib
volumes:
- './collector:/etc/otel'
ports:

View File

@ -22,7 +22,7 @@ use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Routing\RouteContext;
$tracerProvider = (new TracerProviderFactory('example'))->create();
$tracerProvider = (new TracerProviderFactory())->create();
ShutdownHandler::register([$tracerProvider, 'shutdown']);
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');

View File

@ -1,7 +1,10 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\SDK\Trace\SpanDataInterface;
use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter;
@ -9,7 +12,7 @@ use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
// Create an ArrayObject as the storage for the spans
$storage = new ArrayObject();
$storage = new \ArrayObject();
// Boilerplate setup to create a new tracer with an in-memory exporter
$tracerProvider = new TracerProvider(
@ -31,6 +34,7 @@ $childSpan2 = $tracer->spanBuilder('bar')->startSpan();
$childSpan2->end();
$childSpan1->end();
$rootSpan->end();
$rootScope->detach();
/** @var SpanDataInterface $span */
foreach ($storage as $span) {

View File

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\Contrib\Otlp\ContentTypes;
use OpenTelemetry\Contrib\Otlp\SpanExporter;
use OpenTelemetry\SDK\Common\Export\Stream\StreamTransportFactory;
use OpenTelemetry\SDK\Trace\SpanProcessor\BatchSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
$filename = sys_get_temp_dir() . '/traces.jsonl';
$file = fopen($filename, 'a');
if ($file === false) {
throw new \RuntimeException('Failed to open file for writing: ' . $filename);
}
$transport = (new StreamTransportFactory())->create($file, ContentTypes::NDJSON);
$exporter = new SpanExporter($transport);
echo 'Starting OTLP example';
$tracerProvider = new TracerProvider(
new BatchSpanProcessor(
$exporter,
Clock::getDefault()
)
);
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$root = $span = $tracer->spanBuilder('root')->startSpan();
$scope = $span->activate();
for ($i = 0; $i < 3; $i++) {
// start a span, register some events
$span = $tracer->spanBuilder('loop-' . $i)->startSpan();
$span->setAttribute('remote_ip', '1.2.3.4')
->setAttribute('country', 'USA');
$span->addEvent('found_login' . $i, [
'id' => $i,
'username' => 'otuser' . $i,
]);
$span->addEvent('generated_session', [
'id' => md5((string) microtime(true)),
]);
$span->end();
}
$root->end();
$scope->detach();
echo PHP_EOL . 'OTLP example complete! Traces written to: ' . $filename;
echo PHP_EOL;
$tracerProvider->shutdown();

View File

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Instrumentation\CachedInstrumentation;
putenv('OTEL_PHP_AUTOLOAD_ENABLED=true');
putenv('OTEL_TRACES_EXPORTER=otlp/stdout');
putenv('OTEL_LOGS_EXPORTER=otlp/stdout');
putenv('OTEL_METRICS_EXPORTER=otlp/stdout');
require __DIR__ . '/../../../vendor/autoload.php';
$instrumentation = new CachedInstrumentation('demo');
$instrumentation->tracer()->spanBuilder('root')->startSpan()->end();
$instrumentation->meter()->createCounter('cnt')->add(1);
$instrumentation->eventLogger()->emit('foo', 'hello, otel');
echo PHP_EOL . 'OTLP/stdout autoload example complete!';
echo PHP_EOL;

View File

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\SDK\Trace\TracerProviderFactory;
putenv('OTEL_TRACES_EXPORTER=otlp/stdout');
$factory = new TracerProviderFactory();
$tracerProvider = $factory->create();
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$root = $span = $tracer->spanBuilder('root')->startSpan();
$scope = $span->activate();
for ($i = 0; $i < 3; $i++) {
// start a span, register some events
$span = $tracer->spanBuilder('loop-' . $i)->startSpan();
$span->setAttribute('remote_ip', '1.2.3.4')
->setAttribute('country', 'USA');
$span->addEvent('found_login' . $i, [
'id' => $i,
'username' => 'otuser' . $i,
]);
$span->addEvent('generated_session', [
'id' => md5((string) microtime(true)),
]);
$span->end();
}
$root->end();
$scope->detach();
echo PHP_EOL . 'OTLP/stdout example complete!';
echo PHP_EOL;
$tracerProvider->shutdown();

View File

@ -1,14 +1,20 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
use OpenTelemetry\Contrib\OtlpGrpc\Exporter as OTLPGrpcExporter;
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\API\Signals;
use OpenTelemetry\Contrib\Grpc\GrpcTransportFactory;
use OpenTelemetry\Contrib\Otlp\OtlpUtil;
use OpenTelemetry\Contrib\Otlp\SpanExporter;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
$exporter = new OTLPGrpcExporter('collector:4317');
$transport = (new GrpcTransportFactory())->create('http://collector:4317' . OtlpUtil::method(Signals::TRACE));
$exporter = new SpanExporter($transport);
echo 'Starting OTLP GRPC example';
$tracerProvider = new TracerProvider(
@ -19,7 +25,7 @@ $tracerProvider = new TracerProvider(
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$root = $span = $tracer->spanBuilder('root')->startSpan();
$span->activate();
$scope = $span->activate();
for ($i = 0; $i < 3; $i++) {
// start a span, register some events
@ -39,6 +45,7 @@ for ($i = 0; $i < 3; $i++) {
$span->end();
}
$root->end();
$scope->detach();
echo PHP_EOL . 'OTLP GRPC example complete! ';
echo PHP_EOL;

View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\SDK\Trace\TracerProviderFactory;
require __DIR__ . '/../../../vendor/autoload.php';
/**
* Create an otlp+grpc tracer provider from TracerProviderFactory, using environment variables as input
*/
putenv('OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317');
putenv('OTEL_EXPORTER_OTLP_PROTOCOL=grpc');
$factory = new TracerProviderFactory();
$tracerProvider = $factory->create();
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$root = $span = $tracer->spanBuilder('root')->startSpan();
$root->end();
echo PHP_EOL . 'OTLP GRPC example complete! ';
echo PHP_EOL;
$tracerProvider->shutdown();

View File

@ -1,20 +1,18 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use OpenTelemetry\Contrib\OtlpHttp\Exporter as OTLPExporter;
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\Contrib\Otlp\OtlpHttpTransportFactory;
use OpenTelemetry\Contrib\Otlp\SpanExporter;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
putenv('OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318/v1/traces');
$exporter = new OTLPExporter(
new Client(),
new HttpFactory(),
new HttpFactory()
);
$transport = (new OtlpHttpTransportFactory())->create('http://collector:4318/v1/traces', 'application/x-protobuf');
$exporter = new SpanExporter($transport);
echo 'Starting OTLP example';
@ -26,7 +24,7 @@ $tracerProvider = new TracerProvider(
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$root = $span = $tracer->spanBuilder('root')->startSpan();
$span->activate();
$scope = $span->activate();
for ($i = 0; $i < 3; $i++) {
// start a span, register some events
@ -46,6 +44,7 @@ for ($i = 0; $i < 3; $i++) {
$span->end();
}
$root->end();
$scope->detach();
echo PHP_EOL . 'OTLP example complete! ';
echo PHP_EOL;

View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
/**
* Create an otlp+http/protobuf tracer provider from TracerProviderFactory, using environment variables as input
*/
putenv('OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318');
putenv('OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf');
putenv('OTEL_EXPORTER_OTLP_TIMEOUT=1500'); //1.5s
$factory = new \OpenTelemetry\SDK\Trace\TracerProviderFactory();
$tracerProvider = $factory->create();
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$tracer->spanBuilder('root')->startSpan()->end();
echo PHP_EOL . 'OTLP http/protobuf example complete! ';
echo PHP_EOL;
$tracerProvider->shutdown();

View File

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\Contrib\Otlp\ContentTypes;
use OpenTelemetry\Contrib\Otlp\OtlpHttpTransportFactory;
use OpenTelemetry\Contrib\Otlp\SpanExporter;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
$transport = (new OtlpHttpTransportFactory())->create('http://collector:4318/v1/traces', ContentTypes::JSON);
$exporter = new SpanExporter($transport);
echo 'Starting OTLP+json example';
$tracerProvider = new TracerProvider(
new SimpleSpanProcessor(
$exporter
)
);
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$root = $span = $tracer->spanBuilder('root')->startSpan();
$root->end();
echo PHP_EOL . 'OTLP+json example complete! ';
echo PHP_EOL;
$tracerProvider->shutdown();

View File

@ -1,20 +1,19 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\Contrib\Zipkin\Exporter as ZipkinExporter;
use OpenTelemetry\SDK\Common\Export\Http\PsrTransportFactory;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
$transport = (new PsrTransportFactory())->create('http://zipkin:9411/api/v2/spans', 'application/json');
$zipkinExporter = new ZipkinExporter(
'alwaysOnZipkinExample',
'http://zipkin:9411/api/v2/spans',
new Client(),
new HttpFactory(),
new HttpFactory()
$transport
);
$tracerProvider = new TracerProvider(
new SimpleSpanProcessor(
@ -26,7 +25,7 @@ $tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
echo 'Starting Zipkin example';
$root = $span = $tracer->spanBuilder('root')->startSpan();
$span->activate();
$scope = $span->activate();
for ($i = 0; $i < 3; $i++) {
// start a span, register some events
@ -45,6 +44,7 @@ for ($i = 0; $i < 3; $i++) {
$span->end();
}
$scope->detach();
$root->end();
echo PHP_EOL . 'Zipkin example complete! See the results at http://localhost:9411/';

View File

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Logs\LogRecord;
putenv('OTEL_PHP_AUTOLOAD_ENABLED=true');
putenv('OTEL_TRACES_EXPORTER=console');
putenv('OTEL_METRICS_EXPORTER=none');
putenv('OTEL_LOGS_EXPORTER=console');
putenv('OTEL_PROPAGATORS=tracecontext');
putenv('OTEL_PHP_EXPERIMENTAL_AUTO_ROOT_SPAN=true');
//Usage: php -S localhost:8080 examples/traces/features/auto_root_span.php
require dirname(__DIR__, 3) . '/vendor/autoload.php';
Globals::loggerProvider()->getLogger('test')->emit(new LogRecord('I processed a request'));
echo 'hello world!' . PHP_EOL;

View File

@ -1,9 +1,13 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\SDK\Trace\SpanExporter\ConsoleSpanExporter;
use OpenTelemetry\API\Common\Time\Clock;
use OpenTelemetry\SDK\Trace\SpanExporter\ConsoleSpanExporterFactory;
use OpenTelemetry\SDK\Trace\SpanProcessor\BatchSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
@ -14,8 +18,8 @@ echo sprintf('Sending batches every %dms and on shutdown', $delayMillis) . PHP_E
$tracerProvider = new TracerProvider(
new BatchSpanProcessor(
new ConsoleSpanExporter(),
null,
(new ConsoleSpanExporterFactory())->create(),
Clock::getDefault(),
2048, //max spans to queue before sending to exporter
$delayMillis, //batch delay milliseconds
)

View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
use OpenTelemetry\API\Globals;
putenv('OTEL_PHP_AUTOLOAD_ENABLED=true');
putenv('OTEL_TRACES_EXPORTER=console');
putenv('OTEL_METRICS_EXPORTER=console');
putenv('OTEL_PHP_INTERNAL_METRICS_ENABLED=true');
require __DIR__ . '/../../../vendor/autoload.php';
/**
* Demonstrates batch span processing which also emits metrics for the internal state
* of the processor (eg spans received, queue length)
*/
echo 'Starting ConsoleSpanExporter with BatchSpanProcessor and metrics' . PHP_EOL;
$tracer = Globals::tracerProvider()->getTracer('io.opentelemetry.contrib.php');
$tracer->spanBuilder('root')->startSpan()->end();
echo PHP_EOL . 'Example complete! ' . PHP_EOL;

View File

@ -1,9 +1,12 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\SDK\Trace\SpanExporter\ConsoleSpanExporter;
use OpenTelemetry\SDK\Trace\SpanExporter\ConsoleSpanExporterFactory;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
@ -15,7 +18,7 @@ echo 'Starting ConsoleSpanExporter' . PHP_EOL;
$tracerProvider = new TracerProvider(
new SimpleSpanProcessor(
new ConsoleSpanExporter()
(new ConsoleSpanExporterFactory())->create()
)
);
@ -36,6 +39,7 @@ try {
->setAttribute('http.response_content_length', 1024)
->startSpan();
}
/** @psalm-suppress ArgumentTypeCoercion */
foreach ($spans as $span) {
usleep((int) (0.3 * 1e6));
$span->end();

View File

@ -1,23 +1,28 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\SDK\Trace\TracerProviderFactory;
//@see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/sdk-environment-variables.md
//@see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md
putenv('OTEL_RESOURCE_ATTRIBUTES=service.version=1.0.0');
putenv('OTEL_SERVICE_NAME=example-app');
putenv('OTEL_LOG_LEVEL=warning');
putenv('OTEL_TRACES_SAMPLER=traceidratio');
putenv('OTEL_TRACES_SAMPLER_ARG=0.95');
putenv('OTEL_TRACES_EXPORTER=console');
putenv('OTEL_TRACES_EXPORTER=otlp');
putenv('OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318');
putenv('OTEL_EXPORTER_OTLP_PROTOCOL=http/json');
putenv('OTEL_PHP_TRACES_PROCESSOR=batch');
putenv('OTEL_BSP_SCHEDULE_DELAY=10000');
echo 'Creating Exporter From Environment' . PHP_EOL;
$tracerProvider = (new TracerProviderFactory('example'))->create();
$tracerProvider = (new TracerProviderFactory())->create();
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');

View File

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
require 'vendor/autoload.php';
use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;
use OpenTelemetry\Context\Propagation\EnvironmentGetterSetter;
use OpenTelemetry\SDK\Trace\SpanExporter\ConsoleSpanExporterFactory;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
$tracerProvider = new TracerProvider(
new SimpleSpanProcessor(
(new ConsoleSpanExporterFactory())->create()
)
);
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$propagator = TraceContextPropagator::getInstance();
$envGetterSetter = EnvironmentGetterSetter::getInstance();
$isChild = isset($argv[1]) && $argv[1] === 'child';
if (!$isChild) {
$span = $tracer->spanBuilder('root')->startSpan();
$scope = $span->activate();
// Inject trace context into environment variables
$carrier = [];
$propagator->inject($carrier, $envGetterSetter);
// Execute child process
$command = sprintf('%s %s %s', PHP_BINARY, escapeshellarg(__FILE__), 'child');
$handle = popen($command, 'w');
if ($handle === false) {
echo 'Failed to execute child process.' . PHP_EOL;
} else {
pclose($handle);
}
$scope->detach();
$span->end();
} else {
// Extract trace context from environment variables
$context = $propagator->extract([], $envGetterSetter);
$scope = $context->activate();
// Start child span with parent context
$span = $tracer->spanBuilder('child-span')->setParent($context)->startSpan();
$spanContext = $span->getContext();
$scope->detach();
$span->end();
}
$tracerProvider->shutdown();

View File

@ -1,16 +1,19 @@
<?php
declare(strict_types=1);
namespace OpenTelemetry\Example;
require __DIR__ . '/../../../vendor/autoload.php';
use OpenTelemetry\SDK\Trace\SpanExporter\ConsoleSpanExporter;
use OpenTelemetry\SDK\Trace\SpanExporter\ConsoleSpanExporterFactory;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
// Boilerplate setup to create a new tracer with console output
$tracerProvider = new TracerProvider(
new SimpleSpanProcessor(
new ConsoleSpanExporter()
(new ConsoleSpanExporterFactory())->create()
)
);
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');

View File

@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
use OpenTelemetry\Contrib\Jaeger\Exporter as JaegerExporter;
use OpenTelemetry\SDK\Trace\Sampler\AlwaysOnSampler;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
$exporter = JaegerExporter::fromConnectionString('http://jaeger:9412/api/v2/spans', 'AlwaysOnJaegerExample');
$tracerProvider = new TracerProvider(
new SimpleSpanProcessor($exporter),
new AlwaysOnSampler(),
);
echo 'Starting Jaeger example';
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$rootSpan = $tracer->spanBuilder('root')->startSpan();
$rootSpan->activate();
for ($i = 0; $i < 5; $i++) {
// start a span, register some events
$span = $tracer->spanBuilder('session.generate.span-' . $i)->startSpan();
echo sprintf(
PHP_EOL . 'Exporting Trace: %s, Parent: %s, Span: %s',
$span->getContext()->getTraceId(),
$span->getParentContext()->getSpanId() ?: 'None',
$span->getContext()->getSpanId()
);
$span->setAttribute('remote_ip', '1.2.3.4')
->setAttribute('country', 'USA');
$span->addEvent('found_login' . $i, [
'id' => $i,
'username' => 'otuser' . $i,
]);
$span->addEvent('generated_session', [
'id' => md5((string) microtime(true)),
]);
try {
throw new Exception('Record exception test event');
} catch (Exception $exception) {
$span->recordException($exception);
}
$span->end();
}
$rootSpan->end();
echo PHP_EOL . 'Jaeger example complete! See the results at http://localhost:16686/';
echo PHP_EOL;
$tracerProvider->shutdown();

View File

@ -1,72 +0,0 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use OpenTelemetry\Contrib\Jaeger\AgentExporter;
use OpenTelemetry\SDK\Common\Log\LoggerHolder;
use OpenTelemetry\SDK\Trace\Sampler\AlwaysOnSampler;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
use Psr\Log\LogLevel;
$logger = new Logger('otel-php', [new StreamHandler(STDOUT, LogLevel::DEBUG)]);
LoggerHolder::set($logger);
$exporter = new AgentExporter('jaeger-thrift', 'jaeger:6831');
$tracerProvider = new TracerProvider(
new SimpleSpanProcessor($exporter),
new AlwaysOnSampler(),
);
echo 'Starting Jaeger Thrift example';
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$rootSpan = $tracer->spanBuilder('root')->startSpan();
$rootSpan->activate();
echo PHP_EOL . sprintf(
'Root Span: %s, Parent: %s, Span: %s',
$rootSpan->getContext()->getTraceId(),
$rootSpan->getParentContext()->getSpanId(),
$rootSpan->getContext()->getSpanId()
) . PHP_EOL;
for ($i = 0; $i < 1; $i++) {
// start a span, register some events
$span = $tracer->spanBuilder('session.generate.span-' . $i)->startSpan();
echo sprintf(
PHP_EOL . 'Exporting Trace: %s, Parent: %s, Span: %s',
$span->getContext()->getTraceId(),
$span->getParentContext()->getSpanId() ?: 'None',
$span->getContext()->getSpanId()
) . PHP_EOL;
$span->setAttribute('remote_ip', '1.2.3.4')
->setAttribute('country', 'USA');
$span->addEvent('found_login' . $i, [
'id' => $i,
'username' => 'otuser' . $i,
]);
$span->addEvent('generated_session', [
'id' => md5((string) microtime(true)),
]);
try {
throw new Exception('Record exception test event');
} catch (Exception $exception) {
$span->recordException($exception);
}
$span->end();
}
$rootSpan->end();
echo PHP_EOL . 'Jaeger Thrift example complete! See the results at http://localhost:16686/';
echo PHP_EOL;
$tracerProvider->shutdown();

View File

@ -1,81 +0,0 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use OpenTelemetry\Contrib\Newrelic\Exporter as NewrelicExporter;
use OpenTelemetry\SDK\Common\Time\ClockFactory;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
/*
* Experimental example to send trace data to New Relic.
* It will send PHP Otel trace data end to end across the internet to a functional backend.
* Needs a license key to connect. For a free account/key, go to: https://newrelic.com/signup/
*/
$licenseKey = getenv('NEW_RELIC_INSERT_KEY');
// Needs a license key in the environment to connect to the backend server.
if ($licenseKey == false) {
echo PHP_EOL . 'NEW_RELIC_INSERT_KEY not found in environment. Newrelic Example tracing is not enabled.';
return;
}
/*
* Default Trace API endpoint: https://trace-api.newrelic.com/trace/v1
* EU data centers: https://trace-api.eu.newrelic.com/trace/v1
*/
$endpointUrl = getenv('NEW_RELIC_ENDPOINT');
if ($endpointUrl == false) {
$endpointUrl = 'https://trace-api.newrelic.com/trace/v1';
}
$newrelicExporter = new NewrelicExporter(
'alwaysOnNewrelicExample',
$endpointUrl,
$licenseKey,
new Client(),
new HttpFactory(),
new HttpFactory()
);
echo 'Starting Newrelic example';
$tracerProvider = new TracerProvider(new SimpleSpanProcessor($newrelicExporter));
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
for ($i = 0; $i < 5; $i++) {
// start a span, register some events
$timestamp = ClockFactory::getDefault()->now();
$span = $tracer->spanBuilder('session.generate.span.' . microtime(true))->startSpan();
echo sprintf(
PHP_EOL . 'Exporting Trace: %s, Span: %s',
$span->getContext()->getTraceId(),
$span->getContext()->getSpanId()
);
$span->setAttribute('remote_ip', '1.2.3.4')
->setAttribute('country', 'USA');
$span->addEvent('found_login' . $i, [
'id' => $i,
'username' => 'otuser' . $i,
], $timestamp);
$span->addEvent('generated_session', [
'id' => md5((string) microtime(true)),
], $timestamp);
$span->end();
}
echo PHP_EOL . 'Newrelic example complete! See the results at https://one.newrelic.com/launcher/distributed-tracing.launcher?pane=eyJuZXJkbGV0SWQiOiJkaXN0cmlidXRlZC10cmFjaW5nLmhvbWUiLCJzb3J0SW5kZXgiOjAsInNvcnREaXJlY3Rpb24iOiJERVNDIiwicXVlcnkiOnsib3BlcmF0b3IiOiJBTkQiLCJpbmRleFF1ZXJ5Ijp7ImNvbmRpdGlvblR5cGUiOiJJTkRFWCIsIm9wZXJhdG9yIjoiQU5EIiwiY29uZGl0aW9uU2V0cyI6W119LCJzcGFuUXVlcnkiOnsib3BlcmF0b3IiOiJBTkQiLCJjb25kaXRpb25TZXRzIjpbeyJjb25kaXRpb25UeXBlIjoiU1BBTiIsIm9wZXJhdG9yIjoiQU5EIiwiY29uZGl0aW9ucyI6W3siYXR0ciI6InNlcnZpY2UubmFtZSIsIm9wZXJhdG9yIjoiRVEiLCJ2YWx1ZSI6ImFsd2F5c09uTmV3cmVsaWNFeGFtcGxlIn1dfV19fX0=&platform[timeRange][duration]=1800000&platform[$isFallbackTimeRange]=true';
echo PHP_EOL;
$tracerProvider->shutdown();

View File

@ -1,59 +0,0 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../../../../vendor/autoload.php';
use OpenTelemetry\Context\Context;
use OpenTelemetry\Contrib\OtlpGrpc\Exporter as OTLPExporter;
use OpenTelemetry\SDK\Common\Time\ClockFactory;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
$Exporter = new OTLPExporter();
echo 'Starting OTLPGrpc example 1';
$tracerProvider = new TracerProvider(new SimpleSpanProcessor($Exporter));
$tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
for ($i = 0; $i < 5; $i++) {
// start a span, register some events
$timestamp = ClockFactory::getDefault()->now();
$span = $tracer->spanBuilder('session.generate.span' . microtime(true))->startSpan();
//startAndActivateSpan('session.generate.span.' . microtime(true));
$childSpan = $tracer
->spanBuilder('child')
->setParent($span->storeInContext(Context::getCurrent()))
->startSpan();
// Temporarily setting service name here. It should eventually be pulled from tracer.resources.
$span->setAttribute('service.name', 'alwaysOnOTLPGrpcExample');
$span->setAttribute('remote_ip', '1.2.3.4')
->setAttribute('country', 'USA');
$span->addEvent('found_login' . $i, [
'id' => $i,
'username' => 'otuser' . $i,
], $timestamp);
$span->addEvent('generated_session', [
'id' => md5((string) microtime(true)),
], $timestamp);
// temporarily setting service name here. It should eventually be pulled from tracer.resources.
$childSpan->setAttribute('service.name', 'alwaysOnOTLPGrpcExample');
$childSpan->setAttribute('attr_one', 'one')
->setAttribute('attr_two', 'two');
$childSpan->addEvent('found_event1' . $i, [
'id' => $i,
'username' => 'child' . $i,
], $timestamp);
$childSpan->end();
$span->end();
}
echo PHP_EOL . 'OTLPGrpc example 1 complete! ';
echo PHP_EOL;
$tracerProvider->shutdown();

Some files were not shown because too many files have changed in this diff Show More