{"id":19330332,"url":"https://github.com/larttyler/prometheus-client","last_synced_at":"2025-04-22T23:31:20.211Z","repository":{"id":56963970,"uuid":"173376893","full_name":"LartTyler/prometheus-client","owner":"LartTyler","description":"A client library for the Prometheus monitoring system","archived":false,"fork":false,"pushed_at":"2024-08-05T17:06:31.000Z","size":89,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-11-07T06:48:18.264Z","etag":null,"topics":["client","php","prometheus"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/LartTyler.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-03-01T22:35:03.000Z","updated_at":"2024-08-05T17:06:34.000Z","dependencies_parsed_at":"2022-08-21T05:40:29.660Z","dependency_job_id":null,"html_url":"https://github.com/LartTyler/prometheus-client","commit_stats":null,"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LartTyler%2Fprometheus-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LartTyler%2Fprometheus-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LartTyler%2Fprometheus-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LartTyler%2Fprometheus-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/LartTyler","download_url":"https://codeload.github.com/LartTyler/prometheus-client/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223906499,"owners_count":17223046,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["client","php","prometheus"],"created_at":"2024-11-10T02:35:57.551Z","updated_at":"2024-11-10T02:35:59.225Z","avatar_url":"https://github.com/LartTyler.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"## Installation\nRun the following command in your project root.\n\n```shell\n$ composer require dbstudios/prometheus-client\n```\n\n## Getting Started\nThere are two components that you'll need to set up in order to start using this library. The first is the\n`CollectorRegistry`, which acts as a repository for your collectors. There isn't any special configuration to worry\nabout, all you need is an instance you can can access anywhere in your application.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\CollectorRegistry;\n    \n    $registry = new CollectorRegistry();\n```\n\nNext up is an adapter, which acts as an interface between the library code, and your chosen storage system. At the time\nof writing, this library ships with support for the following adapters.\n\n- [Redis](#redis)\n- [Filesystem](#filesystem)\n- [APCu](#apcu)\n\nInstantiation will vary from adapter to adapter, so please check the [documentation for the adapter](#adapters) you're\nusing.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Adapter\\Apcu\\ApcuAdapter;\n    \n    $adapter = new ApcuAdapter();\n```\n\nAnd finally, you'll need one or more collectors.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Collector\\Counter;\n    use DaybreakStudios\\PrometheusClient\\Collector\\Gauge;\n    use DaybreakStudios\\PrometheusClient\\Collector\\Histogram;\n    \n    $counter = new Counter($adapter, 'test_counter', 'Please ignore');\n    $registry-\u003eregister($counter);\n    \n    $gauge = new Gauge($adapter, 'test_gauge', 'Please ignore');\n    $registry-\u003eregister($gauge);\n    \n    $histogram = new Histogram($adapter, 'test_histogram', 'Please ignore', [\n    \t1,\n    \t5,\n    \t15,\n    \t50,\n    \t100\n    ]);\n    \n    $registry-\u003eregister($histogram);\n```\n\nOnce a collector is registered, you can either expose them as global variables, or by name via the `CollectorRegistry`\n(which needs to be globally accessible in some way).\n\n```php\n\u003c?php\n    $testCounter = $registry-\u003eget('test_counter');\n    $testCounter-\u003eincrement();\n    \n    $testHistogram = $registry-\u003eget('test_histogram');\n    $testHistogram-\u003eobserve(153);\n```\n\n## \"Strong\" Typing\nTo help enforce types when retrieving collectors from the registry, you can use the `getCounter()`, `getGauge()`, and\n`getHistogram()` methods in place of the basic `get()` method.\n\n```php\n\u003c?php\n    $counter = $registry-\u003egetCounter('test_counter');\n    $counter-\u003eincrement();\n    \n    $histogram = $registry-\u003egetHistogram('test_gauge');\n    // throws DaybreakStudios\\PrometheusClient\\Exception\\CollectorRegistryException due to type mismatch\n```\n\nIn addition to performing the same `null` checking that `get()` performs, each of those methods will also check that the\ncollector is of the expected type, and throw an exception if the collector is not. They'll also correctly enable IDE\nautocompletion, since those three methods specify the proper return type in their PHPDoc block.\n\n## Using Labels\nYou must define all of a collector's labels when its registered.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Collector\\Counter;\n    \n    $counter = new Counter($adapter, 'api_calls_total', 'Number of API calls made', [\n        'path',\n        'method',  \t\n    ]);\n    \n    $counter-\u003eincrement([\n    \t'method' =\u003e 'GET',\n    \t'path' =\u003e '/users/me',\n    ]);\n```\n\nThe order in which you specify the labels when using the collector (i.e. in `Counter::increment()` in the example above)\ndoes not matter, however ALL label values must be provided each time. \n\n## Exporting\nYou can export data from your registry by setting up an endpoint in your application with code similar to the code\nbelow.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Export\\Render\\TextRenderer;\n    \n    $renderer = new TextRenderer();\n    \n    header('Content-Type: ' . $renderer-\u003egetMimeType());\n    echo $renderer-\u003erender($registry-\u003ecollect());\n```\n\n## Collectors\nCollectors are the interface between your code and Prometheus. The Prometheus spec currently defines 3 supported\ncollector types, which are documented below.\n\nFor more information on the concepts of collectors, please refer to the\n[official Prometheus documentation](https://prometheus.io/docs/concepts/metric_types/).\n\n### Counters\nCounters are the simplest form of collector. The official Prometheus documentation describes counters like so.\n\n\u003e A _counter_ is a cumulative metric that represents a single\n\u003e [monotonically increasing counter](https://en.wikipedia.org/wiki/Monotonic_function) whose value can only increase or\n\u003e be reset to zero on restart.\n\nBasically, a counter is a collector that can only increase, usually by increments of one. For example, you might use it\nto track the number of requests an application has served, or the number of database queries an application has\nexecuted.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Collector\\Counter;\n\n    /**\n     * @var \\DaybreakStudios\\PrometheusClient\\Adapter\\AdapterInterface $adapter \n     */\n    $counter = new Counter($adapter, 'requests_served', 'The number of requests processed by the application');\n\n    $counter-\u003eincrement();\n    $counter-\u003eincrement([], 3);\n```\n\nAll arguments to `Counter::increment()` are optional. The first argument is the [labels](#using-labels) to use for\nthe counter being incremented. The second argument is the step for the increment (defaults to one).\n\n### Gauges\nA gauge is very similar to a [counter](#counters). However, unlike counters, they can increase or decrease, and can\neven have their current value set to a specific number. The official Prometheus documentation describes gauges like so.\n\n\u003e A _gauge_ is a metric that represents a single numerical value that can arbitrarily go up and down.\n\nA gauge is useful for tracking things like temperature, or CPU or memory usage.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Collector\\Gauge;\n\n    /**\n     * @var \\DaybreakStudios\\PrometheusClient\\Adapter\\AdapterInterface $adapter\n     */\n    $gauge = new Gauge($adapter, 'cpu_usage_last5', 'CPU usage average over the last 5 minutes');\n\n    $gauge-\u003eincrement();\n    $gauge-\u003edecrement();\n    $gauge-\u003eset(1.7);\n```\n\nMuch like a [counter](#counters), the arguments to `Gauge::increment()` and `Gauge::decrement()` are optional. Both\naccept up to two arguments: labels and the step, in that order.\n\nYou can use `Gauge::set()` to update the gauge to a specific value. It accepts one or two arguments, the first being\nthe required value to set the gauge to, and the second optional value being the labels for the gauge.\n\n### Histograms\nA histogram is (compared to [counters](#counters) and [gauges](#gauges)) a relatively complex collector. The official\nPrometheus documentation describes histograms like so.\n\n\u003e A _histogram_ samples observations (usually things like request durations or response sizes) and counts them in\n\u003e configurable buckets. It also provides a sum of all observed values.\n\nHistograms can be useful when you're dealing with a metric that might vary wildly each time it's recorded, and can be\nused to separate the recorded metrics into quantiles for easier analysis. For example, a histogram may be useful in\nanalyzing execution times for different code paths, and recording data in a way that outliers can be easily identified\n(such as that one particularly slow piece of code that _you can't make run any faster no matter how many hundreds of\nhours you throw at it_).\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Collector\\Histogram;\n   \n    /**\n     * @var \\DaybreakStudios\\PrometheusClient\\Adapter\\AdapterInterface $adapter\n     */\n    $histogram = new Histogram(\n        $adapter,\n        'api_call_execution_time_milliseconds',\n        'Call time to external API',\n        [50, 1000, 5000]\n    );\n\n    $histogram-\u003eobserve(17);\n    $histogram-\u003eobserve(120);\n    $histogram-\u003eobserve(2700);\n    $histogram-\u003eobserve(7010);\n```\n\nSince histograms are often used for timing, there are two built-in utility methods for working with time. Please note\nthat you will need to install the [`symfony/stopwatch`](https://symfony.com/doc/current/components/stopwatch.html)\ncomponent in order to use timing features.\n\n```php\n\u003c?php\n    /**\n     * @var \\DaybreakStudios\\PrometheusClient\\Collector\\Histogram $histogram\n     */\n\n    $timer = $histogram-\u003estartTimer();\n    usleep(10000); // ~10 ms\n    $timer-\u003eobserve(); // Tracks time since Histogram::startTime() was invoked and adds it to the histogram\n\n    $histogram-\u003etime(function() {\n        usleep(100000); // ~100 ms\n    }); // Invokes the callable passed to Histogram::time() and adds the execution time as a value of the histogram\n```\n\nBy default, histograms track time with millisecond precision. However, a histogram accepts an optional constructor\nargument to change this to second precision, if that's better suited for your needs.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Collector\\Histogram;\n    use DaybreakStudios\\PrometheusClient\\Collector\\HistogramTimer;\n\n    /**\n     * @var \\DaybreakStudios\\PrometheusClient\\Adapter\\AdapterInterface $adapter\n     */\n    $histogram = new Histogram(\n        $adapter,\n        'api_call_execution_time_seconds',\n        'Call time to external API',\n        [100, 1000, 5000],\n        [],\n        HistogramTimer::PRECISION_SECONDS,\n    );\n\n    $histogram-\u003etime(function() {\n        usleep(1100000); // ~1100 ms or 1.1 s\n    }); // Adds 1 to the histogram (e.g. `$histogram-\u003eobserve(1)`)\n```\n\n## Adapters\nThis library provides access to the underlying storage system via adapters. The built-in adapters are documented below.\n\n### Redis\nThe `DaybreakStudios\\PrometheusClient\\Adapter\\Redis\\RedisAdapter` uses Redis to store metrics. To use the Redis adapter,\nyou simply need to provide it with the host of the Redis instance.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Adapter\\Redis\\RedisAdapter;\n    use DaybreakStudios\\PrometheusClient\\Adapter\\Redis\\RedisClientConfiguration;\n\n    $config = new RedisClientConfiguration('localhost');\n    \n    // You can also supply other information, such as port or password, using the setters\n    // available on the configuration object, e.g.:\n    //     - $config-\u003esetPort(1234)\n    //     - $config-\u003esetPassword('MyTotallySecurePassword')\n\n    $adapter = new RedisAdapter($config);\n```\n\nKeys in the Redis adapter are automatically prefixed in order to prevent collisions with other keys that might be in\nyour Redis instance. By default, the prefix is \"dbstudios_prom:\", but you can change this by providing a second argument\nto the constructor of `RedisClientConfiguration`.\n\n### Filesystem\nThe `DaybreakStudios\\PrometheusClient\\Adapter\\Filesystem\\FilesystemAdapter` uses files to store metrics. Data written to\nthe adapter's files is encoded using PHP's [`serialize()`](http://php.net/manual/en/function.serialize.php) function, so\ntypes will be properly preserved. To use the `FilesystemAdapter`, you will need to specify which directory the adapter\nshould use to store it's files. In order to prevent data loss, the directory you specify should _only_ be used by\nPrometheus.\n\n```php\n\u003c?php\n    use DaybreakStudios\\PrometheusClient\\Adapter\\Filesystem\\FilesystemAdapter;\n    \n    $adapter = new FilesystemAdapter('/var/www/html/prometheus');\n```\n\nUnlike the [APCu adapter](#apcu), cached data will persist, even if your server reboots. You can use the\n`FilesystemAdapter::clear()` method to remove all files from the adapter's cache. Please keep in mind that this will\ndelete _everything_ in the directory you specified as the adapter's base directory.\n\n### APCu\nThe `DaybreakStudios\\PrometheusClient\\Adapter\\Apcu\\ApcuAdapter` uses [APCu](http://php.net/manual/en/book.apcu.php) to\nstore metrics. The APCU adapter uses no additional configuration.\n\nThere are a few pitfalls to be aware of, however. APCu, by default, does not persist stored data through certain events,\nsuch as a server reboot. Additionally, it also wipes its entire cache once the cache fills up. Neither of those\nshould cause problems for your Prometheus installation, but it's something you should keep in mind if you choose to use\nthe APCu adapter.\n\nAdditionally, APCu _does not_ properly support accessing its cache for PHP sessions started from the command line.\nUnder a default configuration, every call to an `apcu_*` function is \"black holed\", meaning that they'll always return\n`false`, and will not store any data in the cache. You can enable the CLI cache by adding `apc.enable_cli=1` to your\n`php.ini`, but that will only keep information in the cache for the run time of the script. Once the script is done\nexecuting, the cache data will be purged. As far as I'm aware, _there is no way to alter this behavior_.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flarttyler%2Fprometheus-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flarttyler%2Fprometheus-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flarttyler%2Fprometheus-client/lists"}