1Metrics::Any::CollectorU(s3e)r Contributed Perl DocumentaMteitornics::Any::Collector(3)
2
3
4

NAME

6       "Metrics::Any::Collector" - module-side of the monitoring metrics
7       reporting API
8

SYNOPSIS

10          use Metrics::Any '$metrics',
11             strict => 0,
12             name_prefix => [ 'my_module_name' ];
13
14          sub do_thing {
15             $metrics->inc_counter( 'things_done' );
16          }
17

DESCRIPTION

19       Instances of this class provide an API for individual modules to
20       declare metadata about metrics they will report, and to report
21       individual values or observations on those metrics. An instance should
22       be obtained for a reporting module by the "use Metrics::Any" statement.
23
24       The collector acts primarily as a proxy for the application's
25       configured Metrics::Any::Adapter instance. The proxy will lazily create
26       an adapter when required to first actually report a metric value, but
27       until then any metadata stored by any of the "make_*" methods will not
28       create one. This lazy deferral allows a certain amount of flexibility
29       with module load order and application startup. By carefully writing
30       module code to not report any values of metrics until the main activity
31       has actually begin, it should be possible to allow programs to
32       configure the metric reporting in a flexible manner during program
33       startup.
34
35   Batch-Mode Reporting
36       Some adapters may support an optional API for implementing metrics in a
37       more high-performance manner, suitable for use in low-level (perhaps
38       even XS) code that might be invoked at high speed or many times over.
39
40       Such code often needs to keep simple counters of particular events that
41       happen a lot. Rather than incurring the cost of a full stack of method
42       calls into the collector and adapter implementation on every event, the
43       instrumented code can register a callback function that the adapter
44       will call on some schedule, that will report the actual metrics. In the
45       meantime, the instrumented code can maintain its own counters of
46       events, using plain Perl scalars (or native integers in XS code), to be
47       reported in bulk when required. This reduces the overall CPU cost
48       involved in collecting metrics.
49
50       This is most effective with pull-based adapters such as Test or
51       Prometheus, where the callback might only need to be invoked at the end
52       of a test run, or when the prometheus server polls the "/metrics" HTTP
53       endpoint.
54
55          my $evcounter = 0;
56
57          $metrics->add_batch_mode_callback( sub {
58             $metrics->inc_counter_by( events => $evcounter );
59             $evcounter = 0;
60          } );
61
62          sub do_thing {
63             $evcounter++;
64             ...
65          }
66
67       Because not every adapter may implement this mode, instrumented code
68       should be prepared to fall back on the regular API to report its
69       counters.
70
71          my $evcounter = 0;
72
73          my $use_batch = $metrics->add_batch_mode_callback( sub {
74             $metrics->inc_counter_by( events => $evcounter );
75             $evcounter = 0;
76          } );
77
78          sub do_thing {
79             $use_batch ? $evcounter++ : $metrics->inc_counter( events => );
80             ...
81          }
82
83       Each adapter implementation should document if and how it handles batch
84       mode.
85

ENVIRONMENT

87   METRICS_ANY_DISABLE
88       Since version 0.07.
89
90       Provides a list of packages and namespaces in which to disable
91       Metrics::Any reporting entirely.
92
93       This variable gives a comma-separated list of name patterns. Patterns
94       may end with "::*", where they will match any package whose name starts
95       with that prefix, or they may be literal package names. If any code in
96       matching packages attempts to use Metrics::Any::Collector to report
97       metrics, that code will be given a "Null" adapter, and no metrics will
98       be reported from here.
99
100       For example, to disable the metrics that "Net::Async::HTTP::Server"
101       itself creates when exporting Prometheus metrics:
102
103          $ METRICS_ANY_DISABLE=Net::Async::HTTP::Server ./program.pl
104

ARGUMENTS

