pax_global_header 0000666 0000000 0000000 00000000064 14301147710 0014510 g ustar 00root root 0000000 0000000 52 comment=0cf38e85047d0ac1d2051007280c6bcdc159530e
prom-client-14.1.0/ 0000775 0000000 0000000 00000000000 14301147710 0014024 5 ustar 00root root 0000000 0000000 prom-client-14.1.0/.editorconfig 0000664 0000000 0000000 00000000234 14301147710 0016500 0 ustar 00root root 0000000 0000000 ; http://editorconfig.org
root = true
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
prom-client-14.1.0/.eslintignore 0000664 0000000 0000000 00000000012 14301147710 0016520 0 ustar 00root root 0000000 0000000 coverage/
prom-client-14.1.0/.eslintrc 0000664 0000000 0000000 00000003062 14301147710 0015651 0 ustar 00root root 0000000 0000000 {
"plugins": ["prettier"],
"extends": [
"eslint:recommended",
"plugin:node/recommended",
"plugin:prettier/recommended"
],
"env": {
"node": true,
"es6": true
},
"parserOptions": {
"ecmaVersion": 2019
},
"rules": {
"no-underscore-dangle": "off",
"no-mixed-requires": "off",
"new-cap": "off",
"no-path-concat": "off",
"no-shadow": "warn",
"no-array-constructor": "error",
"no-caller": "error",
"no-eval": "error",
"no-extend-native": "error",
"no-extra-bind": "error",
"no-with": "error",
"no-loop-func": "error",
"no-multi-str": "error",
"no-new-func": "error",
"no-new-object": "error",
"no-return-assign": "error",
"no-sequences": "error",
"no-shadow-restricted-names": "error",
"no-unused-expressions": "error",
"no-use-before-define": "off",
"no-new": "off",
"dot-notation": ["error", { "allowKeywords": true }],
"eqeqeq": "error",
"new-parens": "error",
"strict": ["error", "global"],
"yoda": "error",
"valid-jsdoc": "error",
"object-shorthand": "error",
"no-var": "error",
"prefer-const": "error",
"prefer-arrow-callback": "error",
"arrow-body-style": [
"error",
"as-needed",
{ "requireReturnForObjectLiteral": true }
],
"prefer-template": "error"
},
"overrides": [
{
"files": ["test/**/*.js"],
"env": {
"jest": true
},
"rules": {
"no-console": "off",
"no-unused-vars": "off",
"no-shadow": "off",
"no-unused-expressions": "off"
}
},
{
"files": ["example/**/*.js", "benchmarks/**/*.js"],
"rules": {
"no-console": "off"
}
}
]
}
prom-client-14.1.0/.gitattributes 0000664 0000000 0000000 00000000023 14301147710 0016712 0 ustar 00root root 0000000 0000000 * text=auto eol=lf
prom-client-14.1.0/.github/ 0000775 0000000 0000000 00000000000 14301147710 0015364 5 ustar 00root root 0000000 0000000 prom-client-14.1.0/.github/workflows/ 0000775 0000000 0000000 00000000000 14301147710 0017421 5 ustar 00root root 0000000 0000000 prom-client-14.1.0/.github/workflows/changelog.yml 0000664 0000000 0000000 00000001040 14301147710 0022066 0 ustar 00root root 0000000 0000000 on: [pull_request]
name: Changelog Reminder
jobs:
remind:
name: Changelog Reminder
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Changelog Reminder
uses: peterjgrainger/action-changelog-reminder@v1.2.0
with:
changelog_regex: 'CHANGELOG\.md'
customPrMessage: 'Thanks for opening this pull request! Each pull request require an update in the CHANGELOG. Please update it based on your changes.'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
prom-client-14.1.0/.github/workflows/nodejs.yml 0000664 0000000 0000000 00000002123 14301147710 0021424 0 ustar 00root root 0000000 0000000 name: Node.js CI
on:
push:
branches:
- master
- main
- next
pull_request:
branches:
- '**'
jobs:
build:
name: Test on Node.js v${{ matrix.node-version }} and OS ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
node-version: [10.x, 12.x, 14.x, 16.x, 17.x, 18.x]
os: [ubuntu-latest, windows-latest, macOS-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- name: Restore dependencies cache
uses: actions/cache@v2
id: cache
with:
path: node_modules
key: ${{ matrix.os }}-{{ matrix.node-version }}-node_modules-${{ hashFiles('**/package.json') }}
restore-keys: |
${{ matrix.os }}-{{ matrix.node-version }}-node_modules-
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: npm i
- name: Test
run: npm run test
prom-client-14.1.0/.gitignore 0000664 0000000 0000000 00000000100 14301147710 0016003 0 ustar 00root root 0000000 0000000 .DS_Store
node_modules
.idea/
*.log
coverage/
package-lock.json
prom-client-14.1.0/CHANGELOG.md 0000664 0000000 0000000 00000032734 14301147710 0015646 0 ustar 00root root 0000000 0000000 # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/) and this
project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
### Breaking
### Changed
### Added
## [14.1.0] - 2022-08-23
### Changed
- types: converted all the generic Metric types to be optional
- The `done()` functions returned by `gauge.startTimer()` and
`summary.startTimer()` now return the timed duration. Histograms already had
this behavior.
- types: fixed type for `registry.getMetricsAsArray()`
- Improve performance of `gague.inc()` and `gauge.dec()` by calling `hashObject()` once.
### Added
- The `processResources` metric was added, which keeps a track of all sorts of
active resources. It consists of the following gauges:
- `nodejs_active_resources` - Number of active resources that are currently
keeping the event loop alive, grouped by async resource type.
- `nodejs_active_resources_total` - Total number of active resources.
It is supposed to provide the combined result of the `processHandles` and
`processRequests` metrics along with information about any other types of
async resources that these metrics do not keep a track of (like timers).
- Support gzipped pushgateway requests
## [14.0.1] - 2021-11-02
### Changed
- changed: typedef for pushgateway to reflect js implementation.
## [14.0.0] - 2021-09-18
### Breaking
- changed: `linearBuckets` does not propagate rounding errors anymore.
Fewer bucket bounds will be affected by rounding errors. Histogram bucket
labels may change. [`6f1f3b2`](https://github.com/siimon/prom-client/commit/6f1f3b24c9c21311ff33e7d4b987b40c6b304e04)
- changed: The push gateway methods `pushAdd()`, `push()` and `delete()` now
return Promises instead of accepting a callback:
```js
// Old:
gateway.pushAdd({ jobName: 'test' }, (err, resp, body) => {});
// New:
gateway
.pushAdd({ jobName: 'test' })
.then(({ resp, body }) => {})
.catch(err => {});
// or
const { resp, body } = await gateway.pushAdd({ jobName: 'test' });
```
[`f177b1f`](https://github.com/siimon/prom-client/commit/f177b1fd3d4db5fc48fcb1ec02d94069fffcf144)
- changed: The default `nodejs_eventloop_lag_*` metrics are now reset every time
they are observed. This prevents these metrics from "stabilizing" over a long
period of time and becoming insensitive to small changes. For more info, see
[#370](https://github.com/siimon/prom-client/issues/370). [`0f444cd`](https://github.com/siimon/prom-client/commit/0f444cd38e4c7074991270106c270f731bafddb8)
### Changed
- Add missing `await`/`then`s to examples. [`074f339`](https://github.com/siimon/prom-client/commit/074f339914e5d71b5829cd4a949affae23dbc409)
- Add missing type declaration for `client.contentType`. [`3b66641`](https://github.com/siimon/prom-client/commit/3b6664160bdd1555045b03d8f4c421022f30e1db)
- Modernize some label processing code. [`c9bf1d8`](https://github.com/siimon/prom-client/commit/c9bf1d8e3db3b5fb97faf2df9ca9b9af670288f3)
## [13.2.0] - 2021-08-08
### Changed
- Don't add event listener to `process` if cluster module is not used.
- fix: set labels for default memory metrics on linux.
- fix: fix DEP0152 deprecation warning in Node.js v16+.
- fix: Set aggregation mode for newer event loop metrics. (Fixes [#418](https://github.com/siimon/prom-client/issues/418))
- Improve performance of/reduce memory allocations in Gauge.
### Added
- feat: added `zero()` to `Histogram` for setting the metrics for a given label combination to zero
- fix: allow `Gauge.inc/dec(0)` without defaulting to 1
## [13.1.0] - 2021-01-24
### Changed
- fix: push client attempting to write Promise (fixes [#390](https://github.com/siimon/prom-client/issues/390))
- types: improve type checking of labels
- fix: Summary#observe should throw when adding additional labels to labelset (fixes [#262](https://github.com/siimon/prom-client/issues/262))
### Added
- feat: added the ability to pass labels as an object to `labels()` and `remove()`
- Added: More examples with commented output
## [13.0.0] - 2020-12-16
### Breaking
- changed: The following functions are now async (return a promise):
`registry.metrics()`
`registry.getMetricsAsJSON()`
`registry.getMetricsAsArray()`
`registry.getSingleMetricAsString()`
If your metrics server has a line like `res.send(register.metrics())`, you
should change it to `res.send(await register.metrics())`.
Additionally, all metric types now accept an optional `collect` function,
which is called when the metric's value should be collected and within which
you should set the metric's value. You should provide a `collect` function for
point-in-time metrics (e.g. current memory usage, as opposed to HTTP request
durations that are continuously logged in a histogram).
- changed: `register.clusterMetrics()` no longer accepts a callback; it only
returns a promise.
- removed: v12.0.0 added the undocumented functions `registry.registerCollector`
and `registry.collectors()`. These have been removed. If you were using them,
you should instead provide a `collect` function as described above.
### Changed
- fix: provide nodejs_version_info metric value after calling `registry.resetMetrics()` (#238)
- fix: provide process_max_fds metric value after calling `registry.resetMetrics()`
- fix: provide process_start_time_seconds metric value after calling `registry.resetMetrics()`
- chore: improve performance of `registry.getMetricAsPrometheusString`
- chore: refactor metrics to reduce code duplication
- chore: replace `utils.getPropertiesFromObj` with `Object.values`
- chore: remove unused `catch` bindings
- chore: upgrade Prettier to 2.x
- fix: startTimer returns `number` in typescript instead of `void`
- fix: incorrect typings of `registry.getSingleMetric' (#388)
- chore: stop testing node v13 on CI
### Added
- feat: exposed `registry.registerCollector()` and `registry.collectors()` methods in TypeScript declaration
- Added: complete working example of a pushgateway push in `example/pushgateway.js`
- feat: added support for adding labels to default metrics (#374)
- Added CHANGELOG reminder
## [12.0.0] - 2020-02-20
### Breaking
- Dropped support for end-of-life Node.js versions 6.x and 8.x
- Dropped the previously deprecated support for positional parameters in
constructors, only the config object forms remain.
- Default metrics are collected on scrape of metrics endpoint, not on an
interval. The `timeout` option to `collectDefaultMetrics(conf)` is no longer
supported or needed, and the function no longer returns a `Timeout` object.
### Changed
- chore: remove ignored package-lock.json
- fix: `process_max_fds` is process limit, not OS (#314)
- Changed `Metric` labelNames & labelValues in TypeScript declaration to a generic type `T extends string`, instead of `string`
- Lazy-load Node.js Cluster module to fix Passenger support (#293)
- fix: avoid mutation bug in `registry.getMetricsAsJSON()`
- fix: improve performance of `registry.getMetrics*`
- End function of histogram `startTimer`, when invoked returns the number of seconds
- chore: reindent package.json
- chore: correct var name in processStartTime
- chore: add test for `process_start_time_seconds`
- chore: spelling corrections in README
### Added
- feat: implement GC metrics collection without native(C++) modules.
- feat: implement advanced event loop monitoring
## [11.5.3] - 2019-06-27
### Changed
- Parameter `compressCount` in Summaries to control compression of data in t-digest.
- Compress t-digest in Summaries
## [11.5.2] - 2019-06-20
### Changed
- fix: avoid mutation bug in registry
## [11.5.1] - 2019-06-13
### Changed
- fix: guard against missing constructor
## [11.5.0] - 2019-06-04
### Added
- Added `timestamps` toggle to `collectDefaultMetrics` options
- Export `validateMetricName`
## [11.4.0] - 2019-06-04
### Added
- `nodejs_active_handles` metric to the `collectDefaultMetrics()`. Unlike `nodejs_active_handles_total` it split count of active handles by type.
- `nodejs_active_requests` metric to the `collectDefaultMetrics()`. Unlike `nodejs_active_requests_total` it split count of active requests by type.
## [11.3.0] - 2019-04-02
### Changed
- Check that cluster worker is still connected before attempting to query it for
metrics. (#244)
### Added
- Added a `remove()` method on each metric type, based on [Prometheus "Writing Client Libraries" section on labels](https://prometheus.io/docs/instrumenting/writing_clientlibs/#labels)
## [11.2.1]
### Breaking
### Changed
### Added
- Updated types for Summary in typescript definition file
## [11.2.0]
### Changed
- Updated child dependency `merge` patch version to remove vulnerability.
### Added
- Added an initial `benchmark` suite which can be run with `npm run benchmarks`.
- Add support for sliding windows in Summaries
## [11.1.3] - 2018-09-22
### Changed
- Fixed performance by avoiding `Object.assign` on hot paths, as well as
mutating objects when appropriate.
## [11.1.2] - 2018-09-19
### Changed
- Allow setting Gauge values to NaN, +Inf, and -Inf
- Fixed `histogram` scrape performance by using `acc.push` instead of `acc.concat`. Fixes #216 with #219
## [11.1.1] - 2018-06-29
### Changed
- Fixed `processOpenFileDescriptors` metric when no custom config was set
## [11.1.0] - 2018-06-29
- Added ability to set a name prefix in the default metrics
### Changed
- Fixed `startTimer` utility to not mutate objects passed as `startLabels`
- Fixed `Counter` to validate labels parameter of `inc()` against initial
labelset
- Fixed `AggregatorFactory` losing the aggregator method of metrics
## [11.0.0] - 2018-03-10
### Breaking
- Fixed `gauge.setToCurrentTime()` to use seconds instead of milliseconds
- This conforms to Prometheus
[best practices](https://prometheus.io/docs/practices/naming/#base-units)
- Dropped support for node 4
## [10.2.3] - 2018-02-28
### Breaking
### Changed
- Fixed issue that `registry.getMetricsAsJSON()` ignores registry default labels
### Added
## [10.2.2] - 2017-11-02
### Changed
- Fixed invalid `process_virtual_memory_bytes` reported under linux
## [10.2.1] - 2017-10-27
### Changed
- Only resolve/reject `clusterMetrics` promise if no callback is provided
## [10.2.0] - 2017-10-16
### Changed
- Don't add event listeners if cluster module is not used.
- Fixed issue with counters having extra records when using empty labels
### Added
- Added `reset` to Counter and Gauge
- Added `resetMetrics` to register to calling `reset` of all metric instances
## [10.1.1] - 2017-09-26
### Changed
- Update TypeScript definitions and JSDoc comments to match JavaScript sources
- Fix lexical scope of `arguments` in cluster code
## [10.1.0] - 2017-09-04
### Added
- Support aggregating metrics across workers in a Node.js cluster.
## [10.0.4] - 2017-08-22
### Changed
- Include invalid values in the error messages
## [10.0.3] - 2017-08-07
### Added
- Added registerMetric to definitions file
### Changed
- Fixed typing of DefaultMetricsCollectorConfiguration in definitions file
- Don't pass timestamps through to pushgateway by default
## [10.0.2] - 2017-07-07
### Changed
- Don't poll default metrics every single tick
## [10.0.1] - 2017-07-06
### Added
- Metrics should be initialized to 0 when there are no labels
## [10.0.0] - 2017-07-04
### Breaking
- Print deprecation warning when metrics are constructed using non-objects
- Print deprecation warning when `collectDefaultMetrics` is called with a number
### Added
- Ability to set default labels by registry
- Allow passing in `registry` as second argument to `collectDefaultMetrics` to
use that instead of the default registry
### Changed
- Convert code base to ES2015 code (node 4)
- add engines field to package.json
- Use object shorthand
- Remove `util-extend` in favor of `Object.assign`
- Arrow functions over binding or putting `this` in a variable
- Use template strings
- `prototype` -> `class`
## [9.1.1] - 2017-06-17
### Changed
- Don't set timestamps for metrics that are never updated
## [9.1.0] - 2017-06-07
### Added
- Ability to merge registries
### Changed
- Correct typedefs for object constructor of metrics
## [9.0.0] - 2017-05-06
### Added
- Support for multiple registers
- Support for object literals in metric constructors
- Timestamp support
### Changed
- Collection of default metrics is now disabled by default. Start collection by
running `collectDefaultMetrics()`.
### Deprecated
- Creating metrics with one argument per parameter - use object literals
instead.
[unreleased]: https://github.com/siimon/prom-client/compare/v10.2.2...HEAD
[10.2.2]: https://github.com/siimon/prom-client/compare/v10.2.1...v10.2.2
[10.2.1]: https://github.com/siimon/prom-client/compare/v10.2.0...v10.2.1
[10.2.0]: https://github.com/siimon/prom-client/compare/v10.1.1...v10.2.0
[10.1.1]: https://github.com/siimon/prom-client/compare/v10.1.0...v10.1.1
[10.1.0]: https://github.com/siimon/prom-client/compare/v10.0.4...v10.1.0
[10.0.4]: https://github.com/siimon/prom-client/compare/v10.0.3...v10.0.4
[10.0.3]: https://github.com/siimon/prom-client/compare/v10.0.2...v10.0.3
[10.0.2]: https://github.com/siimon/prom-client/compare/v10.0.1...v10.0.2
[10.0.1]: https://github.com/siimon/prom-client/compare/v10.0.0...v10.0.1
[10.0.0]: https://github.com/siimon/prom-client/compare/v9.1.1...v10.0.0
[9.1.1]: https://github.com/siimon/prom-client/compare/v9.1.0...v9.1.1
[9.1.0]: https://github.com/siimon/prom-client/compare/v9.0.0...v9.1.0
[9.0.0]: https://github.com/siimon/prom-client/commit/1ef835f908e1a5032f228bbc754479fe7ccf5201
prom-client-14.1.0/LICENSE 0000664 0000000 0000000 00000026115 14301147710 0015036 0 ustar 00root root 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2015 Simon Nyberg
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
prom-client-14.1.0/README.md 0000664 0000000 0000000 00000040415 14301147710 0015307 0 ustar 00root root 0000000 0000000 # Prometheus client for node.js [](https://github.com/siimon/prom-client/actions)
A prometheus client for Node.js that supports histogram, summaries, gauges and
counters.
## Usage
See example folder for a sample usage. The library does not bundle any web
framework. To expose the metrics, respond to Prometheus's scrape requests with
the result of `await registry.metrics()`.
### Usage with Node.js's `cluster` module
Node.js's `cluster` module spawns multiple processes and hands off socket
connections to those workers. Returning metrics from a worker's local registry
will only reveal that individual worker's metrics, which is generally
undesirable. To solve this, you can aggregate all of the workers' metrics in the
master process. See `example/cluster.js` for an example.
Default metrics use sensible aggregation methods. (Note, however, that the event
loop lag mean and percentiles are averaged, which is not perfectly accurate.)
Custom metrics are summed across workers by default. To use a different
aggregation method, set the `aggregator` property in the metric config to one of
'sum', 'first', 'min', 'max', 'average' or 'omit'. (See `lib/metrics/version.js`
for an example.)
If you need to expose metrics about an individual worker, you can include a
value that is unique to the worker (such as the worker ID or process ID) in a
label. (See `example/server.js` for an example using
`worker_${cluster.worker.id}` as a label value.)
Metrics are aggregated from the global registry by default. To use a different
registry, call
`client.AggregatorRegistry.setRegistries(registryOrArrayOfRegistries)` from the
worker processes.
## API
### Default metrics
There are some default metrics recommended by Prometheus
[itself](https://prometheus.io/docs/instrumenting/writing_clientlibs/#standard-and-runtime-collectors).
To collect these, call `collectDefaultMetrics`. In addition, some
Node.js-specific metrics are included, such as event loop lag, active handles,
GC and Node.js version. See [lib/metrics](lib/metrics) for a list of all
metrics.
NOTE: Some of the metrics, concerning File Descriptors and Memory, are only
available on Linux.
`collectDefaultMetrics` optionally accepts a config object with following entries:
- `prefix` an optional prefix for metric names. Default: no prefix.
- `register` to which metrics should be registered. Default: the global default registry.
- `gcDurationBuckets` with custom buckets for GC duration histogram. Default buckets of GC duration histogram are `[0.001, 0.01, 0.1, 1, 2, 5]` (in seconds).
- `eventLoopMonitoringPrecision` with sampling rate in milliseconds. Must be greater than zero. Default: 10.
To register metrics to another registry, pass it in as `register`:
```js
const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;
const Registry = client.Registry;
const register = new Registry();
collectDefaultMetrics({ register });
```
To use custom buckets for GC duration histogram, pass it in as `gcDurationBuckets`:
```js
const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;
collectDefaultMetrics({ gcDurationBuckets: [0.1, 0.2, 0.3] });
```
To prefix metric names with your own arbitrary string, pass in a `prefix`:
```js
const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;
const prefix = 'my_application_';
collectDefaultMetrics({ prefix });
```
To apply generic labels to all default metrics, pass an object to the `labels` property (useful if you're working in a clustered environment):
```js
const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;
collectDefaultMetrics({
labels: { NODE_APP_INSTANCE: process.env.NODE_APP_INSTANCE },
});
```
You can get the full list of metrics by inspecting
`client.collectDefaultMetrics.metricsList`.
Default metrics are collected on scrape of metrics endpoint,
not on an interval.
```js
const client = require('prom-client');
const collectDefaultMetrics = client.collectDefaultMetrics;
collectDefaultMetrics();
```
### Custom Metrics
All metric types have two mandatory parameters: `name` and `help`. Refer to
for guidance on naming metrics.
For metrics based on point-in-time observations (e.g. current memory usage, as
opposed to HTTP request durations observed continuously in a histogram), you
should provide a `collect()` function, which will be invoked when Prometheus
scrapes your metrics endpoint. `collect()` can either be synchronous or return a
promise. See **Gauge** below for an example. (Note that you should not update
metric values in a `setInterval` callback; do so in this `collect` function
instead.)
See [**Labels**](#labels) for information on how to configure labels for all
metric types.
#### Counter
Counters go up, and reset when the process restarts.
```js
const client = require('prom-client');
const counter = new client.Counter({
name: 'metric_name',
help: 'metric_help',
});
counter.inc(); // Increment by 1
counter.inc(10); // Increment by 10
```
#### Gauge
Gauges are similar to Counters but a Gauge's value can be decreased.
```js
const client = require('prom-client');
const gauge = new client.Gauge({ name: 'metric_name', help: 'metric_help' });
gauge.set(10); // Set to 10
gauge.inc(); // Increment 1
gauge.inc(10); // Increment 10
gauge.dec(); // Decrement by 1
gauge.dec(10); // Decrement by 10
```
##### Configuration
If the gauge is used for a point-in-time observation, you should provide a
`collect` function:
```js
const client = require('prom-client');
new client.Gauge({
name: 'metric_name',
help: 'metric_help',
collect() {
// Invoked when the registry collects its metrics' values.
// This can be synchronous or it can return a promise/be an async function.
this.set(/* the current value */);
},
});
```
```js
// Async version:
const client = require('prom-client');
new client.Gauge({
name: 'metric_name',
help: 'metric_help',
async collect() {
// Invoked when the registry collects its metrics' values.
const currentValue = await somethingAsync();
this.set(currentValue);
},
});
```
Note that you should not use arrow functions for `collect` because arrow
functions will not have the correct value for `this`.
##### Utility Functions
```js
// Set value to current time:
gauge.setToCurrentTime();
// Record durations:
const end = gauge.startTimer();
http.get('url', res => {
end();
});
```
#### Histogram
Histograms track sizes and frequency of events.
##### Configuration
The defaults buckets are intended to cover usual web/RPC requests, but they can
be overridden. (See also [**Bucket Generators**](#bucket-generators).)
```js
const client = require('prom-client');
new client.Histogram({
name: 'metric_name',
help: 'metric_help',
buckets: [0.1, 5, 15, 50, 100, 500],
});
```
##### Examples
```js
const client = require('prom-client');
const histogram = new client.Histogram({
name: 'metric_name',
help: 'metric_help',
});
histogram.observe(10); // Observe value in histogram
```
##### Utility Methods
```js
const end = histogram.startTimer();
xhrRequest(function (err, res) {
const seconds = end(); // Observes and returns the value to xhrRequests duration in seconds
});
```
#### Summary
Summaries calculate percentiles of observed values.
##### Configuration
The default percentiles are: 0.01, 0.05, 0.5, 0.9, 0.95, 0.99, 0.999. But they
can be overridden by specifying a `percentiles` array. (See also
[**Bucket Generators**](#bucket-generators).)
```js
const client = require('prom-client');
new client.Summary({
name: 'metric_name',
help: 'metric_help',
percentiles: [0.01, 0.1, 0.9, 0.99],
});
```
To enable the sliding window functionality for summaries you need to add
`maxAgeSeconds` and `ageBuckets` to the config like this:
```js
const client = require('prom-client');
new client.Summary({
name: 'metric_name',
help: 'metric_help',
maxAgeSeconds: 600,
ageBuckets: 5,
});
```
The `maxAgeSeconds` will tell how old a bucket can be before it is reset and
`ageBuckets` configures how many buckets we will have in our sliding window for
the summary.
##### Examples
```js
const client = require('prom-client');
const summary = new client.Summary({
name: 'metric_name',
help: 'metric_help',
});
summary.observe(10);
```
##### Utility Methods
```js
const end = summary.startTimer();
xhrRequest(function (err, res) {
end(); // Observes the value to xhrRequests duration in seconds
});
```
### Labels
All metrics can take a `labelNames` property in the configuration object. All
label names that the metric support needs to be declared here. There are two
ways to add values to the labels:
```js
const client = require('prom-client');
const gauge = new client.Gauge({
name: 'metric_name',
help: 'metric_help',
labelNames: ['method', 'statusCode'],
});
// 1st version: Set value to 100 with "method" set to "GET" and "statusCode" to "200"
gauge.set({ method: 'GET', statusCode: '200' }, 100);
// 2nd version: Same effect as above
gauge.labels({ method: 'GET', statusCode: '200' }).set(100);
// 3rd version: And again the same effect as above
gauge.labels('GET', '200').set(100);
```
It is also possible to use timers with labels, both before and after the timer
is created:
```js
const end = startTimer({ method: 'GET' }); // Set method to GET, we don't know statusCode yet
xhrRequest(function (err, res) {
if (err) {
end({ statusCode: '500' }); // Sets value to xhrRequest duration in seconds with statusCode 500
} else {
end({ statusCode: '200' }); // Sets value to xhrRequest duration in seconds with statusCode 200
}
});
```
#### Zeroing metrics with Labels
Metrics with labels can not be exported before they have been observed at least
once since the possible label values are not known before they're observed.
For histograms, this can be solved by explicitly zeroing all expected label values:
```js
const histogram = new client.Histogram({
name: 'metric_name',
help: 'metric_help',
buckets: [0.1, 5, 15, 50, 100, 500],
labels: ['method'],
});
histogram.zero({ method: 'GET' });
histogram.zero({ method: 'POST' });
```
#### Strongly typed Labels
Typescript can also enforce label names using `as const`
```typescript
import * as client from 'prom-client';
const gauge = new client.Counter({
name: 'metric_name',
help: 'metric_help',
// add `as const` here to enforce label names
labelNames: ['method'] as const,
});
// Ok
gauge.inc({ method: 1 });
// this is an error since `'methods'` is not a valid `labelName`
// @ts-expect-error
gauge.inc({ methods: 1 });
```
#### Default Labels (segmented by registry)
Static labels may be applied to every metric emitted by a registry:
```js
const client = require('prom-client');
const defaultLabels = { serviceName: 'api-v1' };
client.register.setDefaultLabels(defaultLabels);
```
This will output metrics in the following way:
```
# HELP process_resident_memory_bytes Resident memory size in bytes.
# TYPE process_resident_memory_bytes gauge
process_resident_memory_bytes{serviceName="api-v1"} 33853440 1498510040309
```
Default labels will be overridden if there is a name conflict.
`register.clear()` will clear default labels.
### Multiple registries
By default, metrics are automatically registered to the global registry (located
at `require('prom-client').register`). You can prevent this by specifying
`registers: []` in the metric constructor configuration.
Using non-global registries requires creating a Registry instance and passing it
inside `registers` in the metric configuration object. Alternatively you can
pass an empty `registers` array and register it manually.
Registry has a `merge` function that enables you to expose multiple registries
on the same endpoint. If the same metric name exists in both registries, an
error will be thrown.
```js
const client = require('prom-client');
const registry = new client.Registry();
const counter = new client.Counter({
name: 'metric_name',
help: 'metric_help',
registers: [registry], // specify a non-default registry
});
const histogram = new client.Histogram({
name: 'metric_name',
help: 'metric_help',
registers: [], // don't automatically register this metric
});
registry.registerMetric(histogram); // register metric manually
counter.inc();
const mergedRegistries = client.Registry.merge([registry, client.register]);
```
If you want to use multiple or non-default registries with the Node.js `cluster`
module, you will need to set the registry/registries to aggregate from:
```js
const AggregatorRegistry = client.AggregatorRegistry;
AggregatorRegistry.setRegistries(registry);
// or for multiple registries:
AggregatorRegistry.setRegistries([registry1, registry2]);
```
### Register
You can get all metrics by running `await register.metrics()`, which will return
a string in the Prometheus exposition format.
#### Getting a single metric value in Prometheus exposition format
If you need to output a single metric in the Prometheus exposition format, you
can use `await register.getSingleMetricAsString(*name of metric*)`, which will
return a string for Prometheus to consume.
#### Getting a single metric
If you need to get a reference to a previously registered metric, you can use
`await register.getSingleMetric(*name of metric*)`.
#### Removing metrics
You can remove all metrics by calling `register.clear()`. You can also remove a
single metric by calling `register.removeSingleMetric(*name of metric*)`.
#### Resetting metrics
If you need to reset all metrics, you can use `register.resetMetrics()`. The
metrics will remain present in the register and can be used without the need to
instantiate them again, like you would need to do after `register.clear()`.
#### Cluster metrics
You can get aggregated metrics for all workers in a Node.js cluster with
`await register.clusterMetrics()`. This method returns a promise that resolves
with a metrics string suitable for Prometheus to consume.
```js
const metrics = await register.clusterMetrics();
// - or -
register
.clusterMetrics()
.then(metrics => {
/* ... */
})
.catch(err => {
/* ... */
});
```
### Pushgateway
It is possible to push metrics via a
[Pushgateway](https://github.com/prometheus/pushgateway).
```js
const client = require('prom-client');
let gateway = new client.Pushgateway('http://127.0.0.1:9091');
gateway.pushAdd({ jobName: 'test' })
.then({resp, body} => {
/* ... */
})
.catch(err => {
/* ... */
})); //Add metric and overwrite old ones
gateway.push({ jobName: 'test' })
.then({resp, body} => {
/* ... */
})
.catch(err => {
/* ... */
})); //Overwrite all metrics (use PUT)
gateway.delete({ jobName: 'test' })
.then({resp, body} => {
/* ... */
})
.catch(err => {
/* ... */
})); //Delete all metrics for jobName
//All gateway requests can have groupings on it
gateway.pushAdd({ jobName: 'test', groupings: { key: 'value' } })
.then({resp, body} => {
/* ... */
})
.catch(err => {
/* ... */
}));
// It's possible to extend the Pushgateway with request options from nodes core
// http/https library. In particular, you might want to provide an agent so that
// TCP connections are reused.
gateway = new client.Pushgateway('http://127.0.0.1:9091', {
timeout: 5000, //Set the request timeout to 5000ms
agent: new http.Agent({
keepAlive: true,
keepAliveMsec: 10000,
maxSockets: 5,
}),
});
```
### Bucket Generators
For convenience, there are two bucket generator functions - linear and
exponential.
```js
const client = require('prom-client');
new client.Histogram({
name: 'metric_name',
help: 'metric_help',
buckets: client.linearBuckets(0, 10, 20), //Create 20 buckets, starting on 0 and a width of 10
});
new client.Histogram({
name: 'metric_name',
help: 'metric_help',
buckets: client.exponentialBuckets(1, 2, 5), //Create 5 buckets, starting on 1 and with a factor of 2
});
```
The content-type prometheus expects is also exported as a constant, both on the
`register` and from the main file of this project, called `contentType`.
### Garbage Collection Metrics
To avoid native dependencies in this module, GC statistics for bytes reclaimed
in each GC sweep are kept in a separate module:
https://github.com/SimenB/node-prometheus-gc-stats. (Note that that metric may
no longer be accurate now that v8 uses parallel garbage collection.)
prom-client-14.1.0/benchmarks/ 0000775 0000000 0000000 00000000000 14301147710 0016141 5 ustar 00root root 0000000 0000000 prom-client-14.1.0/benchmarks/gauge.js 0000664 0000000 0000000 00000001463 14301147710 0017573 0 ustar 00root root 0000000 0000000 'use strict';
const { getLabelNames, labelCombinationFactory } = require('./utils/labels');
module.exports = setupGaugeSuite;
function setupGaugeSuite(suite) {
suite.add(
'inc',
labelCombinationFactory([], (client, { Gauge }, labels) =>
Gauge.inc(labels, 1),
),
{ teardown, setup: setup(0) },
);
suite.add(
'inc with labels',
labelCombinationFactory([8, 8], (client, { Gauge }, labels) =>
Gauge.inc(labels, 1),
),
{ teardown, setup: setup(2) },
);
}
function setup(labelCount) {
return client => {
const registry = new client.Registry();
const Gauge = new client.Gauge({
name: 'Gauge',
help: 'Gauge',
labelNames: getLabelNames(labelCount),
registers: [registry],
});
return { registry, Gauge };
};
}
function teardown(client, { registry }) {
registry.clear();
}
prom-client-14.1.0/benchmarks/histogram.js 0000664 0000000 0000000 00000002707 14301147710 0020502 0 ustar 00root root 0000000 0000000 'use strict';
const { getLabelNames, labelCombinationFactory } = require('./utils/labels');
module.exports = setupHistogramSuite;
function setupHistogramSuite(suite) {
suite.add(
'observe#1 with 64',
labelCombinationFactory([64], (client, { histogram }, labels) =>
histogram.observe(labels, 1),
),
{ teardown, setup: setup(1) },
);
suite.add(
'observe#2 with 8',
labelCombinationFactory([8, 8], (client, { histogram }, labels) =>
histogram.observe(labels, 1),
),
{ teardown, setup: setup(2) },
);
suite.add(
'observe#2 with 4 and 2 with 2',
labelCombinationFactory([4, 4, 2, 2], (client, { histogram }, labels) =>
histogram.observe(labels, 1),
),
{ teardown, setup: setup(4) },
);
suite.add(
'observe#2 with 2 and 2 with 4',
labelCombinationFactory([2, 2, 4, 4], (client, { histogram }, labels) =>
histogram.observe(labels, 1),
),
{ teardown, setup: setup(4) },
);
suite.add(
'observe#6 with 2',
labelCombinationFactory(
[2, 2, 2, 2, 2, 2],
(client, { histogram }, labels) => histogram.observe(labels, 1),
),
{ teardown, setup: setup(6) },
);
}
function setup(labelCount) {
return client => {
const registry = new client.Registry();
const histogram = new client.Histogram({
name: 'histogram',
help: 'histogram',
labelNames: getLabelNames(labelCount),
registers: [registry],
});
return { registry, histogram };
};
}
function teardown(client, { registry }) {
registry.clear();
}
prom-client-14.1.0/benchmarks/index.js 0000664 0000000 0000000 00000001054 14301147710 0017606 0 ustar 00root root 0000000 0000000 'use strict';
const createRegressionBenchmark = require('@clevernature/benchmark-regression');
const currentClient = require('..');
const benchmarks = createRegressionBenchmark(currentClient, [
'prom-client@latest',
]);
benchmarks.suite('registry', require('./registry'));
benchmarks.suite('histogram', require('./histogram'));
benchmarks.suite('gauge', require('./gauge'));
benchmarks.suite('summary', require('./summary'));
benchmarks.run().catch(err => {
console.error(err.stack);
// eslint-disable-next-line no-process-exit
process.exit(1);
});
prom-client-14.1.0/benchmarks/registry.js 0000664 0000000 0000000 00000002267 14301147710 0020356 0 ustar 00root root 0000000 0000000 'use strict';
const { getLabelNames, getLabelCombinations } = require('./utils/labels');
module.exports = setupRegistrySuite;
function setupRegistrySuite(suite) {
const labelSetups = [
{ name: '1 with 64', counts: [64] },
{ name: '2 with 8', counts: [8, 8] },
{ name: '2 with 4 and 2 with 2', counts: [4, 4, 2, 2] },
{ name: '2 with 2 and 2 with 4', counts: [2, 2, 4, 4] },
{ name: '6 with 2', counts: [2, 2, 2, 2, 2, 2] },
];
labelSetups.forEach(({ name, counts }) => {
suite.add(
`getMetricsAsJSON#${name}`,
(client, registry) => registry.getMetricsAsJSON(),
{ setup: setup(counts) },
);
});
labelSetups.forEach(({ name, counts }) => {
suite.add(`metrics#${name}`, (client, registry) => registry.metrics(), {
setup: setup(counts),
});
});
}
function setup(labelCounts) {
return client => {
const registry = new client.Registry();
const histogram = new client.Histogram({
name: 'histogram',
help: 'histogram',
labelNames: getLabelNames(labelCounts.length),
registers: [registry],
});
const labelCombinations = getLabelCombinations(labelCounts);
labelCombinations.forEach(labels => histogram.observe(labels, 1));
return registry;
};
}
prom-client-14.1.0/benchmarks/summary.js 0000664 0000000 0000000 00000002641 14301147710 0020177 0 ustar 00root root 0000000 0000000 'use strict';
const { getLabelNames, labelCombinationFactory } = require('./utils/labels');
module.exports = setupSummarySuite;
function setupSummarySuite(suite) {
suite.add(
'observe#1 with 64',
labelCombinationFactory([64], (client, { summary }, labels) =>
summary.observe(labels, 1),
),
{ teardown, setup: setup(1) },
);
suite.add(
'observe#2 with 8',
labelCombinationFactory([8, 8], (client, { summary }, labels) =>
summary.observe(labels, 1),
),
{ teardown, setup: setup(2) },
);
suite.add(
'observe#2 with 4 and 2 with 2',
labelCombinationFactory([4, 4, 2, 2], (client, { summary }, labels) =>
summary.observe(labels, 1),
),
{ teardown, setup: setup(4) },
);
suite.add(
'observe#2 with 2 and 2 with 4',
labelCombinationFactory([2, 2, 4, 4], (client, { summary }, labels) =>
summary.observe(labels, 1),
),
{ teardown, setup: setup(4) },
);
suite.add(
'observe#6 with 2',
labelCombinationFactory([2, 2, 2, 2, 2, 2], (client, { summary }, labels) =>
summary.observe(labels, 1),
),
{ teardown, setup: setup(6) },
);
}
function setup(labelCount) {
return client => {
const registry = new client.Registry();
const summary = new client.Summary({
name: 'summary',
help: 'summary',
labelNames: getLabelNames(labelCount),
registers: [registry],
});
return { registry, summary };
};
}
function teardown(client, { registry }) {
registry.clear();
}
prom-client-14.1.0/benchmarks/utils/ 0000775 0000000 0000000 00000000000 14301147710 0017301 5 ustar 00root root 0000000 0000000 prom-client-14.1.0/benchmarks/utils/labels.js 0000664 0000000 0000000 00000002122 14301147710 0021076 0 ustar 00root root 0000000 0000000 'use strict';
const letters = 'abcdefghijklmnopqrstuvwxyz'.split('');
module.exports = {
getLabelNames,
getLabelCombinations,
labelCombinationFactory,
};
function getLabelNames(count) {
return letters.slice(0, count);
}
const flatten = (a, b) => [].concat(...a.map(c => b.map(d => [].concat(c, d))));
const cartesianProduct = (a, b, ...c) =>
b ? cartesianProduct(flatten(a, b), ...c) : a;
const times = a => Array.from(Array(a)).map((_, x) => x);
function getLabelCombinations(labelValues) {
const labelNames = getLabelNames(labelValues.length);
labelValues = labelValues.length > 1 ? labelValues : labelValues.concat(1);
const labelValuesArray = labelValues.map(times);
const labelValueCombinations = cartesianProduct(...labelValuesArray);
return labelValueCombinations.map(values =>
labelNames.reduce((acc, label, i) => {
acc[label] = values[i];
return acc;
}, {}),
);
}
function labelCombinationFactory(labelValues, fn) {
const labelCombinations = getLabelCombinations(labelValues);
return (client, ctx) =>
labelCombinations.forEach(labels => fn(client, ctx, labels));
}
prom-client-14.1.0/example/ 0000775 0000000 0000000 00000000000 14301147710 0015457 5 ustar 00root root 0000000 0000000 prom-client-14.1.0/example/cluster.js 0000664 0000000 0000000 00000001401 14301147710 0017472 0 ustar 00root root 0000000 0000000 'use strict';
const cluster = require('cluster');
const express = require('express');
const metricsServer = express();
const AggregatorRegistry = require('../').AggregatorRegistry;
const aggregatorRegistry = new AggregatorRegistry();
if (cluster.isMaster) {
for (let i = 0; i < 4; i++) {
cluster.fork();
}
metricsServer.get('/cluster_metrics', async (req, res) => {
try {
const metrics = await aggregatorRegistry.clusterMetrics();
res.set('Content-Type', aggregatorRegistry.contentType);
res.send(metrics);
} catch (ex) {
res.statusCode = 500;
res.send(ex.message);
}
});
metricsServer.listen(3001);
console.log(
'Cluster metrics server listening to 3001, metrics exposed on /cluster_metrics',
);
} else {
require('./server.js');
}
prom-client-14.1.0/example/counter.js 0000664 0000000 0000000 00000002633 14301147710 0017500 0 ustar 00root root 0000000 0000000 'use strict';
// Counter
// Single Label
// Multiple Values
const { Counter, register } = require('..');
async function main() {
const c = new Counter({
name: 'test_counter',
help: 'Example of a counter',
labelNames: ['code'],
});
c.inc({ code: 200 });
console.log(await register.metrics());
/*
# HELP test_counter Example of a counter
# TYPE test_counter counter
test_counter{code="200"} 1
*/
c.inc({ code: 200 });
console.log(await register.metrics());
/*
# HELP test_counter Example of a counter
# TYPE test_counter counter
test_counter{code="200"} 2
*/
c.inc();
console.log(await register.metrics());
/*
# HELP test_counter Example of a counter
# TYPE test_counter counter
test_counter{code="200"} 2
test_counter 1
*/
c.reset();
console.log(await register.metrics());
/*
# HELP test_counter Example of a counter
# TYPE test_counter counter
*/
c.inc(15);
console.log(await register.metrics());
/*
# HELP test_counter Example of a counter
# TYPE test_counter counter
test_counter 15
*/
c.inc({ code: 200 }, 12);
console.log(await register.metrics());
/*
# HELP test_counter Example of a counter
# TYPE test_counter counter
test_counter 15
test_counter{code="200"} 12
*/
c.labels('200').inc(12);
console.log(await register.metrics());
/*
# HELP test_counter Example of a counter
# TYPE test_counter counter
test_counter 15
test_counter{code="200"} 24
*/
}
main();
prom-client-14.1.0/example/default-metrics.js 0000664 0000000 0000000 00000014116 14301147710 0021110 0 ustar 00root root 0000000 0000000 'use strict';
const { collectDefaultMetrics, register } = require('..');
collectDefaultMetrics({
timeout: 10000,
gcDurationBuckets: [0.001, 0.01, 0.1, 1, 2, 5], // These are the default buckets.
});
register.metrics().then(str => console.log(str));
/*
Output from metrics():
# HELP process_cpu_user_seconds_total Total user CPU time spent in seconds.
# TYPE process_cpu_user_seconds_total counter
process_cpu_user_seconds_total 0.004261
# HELP process_cpu_system_seconds_total Total system CPU time spent in seconds.
# TYPE process_cpu_system_seconds_total counter
process_cpu_system_seconds_total 0.000547
# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds.
# TYPE process_cpu_seconds_total counter
process_cpu_seconds_total 0.004808
# HELP process_start_time_seconds Start time of the process since unix epoch in seconds.
# TYPE process_start_time_seconds gauge
process_start_time_seconds 1585092233
# HELP process_resident_memory_bytes Resident memory size in bytes.
# TYPE process_resident_memory_bytes gauge
process_resident_memory_bytes 37072896
# HELP process_virtual_memory_bytes Virtual memory size in bytes.
# TYPE process_virtual_memory_bytes gauge
process_virtual_memory_bytes 576438272
# HELP process_heap_bytes Process heap size in bytes.
# TYPE process_heap_bytes gauge
process_heap_bytes 50720768
# HELP process_open_fds Number of open file descriptors.
# TYPE process_open_fds gauge
process_open_fds 98
# HELP process_max_fds Maximum number of open file descriptors.
# TYPE process_max_fds gauge
process_max_fds 1048576
# HELP nodejs_eventloop_lag_seconds Lag of event loop in seconds.
# TYPE nodejs_eventloop_lag_seconds gauge
nodejs_eventloop_lag_seconds 0
# HELP nodejs_eventloop_lag_min_seconds The minimum recorded event loop delay.
# TYPE nodejs_eventloop_lag_min_seconds gauge
nodejs_eventloop_lag_min_seconds 9223372036.854776
# HELP nodejs_eventloop_lag_max_seconds The maximum recorded event loop delay.
# TYPE nodejs_eventloop_lag_max_seconds gauge
nodejs_eventloop_lag_max_seconds 0
# HELP nodejs_eventloop_lag_mean_seconds The mean of the recorded event loop delays.
# TYPE nodejs_eventloop_lag_mean_seconds gauge
nodejs_eventloop_lag_mean_seconds Nan
# HELP nodejs_eventloop_lag_stddev_seconds The standard deviation of the recorded event loop delays.
# TYPE nodejs_eventloop_lag_stddev_seconds gauge
nodejs_eventloop_lag_stddev_seconds Nan
# HELP nodejs_eventloop_lag_p50_seconds The 50th percentile of the recorded event loop delays.
# TYPE nodejs_eventloop_lag_p50_seconds gauge
nodejs_eventloop_lag_p50_seconds 0
# HELP nodejs_eventloop_lag_p90_seconds The 90th percentile of the recorded event loop delays.
# TYPE nodejs_eventloop_lag_p90_seconds gauge
nodejs_eventloop_lag_p90_seconds 0
# HELP nodejs_eventloop_lag_p99_seconds The 99th percentile of the recorded event loop delays.
# TYPE nodejs_eventloop_lag_p99_seconds gauge
nodejs_eventloop_lag_p99_seconds 0
# HELP nodejs_active_handles Number of active libuv handles grouped by handle type. Every handle type is C++ class name.
# TYPE nodejs_active_handles gauge
# HELP nodejs_active_handles_total Total number of active handles.
# TYPE nodejs_active_handles_total gauge
nodejs_active_handles_total 0
# HELP nodejs_active_requests Number of active libuv requests grouped by request type. Every request type is C++ class name.
# TYPE nodejs_active_requests gauge
# HELP nodejs_active_requests_total Total number of active requests.
# TYPE nodejs_active_requests_total gauge
nodejs_active_requests_total 0
# HELP nodejs_heap_size_total_bytes Process heap size from Node.js in bytes.
# TYPE nodejs_heap_size_total_bytes gauge
nodejs_heap_size_total_bytes 5746688
# HELP nodejs_heap_size_used_bytes Process heap size used from Node.js in bytes.
# TYPE nodejs_heap_size_used_bytes gauge
nodejs_heap_size_used_bytes 3870560
# HELP nodejs_external_memory_bytes Node.js external memory size in bytes.
# TYPE nodejs_external_memory_bytes gauge
nodejs_external_memory_bytes 1221803
# HELP nodejs_heap_space_size_total_bytes Process heap space size total from Node.js in bytes.
# TYPE nodejs_heap_space_size_total_bytes gauge
nodejs_heap_space_size_total_bytes{space="read_only"} 262144
nodejs_heap_space_size_total_bytes{space="new"} 2097152
nodejs_heap_space_size_total_bytes{space="old"} 2244608
nodejs_heap_space_size_total_bytes{space="code"} 430080
nodejs_heap_space_size_total_bytes{space="map"} 528384
nodejs_heap_space_size_total_bytes{space="large_object"} 135168
nodejs_heap_space_size_total_bytes{space="code_large_object"} 49152
nodejs_heap_space_size_total_bytes{space="new_large_object"} 0
# HELP nodejs_heap_space_size_used_bytes Process heap space size used from Node.js in bytes.
# TYPE nodejs_heap_space_size_used_bytes gauge
nodejs_heap_space_size_used_bytes{space="read_only"} 32808
nodejs_heap_space_size_used_bytes{space="new"} 955440
nodejs_heap_space_size_used_bytes{space="old"} 2231120
nodejs_heap_space_size_used_bytes{space="code"} 165472
nodejs_heap_space_size_used_bytes{space="map"} 353760
nodejs_heap_space_size_used_bytes{space="large_object"} 131112
nodejs_heap_space_size_used_bytes{space="code_large_object"} 2784
nodejs_heap_space_size_used_bytes{space="new_large_object"} 0
# HELP nodejs_heap_space_size_available_bytes Process heap space size available from Node.js in bytes.
# TYPE nodejs_heap_space_size_available_bytes gauge
nodejs_heap_space_size_available_bytes{space="read_only"} 0
nodejs_heap_space_size_available_bytes{space="new"} 92016
nodejs_heap_space_size_available_bytes{space="old"} 3608
nodejs_heap_space_size_available_bytes{space="code"} 0
nodejs_heap_space_size_available_bytes{space="map"} 0
nodejs_heap_space_size_available_bytes{space="large_object"} 0
nodejs_heap_space_size_available_bytes{space="code_large_object"} 0
nodejs_heap_space_size_available_bytes{space="new_large_object"} 1047456
# HELP nodejs_version_info Node.js version info.
# TYPE nodejs_version_info gauge
nodejs_version_info{version="v12.16.1",major="12",minor="16",patch="1"} 1
# HELP nodejs_gc_duration_seconds Garbage collection duration by kind, one of major, minor, incremental or weakcb.
# TYPE nodejs_gc_duration_seconds histogram
*/
prom-client-14.1.0/example/gauge.js 0000664 0000000 0000000 00000002065 14301147710 0017110 0 ustar 00root root 0000000 0000000 'use strict';
// Gauge
// Single Label
// Multiple Values
const { Gauge, register } = require('..');
async function main() {
const g = new Gauge({
name: 'test_gauge',
help: 'Example of a gauge',
labelNames: ['code'],
});
g.set({ code: 200 }, 5);
console.log(await register.metrics());
/*
# HELP test_gauge Example of a gauge
# TYPE test_gauge gauge
test_gauge{code="200"} 5
*/
g.set(15);
console.log(await register.metrics());
/*
# HELP test_gauge Example of a gauge
# TYPE test_gauge gauge
test_gauge{code="200"} 5
test_gauge 15
*/
g.labels('200').inc();
console.log(await register.metrics());
/*
# HELP test_gauge Example of a gauge
# TYPE test_gauge gauge
test_gauge{code="200"} 6
test_gauge 15
*/
g.inc();
console.log(await register.metrics());
/*
# HELP test_gauge Example of a gauge
# TYPE test_gauge gauge
test_gauge{code="200"} 6
test_gauge 16
*/
g.set(22);
console.log(await register.metrics());
/*
# HELP test_gauge Example of a gauge
# TYPE test_gauge gauge
test_gauge{code="200"} 6
test_gauge 22
*/
}
main();
prom-client-14.1.0/example/histogram-1.js 0000664 0000000 0000000 00000002100 14301147710 0020141 0 ustar 00root root 0000000 0000000 'use strict';
// Histogram
// Single Label
// Single Value
const { register, Histogram } = require('..');
const h = new Histogram({
name: 'test_histogram',
help: 'Example of a histogram',
labelNames: ['code'],
});
h.labels('200').observe(0.4);
h.labels('200').observe(0.6);
h.observe({ code: '200' }, 0.4);
register.metrics().then(str => console.log(str));
/*
Output from metrics():
# HELP test_histogram Example of a histogram
# TYPE test_histogram histogram
test_histogram_bucket{le="0.005",code="200"} 0
test_histogram_bucket{le="0.01",code="200"} 0
test_histogram_bucket{le="0.025",code="200"} 0
test_histogram_bucket{le="0.05",code="200"} 0
test_histogram_bucket{le="0.1",code="200"} 0
test_histogram_bucket{le="0.25",code="200"} 0
test_histogram_bucket{le="0.5",code="200"} 2
test_histogram_bucket{le="1",code="200"} 3
test_histogram_bucket{le="2.5",code="200"} 3
test_histogram_bucket{le="5",code="200"} 3
test_histogram_bucket{le="10",code="200"} 3
test_histogram_bucket{le="+Inf",code="200"} 3
test_histogram_sum{code="200"} 1.4
test_histogram_count{code="200"} 3
*/
prom-client-14.1.0/example/histogram-2.js 0000664 0000000 0000000 00000003250 14301147710 0020151 0 ustar 00root root 0000000 0000000 'use strict';
// Histogram
// Single Label
// Multiple Values
const { register, Histogram } = require('..');
const h = new Histogram({
name: 'test_histogram',
help: 'Example of a histogram',
labelNames: ['code'],
});
h.labels('200').observe(0.4);
h.labels('300').observe(0.6);
h.observe({ code: '200' }, 0.4);
register.metrics().then(str => console.log(str));
/*
Output from metrics():
# HELP test_histogram Example of a histogram
# TYPE test_histogram histogram
test_histogram_bucket{le="0.005",code="200"} 0
test_histogram_bucket{le="0.01",code="200"} 0
test_histogram_bucket{le="0.025",code="200"} 0
test_histogram_bucket{le="0.05",code="200"} 0
test_histogram_bucket{le="0.1",code="200"} 0
test_histogram_bucket{le="0.25",code="200"} 0
test_histogram_bucket{le="0.5",code="200"} 2
test_histogram_bucket{le="1",code="200"} 2
test_histogram_bucket{le="2.5",code="200"} 2
test_histogram_bucket{le="5",code="200"} 2
test_histogram_bucket{le="10",code="200"} 2
test_histogram_bucket{le="+Inf",code="200"} 2
test_histogram_sum{code="200"} 0.8
test_histogram_count{code="200"} 2
test_histogram_bucket{le="0.005",code="300"} 0
test_histogram_bucket{le="0.01",code="300"} 0
test_histogram_bucket{le="0.025",code="300"} 0
test_histogram_bucket{le="0.05",code="300"} 0
test_histogram_bucket{le="0.1",code="300"} 0
test_histogram_bucket{le="0.25",code="300"} 0
test_histogram_bucket{le="0.5",code="300"} 0
test_histogram_bucket{le="1",code="300"} 1
test_histogram_bucket{le="2.5",code="300"} 1
test_histogram_bucket{le="5",code="300"} 1
test_histogram_bucket{le="10",code="300"} 1
test_histogram_bucket{le="+Inf",code="300"} 1
test_histogram_sum{code="300"} 0.6
test_histogram_count{code="300"} 1
*/
prom-client-14.1.0/example/histogram-3.js 0000664 0000000 0000000 00000002453 14301147710 0020156 0 ustar 00root root 0000000 0000000 'use strict';
// Histogram
// Multiple Labels
// Single Value per Label
const { register, Histogram } = require('..');
const h = new Histogram({
name: 'test_histogram',
help: 'Example of a histogram',
labelNames: ['code', 'color'],
});
h.labels('200', 'blue').observe(0.4);
h.labels('200', 'blue').observe(0.6);
h.observe({ code: '200', color: 'blue' }, 0.4);
register.metrics().then(str => console.log(str));
/*
Output from metrics():
# HELP test_histogram Example of a histogram
# TYPE test_histogram histogram
test_histogram_bucket{le="0.005",code="200",color="blue"} 0
test_histogram_bucket{le="0.01",code="200",color="blue"} 0
test_histogram_bucket{le="0.025",code="200",color="blue"} 0
test_histogram_bucket{le="0.05",code="200",color="blue"} 0
test_histogram_bucket{le="0.1",code="200",color="blue"} 0
test_histogram_bucket{le="0.25",code="200",color="blue"} 0
test_histogram_bucket{le="0.5",code="200",color="blue"} 2
test_histogram_bucket{le="1",code="200",color="blue"} 3
test_histogram_bucket{le="2.5",code="200",color="blue"} 3
test_histogram_bucket{le="5",code="200",color="blue"} 3
test_histogram_bucket{le="10",code="200",color="blue"} 3
test_histogram_bucket{le="+Inf",code="200",color="blue"} 3
test_histogram_sum{code="200",color="blue"} 1.4
test_histogram_count{code="200",color="blue"} 3
*/
prom-client-14.1.0/example/histogram-4.js 0000664 0000000 0000000 00000007174 14301147710 0020164 0 ustar 00root root 0000000 0000000 'use strict';
// Histogram
// Multiple Labels
// Multiple Values per Label
const { register, Histogram } = require('..');
const h = new Histogram({
name: 'test_histogram',
help: 'Example of a histogram',
labelNames: ['code', 'color'],
});
h.labels('200', 'blue').observe(0.4);
h.labels('300', 'red').observe(0.6);
h.labels('300', 'blue').observe(0.4);
h.labels('200', 'red').observe(0.6);
register.metrics().then(str => console.log(str));
/*
Output from metrics():
# HELP test_histogram Example of a histogram
# TYPE test_histogram histogram
test_histogram_bucket{le="0.005",code="200",color="blue"} 0
test_histogram_bucket{le="0.01",code="200",color="blue"} 0
test_histogram_bucket{le="0.025",code="200",color="blue"} 0
test_histogram_bucket{le="0.05",code="200",color="blue"} 0
test_histogram_bucket{le="0.1",code="200",color="blue"} 0
test_histogram_bucket{le="0.25",code="200",color="blue"} 0
test_histogram_bucket{le="0.5",code="200",color="blue"} 1
test_histogram_bucket{le="1",code="200",color="blue"} 1
test_histogram_bucket{le="2.5",code="200",color="blue"} 1
test_histogram_bucket{le="5",code="200",color="blue"} 1
test_histogram_bucket{le="10",code="200",color="blue"} 1
test_histogram_bucket{le="+Inf",code="200",color="blue"} 1
test_histogram_sum{code="200",color="blue"} 0.4
test_histogram_count{code="200",color="blue"} 1
test_histogram_bucket{le="0.005",code="300",color="red"} 0
test_histogram_bucket{le="0.01",code="300",color="red"} 0
test_histogram_bucket{le="0.025",code="300",color="red"} 0
test_histogram_bucket{le="0.05",code="300",color="red"} 0
test_histogram_bucket{le="0.1",code="300",color="red"} 0
test_histogram_bucket{le="0.25",code="300",color="red"} 0
test_histogram_bucket{le="0.5",code="300",color="red"} 0
test_histogram_bucket{le="1",code="300",color="red"} 1
test_histogram_bucket{le="2.5",code="300",color="red"} 1
test_histogram_bucket{le="5",code="300",color="red"} 1
test_histogram_bucket{le="10",code="300",color="red"} 1
test_histogram_bucket{le="+Inf",code="300",color="red"} 1
test_histogram_sum{code="300",color="red"} 0.6
test_histogram_count{code="300",color="red"} 1
test_histogram_bucket{le="0.005",code="300",color="blue"} 0
test_histogram_bucket{le="0.01",code="300",color="blue"} 0
test_histogram_bucket{le="0.025",code="300",color="blue"} 0
test_histogram_bucket{le="0.05",code="300",color="blue"} 0
test_histogram_bucket{le="0.1",code="300",color="blue"} 0
test_histogram_bucket{le="0.25",code="300",color="blue"} 0
test_histogram_bucket{le="0.5",code="300",color="blue"} 1
test_histogram_bucket{le="1",code="300",color="blue"} 1
test_histogram_bucket{le="2.5",code="300",color="blue"} 1
test_histogram_bucket{le="5",code="300",color="blue"} 1
test_histogram_bucket{le="10",code="300",color="blue"} 1
test_histogram_bucket{le="+Inf",code="300",color="blue"} 1
test_histogram_sum{code="300",color="blue"} 0.4
test_histogram_count{code="300",color="blue"} 1
test_histogram_bucket{le="0.005",code="200",color="red"} 0
test_histogram_bucket{le="0.01",code="200",color="red"} 0
test_histogram_bucket{le="0.025",code="200",color="red"} 0
test_histogram_bucket{le="0.05",code="200",color="red"} 0
test_histogram_bucket{le="0.1",code="200",color="red"} 0
test_histogram_bucket{le="0.25",code="200",color="red"} 0
test_histogram_bucket{le="0.5",code="200",color="red"} 0
test_histogram_bucket{le="1",code="200",color="red"} 1
test_histogram_bucket{le="2.5",code="200",color="red"} 1
test_histogram_bucket{le="5",code="200",color="red"} 1
test_histogram_bucket{le="10",code="200",color="red"} 1
test_histogram_bucket{le="+Inf",code="200",color="red"} 1
test_histogram_sum{code="200",color="red"} 0.6
test_histogram_count{code="200",color="red"} 1
*/
prom-client-14.1.0/example/pushgateway.js 0000664 0000000 0000000 00000001220 14301147710 0020351 0 ustar 00root root 0000000 0000000 'use strict';
const client = require('../index');
function run() {
const Registry = client.Registry;
const register = new Registry();
const gateway = new client.Pushgateway('http://127.0.0.1:9091', [], register);
const prefix = 'dummy_prefix_name';
const test = new client.Counter({
name: `${prefix}_test`,
help: `${prefix}_test`,
registers: [register],
});
register.registerMetric(test);
test.inc(10);
return gateway
.push({ jobName: prefix })
.then(({ resp, body }) => {
console.log(`Body: ${body}`);
console.log(`Response status: ${resp.statusCode}`);
})
.catch(err => {
console.log(`Error: ${err}`);
});
}
run();
prom-client-14.1.0/example/server.js 0000664 0000000 0000000 00000004532 14301147710 0017327 0 ustar 00root root 0000000 0000000 'use strict';
const express = require('express');
const cluster = require('cluster');
const server = express();
const register = require('../').register;
// Enable collection of default metrics
require('../').collectDefaultMetrics({
gcDurationBuckets: [0.001, 0.01, 0.1, 1, 2, 5], // These are the default buckets.
});
// Create custom metrics
const Histogram = require('../').Histogram;
const h = new Histogram({
name: 'test_histogram',
help: 'Example of a histogram',
labelNames: ['code'],
});
const Counter = require('../').Counter;
const c = new Counter({
name: 'test_counter',
help: 'Example of a counter',
labelNames: ['code'],
});
new Counter({
name: 'scrape_counter',
help: 'Number of scrapes (example of a counter with a collect fn)',
collect() {
// collect is invoked each time `register.metrics()` is called.
this.inc();
},
});
const Gauge = require('../').Gauge;
const g = new Gauge({
name: 'test_gauge',
help: 'Example of a gauge',
labelNames: ['method', 'code'],
});
// Set metric values to some random values for demonstration
setTimeout(() => {
h.labels('200').observe(Math.random());
h.labels('300').observe(Math.random());
}, 10);
setInterval(() => {
c.inc({ code: 200 });
}, 5000);
setInterval(() => {
c.inc({ code: 400 });
}, 2000);
setInterval(() => {
c.inc();
}, 2000);
setInterval(() => {
g.set({ method: 'get', code: 200 }, Math.random());
g.set(Math.random());
g.labels('post', '300').inc();
}, 100);
if (cluster.isWorker) {
// Expose some worker-specific metric as an example
setInterval(() => {
c.inc({ code: `worker_${cluster.worker.id}` });
}, 2000);
}
const t = [];
setInterval(() => {
for (let i = 0; i < 100; i++) {
t.push(new Date());
}
}, 10);
setInterval(() => {
while (t.length > 0) {
t.pop();
}
});
// Setup server to Prometheus scrapes:
server.get('/metrics', async (req, res) => {
try {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
} catch (ex) {
res.status(500).end(ex);
}
});
server.get('/metrics/counter', async (req, res) => {
try {
res.set('Content-Type', register.contentType);
res.end(await register.getSingleMetricAsString('test_counter'));
} catch (ex) {
res.status(500).end(ex);
}
});
const port = process.env.PORT || 3000;
console.log(
`Server listening to ${port}, metrics exposed on /metrics endpoint`,
);
server.listen(port);
prom-client-14.1.0/index.d.ts 0000664 0000000 0000000 00000037466 14301147710 0015745 0 ustar 00root root 0000000 0000000 // Type definitions for prom-client
// Definitions by: Simon Nyberg http://twitter.com/siimon_nyberg
/**
* Container for all registered metrics
*/
export class Registry {
/**
* Get string representation for all metrics
*/
metrics(): Promise;
/**
* Remove all metrics from the registry
*/
clear(): void;
/**
* Reset all metrics in the registry
*/
resetMetrics(): void;
/**
* Register metric to register
* @param metric Metric to add to register
*/
registerMetric(metric: Metric): void;
/**
* Get all metrics as objects
*/
getMetricsAsJSON(): Promise;
/**
* Get all metrics as objects
*/
getMetricsAsArray(): metric[];
/**
* Remove a single metric
* @param name The name of the metric to remove
*/
removeSingleMetric(name: string): void;
/**
* Get a single metric
* @param name The name of the metric
*/
getSingleMetric(name: string): Metric | undefined;
/**
* Set static labels to every metric emitted by this registry
* @param labels of name/value pairs:
* { defaultLabel: "value", anotherLabel: "value 2" }
*/
setDefaultLabels(labels: Object): void;
/**
* Get a string representation of a single metric by name
* @param name The name of the metric
*/
getSingleMetricAsString(name: string): Promise;
/**
* Gets the Content-Type of the metrics for use in the response headers.
*/
contentType: string;
/**
* Merge registers
* @param registers The registers you want to merge together
*/
static merge(registers: Registry[]): Registry;
}
export type Collector = () => void;
/**
* The register that contains all metrics
*/
export const register: Registry;
/**
* The Content-Type of the metrics for use in the response headers.
*/
export const contentType: string;
export class AggregatorRegistry extends Registry {
/**
* Gets aggregated metrics for all workers.
* @return {Promise} Promise that resolves with the aggregated
* metrics.
*/
clusterMetrics(): Promise;
/**
* Creates a new Registry instance from an array of metrics that were
* created by `registry.getMetricsAsJSON()`. Metrics are aggregated using
* the method specified by their `aggregator` property, or by summation if
* `aggregator` is undefined.
* @param {Array} metricsArr Array of metrics, each of which created by
* `registry.getMetricsAsJSON()`.
* @return {Registry} aggregated registry.
*/
static aggregate(metricsArr: Array