106   name_prefix
107       Since version 0.05.
108
109       Optional prefix to prepend to any name provided to the "make_*"
110       functions.
111
112       If set, this value and the registered names must be given as array
113       references, not simple strings.
114
115          use Metrics::Any '$metrics', name_prefix => [qw( my_program_name )];
116
117          $metrics->make_counter( events =>
118             name => [ "events" ],
119          );
120
121          # Will create a counter named ["my_program_name", "events"] formed by the
122          # adapter.
123
124   strict
125       Since version 0.05.
126
127       Optional boolean which controls whether metrics must be registered by a
128       "make_" method before they can be used (when true), or whether to
129       attempt lazily registering them when first encountered by a reporting
130       method (when false).
131
132       When strict mode is off and a reporting method (e.g. "inc_counter") is
133       invoked on an unrecognised handle, it will be lazily registered. If the
134       metric is reported with values, an attempt is made to determine what
135       the list of label names is; which will depend on the form the label
136       values are given in.  Labels passed by array reference, or by hash
137       reference for a single label will work fine. If a hash reference is
138       passed with multiple keys, a warning is printed that the order may not
139       be reliable. Finally, for (discouraged) flat lists of values directly
140       it is not possible to recover label name information so an exception is
141       thrown.
142
143       For this reason, when operating with strict mode off, it is recommended
144       always to use the array reference form of supplying labels, to ensure
145       they are registered correctly.
146
147       In the current version this parameter defaults true, and thus all
148       metrics must be registered in advance. This may be changed in a future
149       version for convenience in smaller modules, so paranoid authors should
150       set it explicitly:
151
152          use Metrics::Any::Adapter '$metrics', strict => 1;
153
154       If strict mode is switched off, it is recommended to set a name prefix
155       to ensure that lazily-registered metrics will at least have a useful
156       name.
157

BOOLEAN OVERRIDE

159       Instances of this class override boolean truth testing. They are
160       usually true, except in the case that an adapter has already been
161       created and it is the Null type. This allows modules to efficiently
162       test whether to report metrics at all by using code such as
163
164          if( $metrics ) {
165             $metrics->inc_counter( name => some_expensive_function() );
166          }
167
168       While the Null adapter will simply ignore any of the methods invoked on
169       it, without this conditional test the caller would otherwise still have
170       to calculate the value that won't be used. This structure allows the
171       calculation to be avoided if metrics are not in use.
172

METHODS

174   package
175          $package = $metrics->package
176
177       Returns the package name that created the collector; the package in
178       which the
179
180          use Metrics::Any '$metrics';
181
182       statement was invoked.
183
184   add_batch_mode_callback
185          $ok = $metrics->add_batch_mode_callback( sub { ... } )
186
187       Since version 0.09.
188
189       If batch mode is supported on the underlying adapter, adds another
190       callback to its list of callbacks, to be invoked when it wishes to
191       collect more metrics; if this is supported then the method returns a
192       true value.
193
194       If batch mode is not supported, returns false.
195

METRIC TYPES

197       Each type of metric is created by one of the "make_*" methods. They all
198       take the following common arguments:
199
200       name => ARRAY[ STRING ] | STRING
201           Optional. An array of string parts, or a plain string name to use
202           for reporting this metric to its upstream service.
203
204           Modules should preferrably use an array of string parts to specify
205           their metric names, as different adapter types may have different
206           ways to represent this hierarchially. Base-level parts of the name
207           should come first, followed by more specific parts. It is common
208           for related metrics to be grouped by name having identical prefixes
209           but differing only in the final part.
210
211           The name is optional; if unspecified then the handle will be used
212           to form the name, combined with a "name_prefix" argument if one was
213           set for the package.
214
215       description => STRING
216           Optional human-readable description. May be used for debugging or
217           other purposes.
218
219       labels => ARRAY[ STRING ]
220           Optional reference to an array of string names to use as label
221           names.
222
223           A labelled metric will expect to receive additional information in
224           its reporting method to give values for these labels. This
225           information should be in either an even-length array reference of
226           name/value pairs, or a hash reference. E.g.
227
228              $metrics->inc_counter( handle => [ labelname => $labelvalue ] );
229              $metrics->inc_counter( handle => { labelname => $labelvalue } );
230
231           A legacy form where a plain list of values is passed, each
232           corresponding to a named label in the same order, is currently
233           accepted but discouraged in favour of the above forms.
234
235              $metrics->inc_counter( handle => $labelvalue );
236
237           Note that not all metric reporting adapters may be able to
238           represent all of the labels. Each should document what its
239           behaviour will be.
240
241   Counter
242       The "make_counter" method creates a new metric which counts occurances
243       of some event within the application. Its value begins at zero, and can
244       be incremented by "inc_counter" whenever the event occurs.
245
246       Some counters may simple count occurances of events, while others may
247       count in other units, for example counts of bytes. Adapters may make
248       use of the "units" parameter of the distribution to perform some kind
249       of adapter-specific behaviour. The following units are suggested:
250
251       bytes
252
253       Observations give sizes in bytes (perhaps memory buffer or network
254       message sizes), and should be integers.
255
256   make_counter
257          $collector->make_counter( $handle, %args )
258
259       Requests the creation of a new counter metric. The $handle name should
260       be unique within the collector instance, though does not need to be
261       unique across the entire program, as it will be namespaced by the
262       collector instance.
263
264       The following extra arguments may be passed:
265
266       units => STRING
267           A hint to the adapter about what kind of measurements are being
268           observed, so it might take specific behaviour.
269
270   inc_counter
271          $collector->inc_counter( $handle, $labels )
272
273       Reports that the counter metric value be incremented by one. The
274       $handle name must match one earlier created by "make_counter".
275
276   inc_counter_by
277          $collector->inc_counter_by( $handle, $amount, $labels )
278
279       Reports that a counter metric value be incremented by some specified
280       value.
281
282   Distribution
283       The "make_distribution" method creates a new metric which counts
284       individual observations of some numerical quantity (which may or may
285       not be integral).  New observations can be added by the
286       "report_distribution" method.
287
288       Some adapter types may only store an aggregated total; others may store
289       some sort of statistical breakdown, either total + count, or a bucketed
290       histogram.  The specific adapter documentation should explain how it
291       handles distributions.
292
293       Adapters may make use of the "units" parameter of the distribution to
294       perform some kind of adapter-specific behaviour. The following units
295       are suggested:
296
297       bytes
298
299       Observations give sizes in bytes (perhaps memory buffer or network
300       message sizes), and should be integers.
301
302       seconds
303
304       Observations give durations in seconds.
305
306   make_distribution
307          $collector->make_distribution( $handle, %args )
308
309       Requests the creation of a new distribution metric.
310
311       The following extra arguments may be passed:
312
313       units => STRING
314           A hint to the adapter about what kind of measurements are being
315           observed, so it might take specific behaviour. If unspecified, a
316           default of "bytes" will apply.
317
318   report_distribution
319          $collector->report_distribution( $handle, $amount, $labels )
320
321       Since version 0.05.
322
323       Reports a new observation for the distribution metric. The $handle name
324       must match one earlier created by "make_distribution". The $amount may
325       be interpreted by the adapter depending on the defined "units" type for
326       the distribution.
327
328       This method used to be called "inc_distribution_by" and is currently
329       still available as an alias.
330
331   Gauge
332       The "make_gauge" method creates a new metric which reports on the
333       instantaneous value of some measurable quantity. Unlike the other
334       metric types this does not have to only increment forwards when certain
335       events occur, but can measure a quantity that may both increase and
336       decrease over time; such as the number some kind of object in memory,
337       or the size of some data structure.
338
339       As an alternative to incrementing or decrementing the value when
340       particular events occur, the absolute value of the gauge can also be
341       set directly.
342
343   make_gauge
344          $collector->make_gauge( $handle, %args )
345
346       Requests the creation of a new gauge metric.
347
348   inc_gauge
349          $collector->inc_gauge( $handle, $labels )
350
351   dec_gauge
352          $collector->dec_gauge( $handle, $labels )
353
354   inc_gauge_by
355          $collector->inc_gauge_by( $handle, $amount, $labels )
356
357   dec_gauge_by
358          $collector->dec_gauge_by( $handle, $amount, $labels )
359
360       Reports that the observed value of the gauge has increased or decreased
361       by the given amount (or 1).
362
363   set_gauge_to
364          $collector->set_gauge_to( $handle, $amount, $labels )
365
366       Reports that the observed value of the gauge is now the given amount.
367
368       The $handle name must match one earlier created by "make_gauge".
369
370   Timer
371       The "make_timer" method creates a new metric which measures durations
372       of time consumed by the application. New observations of durations can
373       be added by the "report_timer" method.
374
375       Timer metrics may be handled by the adapter similarly to distribution
376       metrics.  Moreover, adapters may choose to implement timers as
377       distributions with units of "seconds".
378
379   make_timer
380          $collector->make_timer( $handle, %args )
381
382       Requests the creation of a new timer metric.
383
384   report_timer
385          $collector->report_timer( $handle, $duration, $labels )
386
387       Since version 0.05.
388
389       Reports a new duration for the timer metric. The $handle name must
390       match one earlier created by "make_timer". The $duration gives a time
391       measured in seconds, and may be fractional.
392
393       This method used to called "inc_timer_by" and is currently still
394       available as an alias.
395

AUTHOR

397       Paul Evans <leonerd@leonerd.org.uk>
398
399
400
401perl v5.36.0                      2023-01-20        Metrics::Any::Collector(3)
Impressum