Metrics-Any-0.07000755001750001750 014076045756 12332 5ustar00leoleo000000000000Metrics-Any-0.07/Build.PL000444001750001750 102214076045756 13756 0ustar00leoleo000000000000use v5; use strict; use warnings; use Module::Build; my $build = Module::Build->new( module_name => 'Metrics::Any', requires => { 'perl' => '5.014', # //, package NAME {BLOCK} 'List::Util' => '1.29', # core since 5.20 }, test_requires => { 'Test::Fatal' => 0, 'Test::More' => '0.88', # done_testing }, configure_requires => { 'Module::Build' => '0.4004', # test_requires }, license => 'perl', create_license => 1, create_readme => 1, ); $build->create_build_script; Metrics-Any-0.07/Changes000444001750001750 441714076045756 13770 0ustar00leoleo000000000000Revision history for Metrics-Any 0.07 2021-07-21 [CHANGES] * Added METRICS_ANY_DISABLE environment variable (RT137911) * Added `SEE ALSO` docs section (RT132901) 0.06 2020-07-04 [CHANGES] * Added a shareable base class for adapters that store metric values * Pass collector argument into adapter ->make_* methods * Added $collector->package accessor * Added explicit use VERSION declarations to every perl file [BUGFIXES] * Ensure that collector will stringify to a nonconfusing result rather than '1' due to its boolify overload 0.05 2020-05-13 [CHANGES] * Renamed distribution and timer reporting methods to more clearly convey their operation; now named ->report_distribution and ->report_timer * Optional name prefix in Collector to simplify use in modules * Use metric handle (combined with prefix) if no other name supplied * Nicer API for supplying label values to reporting methods * Check that reported label names match the declared names * Support non-strict mode where metrics are lazily registered when first reported * Added Metrics::Any::Adapter::Tee * More flexible parsing of METRICS_ANY_ADAPTER variable 0.04 2020-05-12 [CHANGES] * Add documentation to Metrics::Any::Adapter * Support METRICS_ANY_ADAPTER environment variable to override Null default * Added Metrics::Any::Adapter::File and ::Stderr * Metrics::Any::Adapter::Test now checks that reported metric types match those they were declared as 0.03 2020-04-29 [CHANGES] * Support and encourage hierarchial metric names to be specified by arrayrefs of string parts * Suggest `units` parameter to ->make_counter * Give Collector a boolean overload making it appear false if it has the Null adapter 0.02 2020-04-28 [CHANGES] * Add new metric types: distribution, gauge, timer * Pass additional arguments from `use Metrics::Any::Adapter` statement into adapter constructor 0.01 2020-04-27 First version, released on an unsuspecting world. Metrics-Any-0.07/LICENSE000444001750001750 4376214076045756 13530 0ustar00leoleo000000000000This software is copyright (c) 2021 by Paul Evans . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2021 by Paul Evans . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2021 by Paul Evans . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Metrics-Any-0.07/MANIFEST000444001750001750 114114076045756 13615 0ustar00leoleo000000000000Build.PL Changes lib/Metrics/Any.pm lib/Metrics/Any/Adapter.pm lib/Metrics/Any/Adapter/File.pm lib/Metrics/Any/Adapter/Null.pm lib/Metrics/Any/Adapter/Stderr.pm lib/Metrics/Any/Adapter/Tee.pm lib/Metrics/Any/Adapter/Test.pm lib/Metrics/Any/AdapterBase/Stored.pm lib/Metrics/Any/Collector.pm LICENSE MANIFEST This list of files META.json META.yml README t/00use.t t/01collector.t t/02adapter-early.t t/03adapter-late.t t/04adapter-string-parse.t t/10adapter-null.t t/11adapter-file.t t/12adapter-tee.t t/13adapter-stored.t t/14adapter-test.t t/20name-prefix.t t/21nonstrict.t t/22disable-package.t t/99pod.t Metrics-Any-0.07/META.json000444001750001750 412314076045756 14110 0ustar00leoleo000000000000{ "abstract" : "abstract collection of monitoring metrics", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4231", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Metrics-Any", "prereqs" : { "configure" : { "requires" : { "Module::Build" : "0.4004" } }, "runtime" : { "requires" : { "List::Util" : "1.29", "perl" : "5.014" } }, "test" : { "requires" : { "Test::Fatal" : "0", "Test::More" : "0.88" } } }, "provides" : { "Metrics::Any" : { "file" : "lib/Metrics/Any.pm", "version" : "0.07" }, "Metrics::Any::Adapter" : { "file" : "lib/Metrics/Any/Adapter.pm", "version" : "0.07" }, "Metrics::Any::Adapter::File" : { "file" : "lib/Metrics/Any/Adapter/File.pm", "version" : "0.07" }, "Metrics::Any::Adapter::Null" : { "file" : "lib/Metrics/Any/Adapter/Null.pm", "version" : "0.07" }, "Metrics::Any::Adapter::Stderr" : { "file" : "lib/Metrics/Any/Adapter/Stderr.pm", "version" : "0.07" }, "Metrics::Any::Adapter::Tee" : { "file" : "lib/Metrics/Any/Adapter/Tee.pm", "version" : "0.07" }, "Metrics::Any::Adapter::Test" : { "file" : "lib/Metrics/Any/Adapter/Test.pm", "version" : "0.07" }, "Metrics::Any::AdapterBase::Stored" : { "file" : "lib/Metrics/Any/AdapterBase/Stored.pm", "version" : "0.07" }, "Metrics::Any::Collector" : { "file" : "lib/Metrics/Any/Collector.pm", "version" : "0.07" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ] }, "version" : "0.07", "x_serialization_backend" : "JSON::PP version 4.05" } Metrics-Any-0.07/META.yml000444001750001750 262014076045756 13740 0ustar00leoleo000000000000--- abstract: 'abstract collection of monitoring metrics' author: - 'Paul Evans ' build_requires: Test::Fatal: '0' Test::More: '0.88' configure_requires: Module::Build: '0.4004' dynamic_config: 1 generated_by: 'Module::Build version 0.4231, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Metrics-Any provides: Metrics::Any: file: lib/Metrics/Any.pm version: '0.07' Metrics::Any::Adapter: file: lib/Metrics/Any/Adapter.pm version: '0.07' Metrics::Any::Adapter::File: file: lib/Metrics/Any/Adapter/File.pm version: '0.07' Metrics::Any::Adapter::Null: file: lib/Metrics/Any/Adapter/Null.pm version: '0.07' Metrics::Any::Adapter::Stderr: file: lib/Metrics/Any/Adapter/Stderr.pm version: '0.07' Metrics::Any::Adapter::Tee: file: lib/Metrics/Any/Adapter/Tee.pm version: '0.07' Metrics::Any::Adapter::Test: file: lib/Metrics/Any/Adapter/Test.pm version: '0.07' Metrics::Any::AdapterBase::Stored: file: lib/Metrics/Any/AdapterBase/Stored.pm version: '0.07' Metrics::Any::Collector: file: lib/Metrics/Any/Collector.pm version: '0.07' requires: List::Util: '1.29' perl: '5.014' resources: license: http://dev.perl.org/licenses/ version: '0.07' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Metrics-Any-0.07/README000444001750001750 613514076045756 13354 0ustar00leoleo000000000000NAME Metrics::Any - abstract collection of monitoring metrics SYNOPSIS In a module: use Metrics::Any '$metrics', strict => 0, name_prefix => [ 'my_module_name' ]; sub do_thing { $metrics->inc_counter( 'things_done' ); } In a program or top-level program-like module: use Metrics::Any::Adapter 'Prometheus'; DESCRIPTION Provides a central location for modules to report monitoring metrics, such as counters of the number of times interesting events have happened, and programs to collect up and send those metrics to monitoring services. Inspired by Log::Any, this module splits the overall problem into two sides. Modules wishing to provide metrics for monitoring purposes can use the use Metrics::Any statement to obtain a collector into which they can report metric events. By default this collector doesn't actually do anything, so modules can easily use it without adding extra specific dependencies for specific reporting. A program using one or more such modules can apply a different policy and request a particular adapter implementation in order to actually report these metrics to some external system, by using the use Metrics::Any::Adapter statement. This separation of concerns allows module authors to write code which will report metrics without needing to care about the exact mechanism of that reporting (as well as to write code which does not itself depend on the code required to perform that reporting). Future Direction At present this interface is in an early state of experimentation. The API is fairly specifically-shaped for Net::Prometheus at present, but it is hoped with more adapter implementations (such as for statsd or OpenTelemetry) the API shapes can be expanded and made more generic to support a wider variety of reporting mechanisms. As a result, any API details for now should be considered experimental and subject to change in later versions. USE STATEMENT For a module to use this facility, the use statement importing it should give the name of a variable (as a plain string) to store the collector for that package. use Metrics::Any '$metrics'; This variable will be created in the calling package and populated with an instance of Metrics::Any::Collector. The module can then use the collector API to declare new metrics, and eventually report values into them. Note that the variable is created at the package level; any other packages within the same file will not see it and will have to declare their own. SEE ALSO * The name and overall concept of this module is heavily influenced by a similar module for logging, Log::Any. * For reporting metrics to one specific target collector, there are specific modules for systems like statsd (Net::Statsd, Net::Async::Statsd) or prometheus (Prometheus::Tiny, Net::Prometheus). * There is also a similar concept in Measure::Everything. AUTHOR Paul Evans Metrics-Any-0.07/lib000755001750001750 014076045756 13100 5ustar00leoleo000000000000Metrics-Any-0.07/lib/Metrics000755001750001750 014076045756 14506 5ustar00leoleo000000000000Metrics-Any-0.07/lib/Metrics/Any.pm000444001750001750 740714076045756 15740 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020-2021 -- leonerd@leonerd.org.uk package Metrics::Any 0.07; use v5.14; use warnings; use Metrics::Any::Collector; =head1 NAME C - abstract collection of monitoring metrics =head1 SYNOPSIS In a module: use Metrics::Any '$metrics', strict => 0, name_prefix => [ 'my_module_name' ]; sub do_thing { $metrics->inc_counter( 'things_done' ); } In a program or top-level program-like module: use Metrics::Any::Adapter 'Prometheus'; =head1 DESCRIPTION Provides a central location for modules to report monitoring metrics, such as counters of the number of times interesting events have happened, and programs to collect up and send those metrics to monitoring services. Inspired by L, this module splits the overall problem into two sides. Modules wishing to provide metrics for monitoring purposes can use the C statement to obtain a I into which they can report metric events. By default this collector doesn't actually do anything, so modules can easily use it without adding extra specific dependencies for specific reporting. A program using one or more such modules can apply a different policy and request a particular I implementation in order to actually report these metrics to some external system, by using the C statement. This separation of concerns allows module authors to write code which will report metrics without needing to care about the exact mechanism of that reporting (as well as to write code which does not itself depend on the code required to perform that reporting). =head2 Future Direction At present this interface is in an early state of experimentation. The API is fairly specifically-shaped for L at present, but it is hoped with more adapter implementations (such as for statsd or OpenTelemetry) the API shapes can be expanded and made more generic to support a wider variety of reporting mechanisms. As a result, any API details for now should be considered experimental and subject to change in later versions. =cut =head1 USE STATEMENT For a module to use this facility, the C statement importing it should give the name of a variable (as a plain string) to store the collector for that package. use Metrics::Any '$metrics'; This variable will be created in the calling package and populated with an instance of L. The module can then use the collector API to declare new metrics, and eventually report values into them. Note that the variable is created at the package level; any other packages within the same file will not see it and will have to declare their own. =cut sub import { my $pkg = shift; my $caller = caller; $pkg->import_into( $caller, @_ ); } my %collector_for_package; sub import_into { my ( $pkg, $caller, @args ) = @_; my $varname = $1 and shift @args if @args and $args[0] =~ m/^\$(.*)$/; my $collector = $collector_for_package{$caller} //= Metrics::Any::Collector->new( $caller, @args ); if( defined $varname ) { no strict 'refs'; *{"${caller}::${varname}"} = \$collector; } } =head1 SEE ALSO =over 4 =item * The name and overall concept of this module is heavily influenced by a similar module for logging, L. =item * For reporting metrics to one specific target collector, there are specific modules for systems like F (L, L) or F (L, L). =item * There is also a similar concept in L. =back =cut =head1 AUTHOR Paul Evans =cut 0x55AA; Metrics-Any-0.07/lib/Metrics/Any000755001750001750 014076045756 15235 5ustar00leoleo000000000000Metrics-Any-0.07/lib/Metrics/Any/Adapter.pm000444001750001750 744114076045756 17316 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk package Metrics::Any::Adapter 0.07; use v5.14; use warnings; use Carp; =head1 NAME C - set the C adapter for the program =head1 SYNOPSIS In a program or top-level program-like module: use Metrics::Any::Adapter 'Prometheus'; =head1 DESCRIPTION The C statement which loads this module sets the adapter module for L to report metrics generated by an modules the program uses. The first value passed should be a string giving the name of an adapter module, which will be expected under the C-prefix. This module will be loaded and set as the adapter to use. Any additional arguments will be passed to the constructor of the adapter instance. use Metrics::Any::Adapter Custom => "another arg"; # implies $adapter = Metrics::Any::Adapter::Custom->new( "another arg" ); =head1 ENVIRONMENT =head2 METRICS_ANY_ADAPTER I Sets the default adapter type to use if the program has not otherwise requested one. Normally this is set to C, which loads L. By overriding this to a different value, a default adapter can be loaded without modifying the program. This may be useful for example, when running unit tests: $ METRICS_ANY_ADAPTER=Stderr ./Build test Additional arguments can be specified after a colon, separated by commas or equals signs. $ METRICS_ANY_ADAPTER=File:path=metrics.log ./program.pl Note that if a program requests a specific adapter that will override this variable. A limited attempt is made at supporting nested arguments wrapped in square brackets, to allow basic operation of the L adapter via this variable to itself pass arguments into child adapters: $ METRICS_ANY_ADAPTER=Tee:Prometheus,[File:path=metrics.log] perl ... This should be considered a best-effort scenario useful for short-term testing and debugging. For more complex requirements in your script or program, it is better to use the import arguments directly as then any perl data structures can be passed around. =cut sub import { my $pkg = shift; my $caller = caller; $pkg->import_into( $caller, @_ ); } # Class method so Metrics::Any::Adapter::Tee can share it sub split_type_string { shift; my ( $str ) = @_; my ( $type, $argstr ) = split m/[:,]/, $str, 2; my @args; while( length $argstr ) { if( $argstr =~ m/^\[/ ) { # Extract the entire contents of the [...] bracket # TODO: Support deeper nesting somehow? Currently this is only used # for using the Tee adapter via the $METRICS_ANY_ADAPTER variable $argstr =~ s/^\[(.*?)\](?:,|=|$)// or croak "Missing close bracket ] in adapter type string"; push @args, $1; } else { # All up to the next , = or endofstring $argstr =~ s/^(.*?)(?:,|=|$)//; push @args, $1; } } return ( $type, @args ); } sub class_for_type { shift; my ( $type ) = @_; my $class = "Metrics::Any::Adapter::$type"; unless( $class->can( 'new' ) ) { ( my $file = "$class.pm" ) =~ s{::}{/}g; require $file; } return $class; } my $adaptertype = "Null"; my @adapterargs; if( my $val = $ENV{METRICS_ANY_ADAPTER} ) { ( $adaptertype, @adapterargs ) = __PACKAGE__->split_type_string( $val ); } sub import_into { my ( $pkg, $caller, @args ) = @_; ( $adaptertype, @adapterargs ) = @args if @args; } my $adapter; sub adapter { shift; return $adapter //= __PACKAGE__->class_for_type( $adaptertype )->new( @adapterargs ); } =head1 AUTHOR Paul Evans =cut 0x55AA; Metrics-Any-0.07/lib/Metrics/Any/Collector.pm000444001750001750 4720514076045756 17706 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk package Metrics::Any::Collector 0.07; use v5.14; use warnings; use Carp; use Metrics::Any::Adapter; use List::Util 1.29 qw( pairkeys ); =head1 NAME C - module-side of the monitoring metrics reporting API =head1 SYNOPSIS use Metrics::Any '$metrics', strict => 0, name_prefix => [ 'my_module_name' ]; sub do_thing { $metrics->inc_counter( 'things_done' ); } =head1 DESCRIPTION Instances of this class provide an API for individual modules to declare metadata about metrics they will report, and to report individual values or observations on those metrics. An instance should be obtained for a reporting module by the C statement. The collector acts primarily as a proxy for the application's configured L instance. The proxy will lazily create an adapter when required to first actually report a metric value, but until then any metadata stored by any of the C methods will not create one. This lazy deferral allows a certain amount of flexibility with module load order and application startup. By carefully writing module code to not report any values of metrics until the main activity has actually begin, it should be possible to allow programs to configure the metric reporting in a flexible manner during program startup. =head1 ENVIRONMENT =head2 METRICS_ANY_DISABLE I Provides a list of packages and namespaces in which to disable L reporting entirely. This variable gives a comma-separated list of name patterns. Patterns may end with C<::*>, where they will match any package whose name starts with that prefix, or they may be literal package names. If any code in matching packages attempts to use L to report metrics, that code will be given a C adapter, and no metrics will be reported from here. For example, to disable the metrics that C itself creates when exporting Prometheus metrics: $ METRICS_ANY_DISABLE=Net::Async::HTTP::Server ./program.pl =cut # Not public API; used by Metrics::Any::import_into sub new { my $class = shift; my ( $package, %args ) = @_; return bless { package => $package, adapter => undef, deferred => [], name_prefix => $args{name_prefix}, metrics => {}, strict => $args{strict} // 1, }, $class; } my %disable_for_package; my %disable_for_namespace; if( my $val = $ENV{METRICS_ANY_DISABLE} ) { foreach my $pattern ( split m/,/, $val ) { if( $pattern =~ s/\*$// ) { $pattern =~ s/::$//; $disable_for_namespace{$pattern} = 1; } else { $disable_for_package{$pattern} = 1; } } require Metrics::Any::Adapter::Null; } sub _enabled_for_package { my ( $pkg ) = @_; return 0 if $disable_for_package{$pkg}; return 1 unless %disable_for_namespace; do { return 0 if $disable_for_namespace{$pkg}; } while( $pkg =~ s/::[^:]+// ); return 1; } sub adapter { my $self = shift; return $self->{adapter} if $self->{adapter}; my $adapter = $self->{adapter} = ( _enabled_for_package( $self->{package} ) ? Metrics::Any::Adapter->adapter : Metrics::Any::Adapter::Null->new ); foreach my $call ( @{ $self->{deferred} } ) { my ( $method, @args ) = @$call; $adapter->$method( @args ); } undef $self->{deferred}; return $adapter; } sub _adapter_call { my $self = shift; my ( $method, @args ) = @_; if( $self->{adapter} ) { $self->{adapter}->$method( @args ); } else { push @{ $self->{deferred} }, [ $method, @args ]; } } sub _metricname { my $self = shift; my ( $suffix ) = @_; return $suffix unless defined $self->{name_prefix}; return [ @{ $self->{name_prefix} }, @$suffix ]; } sub _labelvalues { my $self = shift; my ( $type, $handle, @args ) = @_; my $meta = $self->{$handle}; if( $meta ) { $meta->[0] eq $type or croak "Metric '$handle' is not a $type"; } elsif( !$self->{strict} ) { my @labelnames; if( !@args ) { # no labels } elsif( ref $args[0] eq "ARRAY" ) { @labelnames = pairkeys @{ $args[0] }; } elsif( ref $args[0] eq "HASH" ) { carp "Lazily creating a labelled metric with multiple labels using a HASH reference yields unreliable label order" if keys %{ $args[0] } > 1; @labelnames = keys %{ $args[0] }; } else { croak "Cannot lazily create a labelled metric from label values specified in a flat list"; } my $make_method = "make_$type"; $self->$make_method( $handle, labels => \@labelnames ); $meta = $self->{$handle}; } else { croak "No such metric '$handle'"; } my ( undef, @labelnames ) = @$meta; if( !@args ) { return; } elsif( ref $args[0] ) { warn "Received additional arguments to metrics reporting function\n" if @args > 1; my ( $arg ) = @args; my %v = ( ref $arg eq "ARRAY" ) ? @$arg : %$arg; my @labelvalues; ( defined $v{$_} or croak "Missing value for label '$_'" ) and push @labelvalues, delete $v{$_} for @labelnames; # Warn but don't complain about extra values carp "Found extra label value for '$_'" for keys %v; return @labelvalues; } else { return @args; } } =head1 ARGUMENTS =head2 name_prefix I Optional prefix to prepend to any name provided to the C functions. If set, this value and the registered names must be given as array references, not simple strings. use Metrics::Any '$metrics', name_prefix => [qw( my_program_name )]; $metrics->make_counter( events => name => [ "events" ], ); # Will create a counter named ["my_program_name", "events"] formed by the # adapter. =head2 strict I Optional boolean which controls whether metrics must be registered by a C method before they can be used (when true), or whether to attempt lazily registering them when first encountered by a reporting method (when false). When strict mode is off and a reporting method (e.g. C) is invoked on an unrecognised handle, it will be lazily registered. If the metric is reported with values, an attempt is made to determine what the list of label names is; which will depend on the form the label values are given in. Labels passed by array reference, or by hash reference for a single label will work fine. If a hash reference is passed with multiple keys, a warning is printed that the order may not be reliable. Finally, for (discouraged) flat lists of values directly it is not possible to recover label name information so an exception is thrown. For this reason, when operating with strict mode off, it is recommended always to use the array reference form of supplying labels, to ensure they are registered correctly. In the current version this parameter defaults true, and thus all metrics must be registered in advance. This may be changed in a future version for convenience in smaller modules, so paranoid authors should set it explicitly: use Metrics::Any::Adapter '$metrics', strict => 1; If strict mode is switched off, it is recommended to set a name prefix to ensure that lazily-registered metrics will at least have a useful name. =cut =head1 BOOLEAN OVERRIDE Instances of this class override boolean truth testing. They are usually true, except in the case that an adapter has already been created and it is the Null type. This allows modules to efficiently test whether to report metrics at all by using code such as if( $metrics ) { $metrics->inc_counter( name => some_expensive_function() ); } While the Null adapter will simply ignore any of the methods invoked on it, without this conditional test the caller would otherwise still have to calculate the value that won't be used. This structure allows the calculation to be avoided if metrics are not in use. =cut use overload 'bool' => sub { !$_[0]->{adapter} or ref $_[0]->{adapter} ne "Metrics::Any::Adapter::Null" }, # stringify as itself otherwise bool takes over and it just prints as 1, # leading to much developer confusion '""' => sub { $_[0] }, fallback => 1; =head1 METHODS $package = $metrics->package Returns the package name that created the collector; the package in which the use Metrics::Any '$metrics'; statement was invoked. =cut sub package { my $self = shift; return $self->{package}; } =head1 METRIC TYPES Each type of metric is created by one of the C methods. They all take the following common arguments: =over 4 =item name => ARRAY[ STRING ] | STRING Optional. An array of string parts, or a plain string name to use for reporting this metric to its upstream service. Modules should preferrably use an array of string parts to specify their metric names, as different adapter types may have different ways to represent this hierarchially. Base-level parts of the name should come first, followed by more specific parts. It is common for related metrics to be grouped by name having identical prefixes but differing only in the final part. The name is optional; if unspecified then the handle will be used to form the name, combined with a C argument if one was set for the package. =item description => STRING Optional human-readable description. May be used for debugging or other purposes. =item labels => ARRAY[ STRING ] Optional reference to an array of string names to use as label names. A labelled metric will expect to receive additional information in its reporting method to give values for these labels. This information should be in either an even-length array reference of name/value pairs, or a hash reference. E.g. $metrics->inc_counter( handle => [ labelname => $labelvalue ] ); $metrics->inc_counter( handle => { labelname => $labelvalue } ); A legacy form where a plain list of values is passed, each corresponding to a named label in the same order, is currently accepted but discouraged in favour of the above forms. $metrics->inc_counter( handle => $labelvalue ); Note that not all metric reporting adapters may be able to represent all of the labels. Each should document what its behaviour will be. =back =cut =head2 Counter The L method creates a new metric which counts occurances of some event within the application. Its value begins at zero, and can be incremented by L whenever the event occurs. Some counters may simple count occurances of events, while others may count in other units, for example counts of bytes. Adapters may make use of the C parameter of the distribution to perform some kind of adapter-specific behaviour. The following units are suggested: =head3 bytes Observations give sizes in bytes (perhaps memory buffer or network message sizes), and should be integers. =cut =head2 make_counter $collector->make_counter( $handle, %args ) Requests the creation of a new counter metric. The C<$handle> name should be unique within the collector instance, though does not need to be unique across the entire program, as it will be namespaced by the collector instance. The following extra arguments may be passed: =over 4 =item units => STRING A hint to the adapter about what kind of measurements are being observed, so it might take specific behaviour. =back =cut sub make_counter { my $self = shift; my ( $handle, %args ) = @_; $args{name} = $self->_metricname( $args{name} // [ $handle ] ); $self->{$handle} and croak "Already have a metric '$handle'"; $self->{$handle} = [ counter => @{ $args{labels} // [] } ]; $self->_adapter_call( make_counter => "$self->{package}/$handle", collector => $self, %args ); } =head2 inc_counter $collector->inc_counter( $handle, $labels ) Reports that the counter metric value be incremented by one. The C<$handle> name must match one earlier created by L. =cut sub inc_counter { my $self = shift; my ( $handle, @args ) = @_; my @labelvalues = $self->_labelvalues( counter => $handle, @args ); $self->adapter->inc_counter_by( "$self->{package}/$handle", 1, @labelvalues ); } =head2 inc_counter_by $collector->inc_counter_by( $handle, $amount, $labels ) Reports that a counter metric value be incremented by some specified value. =cut sub inc_counter_by { my $self = shift; my ( $handle, $amount, @args ) = @_; my @labelvalues = $self->_labelvalues( counter => $handle, @args ); $self->adapter->inc_counter_by( "$self->{package}/$handle", $amount, @labelvalues ); } =head2 Distribution The L method creates a new metric which counts individual observations of some numerical quantity (which may or may not be integral). New observations can be added by the L method. Some adapter types may only store an aggregated total; others may store some sort of statistical breakdown, either total + count, or a bucketed histogram. The specific adapter documentation should explain how it handles distributions. Adapters may make use of the C parameter of the distribution to perform some kind of adapter-specific behaviour. The following units are suggested: =head3 bytes Observations give sizes in bytes (perhaps memory buffer or network message sizes), and should be integers. =head3 seconds Observations give durations in seconds. =cut =head2 make_distribution $collector->make_distribution( $handle, %args ) Requests the creation of a new distribution metric. The following extra arguments may be passed: =over 4 =item units => STRING A hint to the adapter about what kind of measurements are being observed, so it might take specific behaviour. If unspecified, a default of C will apply. =back =cut sub make_distribution { my $self = shift; my ( $handle, %args ) = @_; $args{name} = $self->_metricname( $args{name} // [ $handle ] ); $args{units} //= "bytes"; $self->{$handle} and croak "Already have a metric '$handle'"; $self->{$handle} = [ distribution => @{ $args{labels} // [] } ]; $self->_adapter_call( make_distribution => "$self->{package}/$handle", collector => $self, %args ); } =head2 report_distribution $collector->report_distribution( $handle, $amount, $labels ) I Reports a new observation for the distribution metric. The C<$handle> name must match one earlier created by L. The C<$amount> may be interpreted by the adapter depending on the defined C type for the distribution. This method used to be called C and is currently still available as an alias. =cut sub report_distribution { my $self = shift; my ( $handle, $amount, @args ) = @_; my @labelvalues = $self->_labelvalues( distribution => $handle, @args ); my $adapter = $self->adapter; # Support new and legacy name my $method = $adapter->can( "report_distribution" ) // "inc_distribution_by"; $adapter->$method( "$self->{package}/$handle", $amount, @labelvalues ); } *inc_distribution_by = \&report_distribution; =head2 Gauge The L method creates a new metric which reports on the instantaneous value of some measurable quantity. Unlike the other metric types this does not have to only increment forwards when certain events occur, but can measure a quantity that may both increase and decrease over time; such as the number some kind of object in memory, or the size of some data structure. As an alternative to incrementing or decrementing the value when particular events occur, the absolute value of the gauge can also be set directly. =cut =head2 make_gauge $collector->make_gauge( $handle, %args ) Requests the creation of a new gauge metric. =cut sub make_gauge { my $self = shift; my ( $handle, %args ) = @_; $args{name} = $self->_metricname( $args{name} // [ $handle ] ); $self->{$handle} and croak "Already have a metric '$handle'"; $self->{$handle} = [ gauge => @{ $args{labels} // [] } ]; $self->_adapter_call( make_gauge => "$self->{package}/$handle", collector => $self, %args ); } =head2 inc_gauge $collector->inc_gauge( $handle, $labels ) =head2 dec_gauge $collector->dec_gauge( $handle, $labels ) =head2 inc_gauge_by $collector->inc_gauge_by( $handle, $amount, $labels ) =head2 dec_gauge_by $collector->dec_gauge_by( $handle, $amount, $labels ) Reports that the observed value of the gauge has increased or decreased by the given amount (or 1). =cut sub inc_gauge { my $self = shift; my ( $handle, @args ) = @_; my @labelvalues = $self->_labelvalues( gauge => $handle, @args ); $self->adapter->inc_gauge_by( "$self->{package}/$handle", 1, @labelvalues ); } sub dec_gauge { my $self = shift; my ( $handle, @args ) = @_; my @labelvalues = $self->_labelvalues( gauge => $handle, @args ); $self->adapter->inc_gauge_by( "$self->{package}/$handle", -1, @labelvalues ); } sub inc_gauge_by { my $self = shift; my ( $handle, $amount, @args ) = @_; my @labelvalues = $self->_labelvalues( gauge => $handle, @args ); $self->adapter->inc_gauge_by( "$self->{package}/$handle", $amount, @labelvalues ); } sub dec_gauge_by { my $self = shift; my ( $handle, $amount, @args ) = @_; my @labelvalues = $self->_labelvalues( gauge => $handle, @args ); $self->adapter->inc_gauge_by( "$self->{package}/$handle", -$amount, @labelvalues ); } =head2 set_gauge_to $collector->set_gauge_to( $handle, $amount, $labels ) Reports that the observed value of the gauge is now the given amount. The C<$handle> name must match one earlier created by L. =cut sub set_gauge_to { my $self = shift; my ( $handle, $amount, @args ) = @_; my @labelvalues = $self->_labelvalues( gauge => $handle, @args ); $self->adapter->set_gauge_to( "$self->{package}/$handle", $amount, @labelvalues ); } =head2 Timer The L method creates a new metric which measures durations of time consumed by the application. New observations of durations can be added by the L method. Timer metrics may be handled by the adapter similarly to distribution metrics. Moreover, adapters may choose to implement timers as distributions with units of C. =cut =head2 make_timer $collector->make_timer( $handle, %args ) Requests the creation of a new timer metric. =cut sub make_timer { my $self = shift; my ( $handle, %args ) = @_; $args{name} = $self->_metricname( $args{name} // [ $handle ] ); $self->{$handle} and croak "Already have a metric '$handle'"; $self->{$handle} = [ timer => @{ $args{labels} // [] } ]; $self->_adapter_call( make_timer => "$self->{package}/$handle", collector => $self, %args ); } =head2 report_timer $collector->report_timer( $handle, $duration, $labels ) I Reports a new duration for the timer metric. The C<$handle> name must match one earlier created by L. The C<$duration> gives a time measured in seconds, and may be fractional. This method used to called C and is currently still available as an alias. =cut sub report_timer { my $self = shift; my ( $handle, $duration, @args ) = @_; my @labelvalues = $self->_labelvalues( timer => $handle, @args ); my $adapter = $self->adapter; # Support new and legacy name my $method = $adapter->can( "report_timer" ) // "inc_timer_by"; $adapter->$method( "$self->{package}/$handle", $duration, @labelvalues ); } *inc_timer_by = \&report_timer; =head1 AUTHOR Paul Evans =cut 0x55AA; Metrics-Any-0.07/lib/Metrics/Any/Adapter000755001750001750 014076045756 16615 5ustar00leoleo000000000000Metrics-Any-0.07/lib/Metrics/Any/Adapter/File.pm000444001750001750 1057714076045756 20221 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk package Metrics::Any::Adapter::File 0.07; use v5.14; use warnings; use Carp; =head1 NAME C - write metrics to a file =head1 SYNOPSIS use Metrics::Any::Adapter 'File', path => "metrics.log"; =head1 DESCRIPTION This L adapter type writes observations of metric values into a file. This may be helpful while debugging or otherwise testing code that reports metrics. For example, by setting the C environment variable to configure the adapter, a metric log will be written as a side-effect of running a unit test: $ METRICS_ANY_ADAPTER=File:path=metrics.log perl -Mblib t/01test.t The generated file can then be inspected to see what metric values were reported while the program was running. In particular, specifying the file F allows the full metrics generation path to be tested with the code under test seeing a "real" adapter even though the output goes nowhere. $ METRICS_ANY_ADAPTER=File:path=/dev/null ./Build test Distribution and timing metrics are tracked with a running total and count of observations. =head1 ARGUMENTS The following additional arguments are recognised =head2 path The path to the file to write to. =cut my %metrics; sub new { my $class = shift; my %args = @_; my $fh; if( $args{fh} ) { # fh isn't documented but useful for unit testing $fh = $args{fh}; } elsif( $args{path} ) { open $fh, ">>", $args{path} or die "Cannot open $args{path} for writing - $!\n"; } else { croak "Require a 'path' argument"; } $fh->autoflush; return bless { __fh => $fh, }, $class; } sub _make { my $self = shift; my ( $type, $handle, %args ) = @_; my $name = $args{name}; $name = join "_", @$name if ref $name eq "ARRAY"; $self->{$handle} = { type => $type, name => $name, labels => $args{labels}, }; } sub _key { my $self = shift; my ( $handle, $suffix, @labelvalues ) = @_; my $meta = $self->{$handle}; my $key = $meta->{name}; $key .= $suffix if defined $suffix; if( my $labels = $meta->{labels} ) { $key .= " $labels->[$_]:$labelvalues[$_]" for 0 .. $#$labels; } return $key; } sub make_counter { shift->_make( counter => @_ ) } sub inc_counter_by { my $self = shift; my ( $handle, $amount, @labelvalues ) = @_; my $fh = $self->{__fh}; my $key = $self->_key( $handle, undef, @labelvalues ); my $current = $metrics{$key} += $amount; printf $fh "METRIC COUNTER %s %+g => %g\n", $key, $amount, $current; } sub make_distribution { shift->_make( distribution => @_ ) } sub report_distribution { my $self = shift; my ( $handle, $amount, @labelvalues ) = @_; my $fh = $self->{__fh}; my $count = $metrics{ $self->_key( $handle, "_count", @labelvalues ) } += 1; my $total = $metrics{ $self->_key( $handle, "_total", @labelvalues ) } += $amount; printf $fh "METRIC DISTRIBUTION %s +%g => %g/%d [avg=%g]\n", $self->_key( $handle, undef, @labelvalues ), $amount, $total, $count, $total/$count; } sub make_gauge { shift->_make( gauge => @_ ) } sub inc_gauge_by { my $self = shift; my ( $handle, $amount, @labelvalues ) = @_; my $fh = $self->{__fh}; my $key = $self->_key( $handle, undef, @labelvalues ); my $current = $metrics{$key} += $amount; printf $fh "METRIC GAUGE %s %+g => %g\n", $key, $amount, $current; } sub set_gauge_to { my $self = shift; my ( $handle, $amount, @labelvalues ) = @_; my $fh = $self->{__fh}; my $key = $self->_key( $handle, undef, @labelvalues ); my $current = $metrics{$key} = $amount; printf $fh "METRIC GAUGE %s => %g\n", $key, $current; } sub make_timer { shift->_make( timer => @_ ) } sub report_timer { my $self = shift; my ( $handle, $duration, @labelvalues ) = @_; my $fh = $self->{__fh}; my $count = $metrics{ $self->_key( $handle, "_count", @labelvalues ) } += 1; my $total = $metrics{ $self->_key( $handle, "_total", @labelvalues ) } += $duration; printf $fh "METRIC TIMER %s +%.3g => %.3g/%d [avg=%g]\n", $self->_key( $handle, undef, @labelvalues ), $duration, $total, $count, $total/$count; } =head1 AUTHOR Paul Evans =cut 0x55AA; Metrics-Any-0.07/lib/Metrics/Any/Adapter/Null.pm000444001750001750 210614076045756 20221 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk package Metrics::Any::Adapter::Null 0.07; use v5.14; use warnings; =head1 NAME C - a metrics reporting adapter which does nothing =head1 DESCRIPTION This L adapter type contains an empty stub implementation of the adapter API, allowing a module to invoke methods on its metrics collector that do not do anything. A program would run with this adapter by default unless it has requested a different one, via the C statement. =cut sub new { my $class = shift; return bless {}, $class; } # All of these are empty methods foreach my $method (qw( make_counter inc_counter_by make_distribution report_distribution make_gauge inc_gauge_by set_gauge_to make_timer report_timer )) { no strict 'refs'; *$method = sub {}; } =head1 AUTHOR Paul Evans =cut 0x55AA; Metrics-Any-0.07/lib/Metrics/Any/Adapter/Stderr.pm000444001750001750 174314076045756 20560 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk package Metrics::Any::Adapter::Stderr 0.07; use v5.14; use warnings; use base qw( Metrics::Any::Adapter::File ); =head1 NAME C - write metrics to C =head1 SYNOPSIS use Metrics::Any::Adapter 'Stderr'; This L adapter type writes observations of metric values to the standard error stream. This may be helpful while debugging or otherwise testing code that reports metrics. For example, by setting the C environment variable to configure the adapter, a metric log will be written to the terminal as a side-effect of running a unit test: $ METRICS_ANY_ADAPTER=Stderr perl -Mblib t/01test.t =cut sub new { shift->SUPER::new( fh => \*STDERR, @_ ); } =head1 AUTHOR Paul Evans =cut 0x55AA; Metrics-Any-0.07/lib/Metrics/Any/Adapter/Tee.pm000444001750001750 413114076045756 20024 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk package Metrics::Any::Adapter::Tee 0.07; use v5.14; use warnings; =head1 NAME C - send metrics to multiple adapters =head1 SYNOPSIS use Metrics::Any::Adapter 'Tee', "Prometheus", [ "File", path => "metrics.log" ], "Statsd"; =head1 DESCRIPTION This L adapter type acts as a container for multiple other adapters, allowing an application to report its metrics via multiple different mechanisms at the same time. =head1 ARGUMENTS Each value passed in the import list should either be an adapter type string or an array reference containing the name and additional arguments. Adapters specified by string are split in the same way as L splits the C environment variable; namely by parsing optional arguments after a colon, separated by commas or equals signs. E.g. "File:path=metrics.log" would be equivalent to the version given in the synopsis above. =cut sub new { my $class = shift; my @adapters; foreach ( @_ ) { # Adapters are probably specified by ARRAYref my ( $type, @args ) = ref $_ eq "ARRAY" ? @$_ : Metrics::Any::Adapter->split_type_string( $_ ); push @adapters, Metrics::Any::Adapter->class_for_type( $type )->new( @args ); } return bless { adapters => \@adapters, }, $class; } # Distribute each method call across all the adapters foreach my $method (qw( make_counter inc_counter_by make_distribution report_distribution make_gauge inc_gauge_by set_gauge make_timer report_timer )) { my $code = sub { my $self = shift; my @e; foreach my $adapter ( @{ $self->{adapters} } ) { defined eval { $adapter->$method( @_ ); 1 } or push @e, $@; } die $e[0] if @e; }; no strict 'refs'; *$method = $code; } =head1 AUTHOR Paul Evans =cut 0x55AA; Metrics-Any-0.07/lib/Metrics/Any/Adapter/Test.pm000444001750001750 747414076045756 20243 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk package Metrics::Any::Adapter::Test 0.07; use v5.14; use warnings; use base qw( Metrics::Any::AdapterBase::Stored ); use Carp; use List::Util 1.29 qw( pairs ); =head1 NAME C - a metrics reporting adapter for unit testing =head1 SYNOPSIS use Test::More; use Metrics::Any::Adapter 'Test'; { Metrics::Any::Adapter::Test->clear; # perform some work in the code under test is( Metrics::Any::Adapter::Test->metrics, "an_expected_metric = 1\n", 'Metrics were reported while doing something' ); } =head1 DESCRIPTION This L adapter type stores reported metrics locally, allowing access to them by the L method. This is useful to use in a unit test to check that the code under test reports the correct metrics. This adapter supports timer metrics by storing the count and total duration. For predictable output of timer metrics in unit tests, a unit test may wish to use the L method. =cut my $singleton; sub new { my $class = shift; return $singleton //= $class->SUPER::new( @_ ); } my $timer_duration; =head1 METHODS =cut =head2 metrics $result = Metrics::Any::Adapter::Test->metrics This class method returns a string describing all of the stored metric values. Each is reported on a line formatted as name = value Each line, including the final one, is terminated by a linefeed. The metrics are sorted alphabetically. Any multi-part metric names will be joined with underscores (C<_>). Metrics that have additional labels are formatted with additional label names and label values in declared order after the name and before the C<=> symbol: name l1:v1 l2:v2 = value =cut use constant { DIST_COUNT => 0, DIST_TOTAL => 1, }; sub store_distribution { shift; my ( $storage, $amount ) = @_; $storage //= [ 0, 0 ]; $storage->[DIST_COUNT] += 1; $storage->[DIST_TOTAL] += $amount; return $storage; } *store_timer = \&store_distribution; sub metrics { my $self = shift; ref $self or $self = Metrics::Any::Adapter::Test->new; my @ret; $self->walk( sub { my ( $type, $name, $labels, $value ) = @_; $name .= sprintf " %s:%s", $_->key, $_->value for pairs @$labels; if( $type eq "counter" or $type eq "gauge" ) { push @ret, "$name = $value"; } elsif( $type eq "distribution" or $type eq "timer" ) { push @ret, "${name}_count = " . $value->[DIST_COUNT]; push @ret, "${name}_total = " . $value->[DIST_TOTAL]; } else { warn "Unsure how to handle metric of type $type\n"; } } ); return join "", map { "$_\n" } @ret; } =head2 clear Metrics::Any::Adapter::Test->clear This class method removes all of the stored values of reported metrics. =cut sub clear { my $self = shift; ref $self or $self = Metrics::Any::Adapter::Test->new; $self->clear_values; undef $timer_duration; } =head2 override_timer_duration Metrics::Any::Adapter::Test->override_timer_duration( $duration ) This class method sets a duration value, that any subsequent call to C will use instead of the value the caller actually passed in. This will ensure reliably predictable output in unit tests. Any value set here will be cleared by L. =cut sub override_timer_duration { shift; ( $timer_duration ) = @_; } sub report_timer { my $self = shift; my ( $handle, $duration, @labelvalues ) = @_; $duration = $timer_duration if defined $timer_duration; $self->SUPER::report_timer( $handle, $duration, @labelvalues ); } =head1 AUTHOR Paul Evans =cut 0x55AA; Metrics-Any-0.07/lib/Metrics/Any/AdapterBase000755001750001750 014076045756 17410 5ustar00leoleo000000000000Metrics-Any-0.07/lib/Metrics/Any/AdapterBase/Stored.pm000444001750001750 1400714076045756 21365 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk package Metrics::Any::AdapterBase::Stored 0.07; use v5.14; use warnings; use Carp; =head1 NAME C - a base class for metrics adapters which store values =head1 DESCRIPTION This base class assists in creating L classes which store values of reported metrics directly. These can then be retrieved later by the containing application, or the subclass code, by using the L method. This base class internally stores counter and gauge metrics as single scalar values directly. In order to provide flexibility for a variety of use-cases, it requires assistance from the implementing class on how to store distribution and timer metrics. The implementing class should provide these methods, returning whatever values it wishes to implement them with. These values are stored by the base class, and handed back as part of the L method. The base class stores a value for each unique set of labels and values on every metric; the subclass does not need to handle this. =cut sub new { my $class = shift; # Metrics are keys of $self, named by handle return bless {}, $class; } =head1 METHODS =cut sub _make { my $self = shift; my ( $type, $handle, %args ) = @_; my $name = $args{name}; $name = join "_", @$name if ref $name eq "ARRAY"; $self->{$handle} = { type => $type, name => $name, labels => $args{labels}, values => {}, # values per labelset }; } sub _metric { my $self = shift; my ( $type, $handle ) = @_; my $metric = $self->{$handle}; $metric->{type} eq $type or croak "$handle is not a $type metric"; return $metric; } sub _labelset { my $self = shift; my ( $handle, @labelvalues ) = @_; my $metric = $self->{$handle}; my $labels = $metric->{labels} or return ""; return join "\0", map { "$labels->[$_]:$labelvalues[$_]" } 0 .. $#$labels; } =head2 walk $stored->walk( $code ) $code->( $type, $name, $labels, $value ) Given a CODE reference, this method invokes it once per labelset of every stored metric. For each labelset, C<$type> will give the metric type (as a string, either C, C, C or C), C<$name> gives the name it was registered with, C<$labels> will be a reference to an even-sized array containing label names and values. For counter and gauge metrics, C<$value> will be a numerical scalar giving the current value. For distribution and timer metrics, C<$value> will be whatever the implementing class's corresponding C or C method returns for them. =cut sub walk { my $self = shift; my ( $code ) = @_; foreach my $handle ( sort keys %$self ) { my $metric = $self->{$handle}; my $values = $metric->{values}; foreach my $labelset ( sort keys %$values ) { my @labels = map { split m/:/, $_, 2 } split m/\0/, $labelset; $code->( $metric->{type}, $metric->{name}, \@labels, $values->{$labelset} ); } } } =head2 clear_values $stored->clear_values Clears all of the metric storage. Every labelset of every metric is deleted. The metric definitions themselves remain. =cut sub clear_values { my $self = shift; $_->{values} = {} for values %$self; } sub make_counter { shift->_make( counter => @_ ) } sub inc_counter_by { my $self = shift; my ( $handle, $amount, @labelvalues ) = @_; my $metric = $self->_metric( counter => $handle ); $metric->{values}{ $self->_labelset( $handle, @labelvalues ) } += $amount; } sub make_distribution { shift->_make( distribution => @_ ) } sub report_distribution { my $self = shift; my ( $handle, $amount, @labelvalues ) = @_; my $metric = $self->_metric( distribution => $handle ); my $values = $metric->{values}; my $key = $self->_labelset( $handle, @labelvalues ); $values->{$key} = $self->store_distribution( $values->{$key}, $amount ); } sub make_gauge { shift->_make( gauge => @_ ) } sub inc_gauge_by { my $self = shift; my ( $handle, $amount, @labelvalues ) = @_; my $metric = $self->_metric( gauge => $handle ); $metric->{values}{ $self->_labelset( $handle, @labelvalues ) } += $amount; } sub set_gauge_to { my $self = shift; my ( $handle, $amount, @labelvalues ) = @_; my $metric = $self->_metric( gauge => $handle ); $metric->{values}{ $self->_labelset( $handle, @labelvalues ) } = $amount; } sub make_timer { shift->_make( timer => @_ ) } sub report_timer { my $self = shift; my ( $handle, $duration, @labelvalues ) = @_; my $metric = $self->_metric( timer => $handle ); my $values = $metric->{values}; my $key = $self->_labelset( $handle, @labelvalues ); $values->{$key} = $self->store_timer( $values->{$key}, $duration ); } =head1 REQUIRED METHODS =head2 store_distribution =head2 store_timer $storage = $stored->store_distribution( $storage, $amount ) $storage = $stored->store_timer( $storage, $duration ) The implementing class must provide these two methods to assist in the management of storage for distribution and timer metrics. When a new observation for the metric is required, the method will be invoked, passing in the currently-stored perl value for the given metric and label values, and the new observation. Whatever the method returns is stored by the base class, to be passed in next time or used by the L method. The base class stores this value directly and does not otherwise interact with it; letting the implementing class decide what is best. For example, a simple implementation may just store every observation individually by pushing them into an array; so the C<$storage> would be an ARRAY reference: sub store_distribution { my $self = shift; my ( $storage, $amount ) = @_; push @$storage, $amount; return $storage; } =cut =head1 AUTHOR Paul Evans =cut 0x55AA; Metrics-Any-0.07/t000755001750001750 014076045756 12575 5ustar00leoleo000000000000Metrics-Any-0.07/t/00use.t000444001750001750 65414076045756 14040 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; use_ok( "Metrics::Any" ); use_ok( "Metrics::Any::Adapter" ); use_ok( "Metrics::Any::Collector" ); use_ok( "Metrics::Any::AdapterBase::Stored" ); use_ok( "Metrics::Any::Adapter::File" ); use_ok( "Metrics::Any::Adapter::Null" ); use_ok( "Metrics::Any::Adapter::Stderr" ); use_ok( "Metrics::Any::Adapter::Tee" ); use_ok( "Metrics::Any::Adapter::Test" ); done_testing; Metrics-Any-0.07/t/01collector.t000444001750001750 400014076045756 15240 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; use Test::Fatal; use Metrics::Any '$metrics', strict => 1; ok( defined $metrics, '$metrics global is defined' ); # counter { can_ok( $metrics, qw( make_counter inc_counter inc_counter_by )); $metrics->make_counter( c => ); ok( exception { $metrics->make_counter( c => ) }, 'Fails duplicate registration of counter' ); ok( !exception { $metrics->inc_counter( c => ) }, 'Can report to registered counter' ); ok( exception { $metrics->inc_counter( c2 => ) }, 'Fails attempt to report to unregistered counter' ); } # distribution { can_ok( $metrics, qw( make_distribution report_distribution )); $metrics->make_distribution( d => ); ok( exception { $metrics->make_distribution( d => ) }, 'Fails registration of distribution' ); ok( !exception { $metrics->report_distribution( d => 5 ) }, 'Can report to registered distribution' ); ok( exception { $metrics->report_distribution( d2 => 5 ) }, 'Fails attempt to report to unregistered distribution' ); } # gauge { can_ok( $metrics, qw( make_gauge inc_gauge inc_gauge_by dec_gauge_by dec_gauge set_gauge_to )); $metrics->make_gauge( g => ); ok( exception { $metrics->make_gauge( g => ) }, 'Fails duplicate registration of gauge' ); ok( !exception { $metrics->inc_gauge( g => ) }, 'Can report to registered gauge' ); ok( exception { $metrics->inc_gauge( g2 => ) }, 'Fails attempt to report to unregistered gauge' ); } # timer { can_ok( $metrics, qw( make_timer report_timer )); $metrics->make_timer( t => ); ok( exception { $metrics->make_timer( t => ) }, 'Fails duplicate registration of timer' ); ok( !exception { $metrics->report_timer( t => ) }, 'Can report to registered timer' ); ok( exception { $metrics->report_timer( t2 => ) }, 'Fails attempt to report to unregistered timer' ); } # misc { is( $metrics->package, "main", '$metrics->package' ); } done_testing; Metrics-Any-0.07/t/02adapter-early.t000444001750001750 132214076045756 16011 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; # package NAME {BLOCK} use warnings; use Test::More; my @method_call_args; package Metrics::Any::Adapter::Testing { sub new { bless {}, shift } sub make_counter { shift; push @method_call_args, [ make_counter => @_ ] } sub inc_counter_by { shift; push @method_call_args, [ inc_counter_by => @_ ] } } use Metrics::Any::Adapter 'Testing'; use Metrics::Any '$metrics'; $metrics->make_counter( handle => name => "the_name" ); $metrics->inc_counter( handle => ); is_deeply( \@method_call_args, [ [qw( make_counter main/handle ), collector => $metrics, name => "the_name" ], [qw( inc_counter_by main/handle 1 )], ], 'Adapter methods invoked' ); done_testing; Metrics-Any-0.07/t/03adapter-late.t000444001750001750 150214076045756 15623 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; # package NAME {BLOCK} use warnings; use Test::More; my @method_call_args; package Metrics::Any::Adapter::Testing { sub new { bless {}, shift } sub make_counter { shift; push @method_call_args, [ make_counter => @_ ] } sub inc_counter_by { shift; push @method_call_args, [ inc_counter_by => @_ ] } } # This file is an identical copy of t/02adapter-early.t except these two 'use' # lines are swapped use Metrics::Any '$metrics'; BEGIN { $metrics->make_counter( handle => name => "the_name" ); } use Metrics::Any::Adapter 'Testing'; $metrics->inc_counter( handle => ); is_deeply( \@method_call_args, [ [qw( make_counter main/handle ), collector => $metrics, name => "the_name" ], [qw( inc_counter_by main/handle 1 )], ], 'Adapter methods invoked' ); done_testing; Metrics-Any-0.07/t/04adapter-string-parse.t000444001750001750 140714076045756 17321 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; use Metrics::Any::Adapter; # Basic parsing { is_deeply( [ Metrics::Any::Adapter->split_type_string( "Type" ) ], [ "Type" ], 'Type string with no args' ); is_deeply( [ Metrics::Any::Adapter->split_type_string( "List:1,2" ) ], [ "List", "1", "2" ], 'Type string with list args' ); is_deeply( [ Metrics::Any::Adapter->split_type_string( "Map:one=1,two=2" ) ], [ "Map", one => "1", two => "2" ], 'Type string with name=value args' ); } # Nesting-aware parsing { is_deeply( [ Metrics::Any::Adapter->split_type_string( "Type:[value:goes,here]" ) ], [ "Type", "value:goes,here" ], 'Type string with [nested part]' ); } done_testing; Metrics-Any-0.07/t/10adapter-null.t000444001750001750 256614076045756 15661 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; use Metrics::Any::Adapter 'Null'; use Metrics::Any '$metrics'; ok( defined $metrics, '$metrics is defined' ); ok( $metrics, '$metrics appears true before adapter' ); # Force creation of the adapter $metrics->adapter; ok( !$metrics, '$metrics appears false with adapter' ); ok( defined eval { $metrics->make_counter( "events" ); 1 }, '$metrics->make_counter' ) or diag( $@ ); ok( defined eval { $metrics->inc_counter( "events" ); 1 }, '$metrics->inc_counter' ) or diag( $@ ); ok( defined eval { $metrics->make_distribution( "bytes" ); 1 }, '$metrics->make_distribution' ) or diag( $@ ); ok( defined eval { $metrics->report_distribution( "bytes", 20 ); 1 }, '$metrics->report_distribution' ) or diag( $@ ); ok( defined eval { $metrics->make_gauge( "size" ); 1 }, '$metrics->make_gauge' ) or diag( $@ ); ok( defined eval { $metrics->inc_gauge_by( "size", 20 ); 1 }, '$metrics->inc_gauge_by' ) or diag( $@ ); ok( defined eval { $metrics->set_gauge_to( "size", 50 ); 1 }, '$metrics->set_gauge_to' ) or diag( $@ ); ok( defined eval { $metrics->make_timer( "duration" ); 1 }, '$metrics->make_timer' ) or diag( $@ ); ok( defined eval { $metrics->report_timer( "duration", 20 ); 1 }, '$metrics->report_timer' ) or diag( $@ ); ok( !$metrics, '$metrics is still false at EOF' ); done_testing; Metrics-Any-0.07/t/11adapter-file.t000444001750001750 371214076045756 15621 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; use IO::Handle; use Errno qw( EAGAIN EWOULDBLOCK ); use Metrics::Any '$metrics'; require Metrics::Any::Adapter; # no 'use' yet sub readall { my $ret = $_[0]; $_[0] = ""; return $ret; } open my $fh, ">>", \( my $buf = "" ); # fh isn't documented but useful for this unit test Metrics::Any::Adapter->import( File => fh => $fh ); # Force the adapter to exist $metrics->adapter; ok( $metrics, '$metrics is still true' ); # counter { $metrics->make_counter( c => name => "counter" ); $metrics->inc_counter( c => ); is( readall( $buf ), "METRIC COUNTER counter +1 => 1\n", 'Counter metric written' ); $metrics->inc_counter_by( c => 3 ); is( readall( $buf ), "METRIC COUNTER counter +3 => 4\n", 'Counter persists total' ); } # distribution { $metrics->make_distribution( d => name => "distribution" ); $metrics->report_distribution( d => 5 ); is( readall( $buf ), "METRIC DISTRIBUTION distribution +5 => 5/1 [avg=5]\n", 'Distribution metric written' ); $metrics->report_distribution( d => 3 ); is( readall( $buf ), "METRIC DISTRIBUTION distribution +3 => 8/2 [avg=4]\n", 'Distribution persists total and count' ); } # gauge { $metrics->make_gauge( g => name => "gauge" ); $metrics->inc_gauge( g => ); is( readall( $buf ), "METRIC GAUGE gauge +1 => 1\n", 'Gauge metric written' ); $metrics->inc_gauge_by( g => 2 ); is( readall( $buf ), "METRIC GAUGE gauge +2 => 3\n", 'Gauge persists total' ); } # timer { $metrics->make_timer( t => name => "timer" ); $metrics->report_timer( t => 0.02 ); is( readall( $buf ), "METRIC TIMER timer +0.02 => 0.02/1 [avg=0.02]\n", 'Timer metric written' ); $metrics->report_timer( t => 0.04 ); is( readall( $buf ), "METRIC TIMER timer +0.04 => 0.06/2 [avg=0.03]\n", 'Timer persists total and count' ); } ok( $metrics, '$metrics is still true at EOF' ); done_testing; Metrics-Any-0.07/t/12adapter-tee.t000444001750001750 214614076045756 15460 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; # package NAME {BLOCK} use warnings; use Test::More; use Metrics::Any '$metrics', strict => 0; package Metrics::Any::Adapter::_ToHash { sub new { my $class = shift; return bless { h => shift }, $class; } sub make_counter {} sub make_distribution {} sub make_gauge {} sub make_timer {} sub _inc { $_[0]->{h}->{$_[1]} += $_[2] } no warnings 'once'; *inc_counter_by = *report_distribution = *inc_gauge_by = *report_timer = \&_inc; } my %metrics1; my %metrics2; require Metrics::Any::Adapter; Metrics::Any::Adapter->import( Tee => [ _ToHash => \%metrics1 ], [ _ToHash => \%metrics2 ], ); $metrics->inc_counter( counter => ); $metrics->report_distribution( distribution => 5 ); $metrics->inc_gauge( gauge => ); $metrics->report_timer( timer => 0.1 ); my %expect = ( 'main/counter' => 1, 'main/distribution' => 5, 'main/gauge' => 1, 'main/timer' => 0.1, ); is_deeply( \%metrics1, \%expect, 'Metrics reported to first adapter' ); is_deeply( \%metrics2, \%expect, 'Metrics reported to second adapter' ); done_testing; Metrics-Any-0.07/t/13adapter-stored.t000444001750001750 340014076045756 16176 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; # package NAME {BLOCK} use warnings; use Test::More; use Metrics::Any '$metrics'; package Metrics::Any::Adapter::localTestAdapter { use base "Metrics::Any::AdapterBase::Stored"; # push to an array sub store_distribution { my ( undef, $storage, $amount ) = @_; push @$storage, $amount; return $storage; } # summarize sub store_timer { my ( undef, $storage, $duration ) = @_; $storage->{total} += $duration; $storage->{count} += 1; return $storage; } } use Metrics::Any::Adapter 'localTestAdapter'; { $metrics->make_counter( counter => ); $metrics->make_distribution( distribution => ); $metrics->make_gauge( gauge => ); $metrics->make_timer( timer => ); $metrics->inc_counter( counter => ); $metrics->report_distribution( distribution => 1 ); $metrics->report_distribution( distribution => 3 ); $metrics->report_distribution( distribution => 5 ); $metrics->inc_gauge_by( gauge => 5 ); $metrics->report_timer( timer => 2 ); $metrics->report_timer( timer => 4 ); # Also test labels $metrics->make_counter( labeled_counter => labels => [qw( x y )], ); $metrics->inc_counter( labeled_counter => { x => 10, y => 20 } ); my @walkdata; Metrics::Any::Adapter->adapter->walk( sub { my ( $type, $name, $labels, $value ) = @_; push @walkdata, [ $type, $name, $labels, $value ]; } ); is_deeply( \@walkdata, [ [ counter => counter => [], 1 ], [ distribution => distribution => [], [ 1, 3, 5 ] ], [ gauge => gauge => [], 5 ], [ counter => labeled_counter => [ x => 10, y => 20 ], 1 ], [ timer => timer => [], { total => 6, count => 2 } ], ], 'metrics to ->walk' ); } done_testing; Metrics-Any-0.07/t/14adapter-test.t000444001750001750 646714076045756 15676 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; use Metrics::Any '$metrics'; use Metrics::Any::Adapter 'Test'; # Force the adapter to exist $metrics->adapter; ok( $metrics, '$metrics is still true' ); # unlabelled { Metrics::Any::Adapter::Test->clear; $metrics->make_counter( abc => name => "the_ABC_counter" ); $metrics->make_counter( def => name => [qw( the DEF counter )] ); $metrics->inc_counter( 'abc' ); $metrics->inc_counter( 'def' ); $metrics->inc_counter( 'def' ); $metrics->inc_counter( 'def' ); is( Metrics::Any::Adapter::Test->metrics, "the_ABC_counter = 1\n" . "the_DEF_counter = 3\n", 'Metrics::Any::Adapter::Test->metrics for basic metrics' ); } # with labels { Metrics::Any::Adapter::Test->clear; $metrics->make_counter( ghi => name => "the_GHI_counter", labels => [qw( label )], ); $metrics->make_counter( jkl => name => "the_JKL_counter", labels => [qw( x y )], ); # inc by ARRAYref $metrics->inc_counter( ghi => [ label => "value" ] ); $metrics->inc_counter( jkl => [ x => 10, y => 20 ] ); is( Metrics::Any::Adapter::Test->metrics, "the_GHI_counter label:value = 1\n" . "the_JKL_counter x:10 y:20 = 1\n", 'Metrics::Any::Adapter::Test->metrics after increment with label by ARRAYref' ); # inc by HASHref $metrics->inc_counter( ghi => { label => "value" } ); $metrics->inc_counter( jkl => { x => 10, y => 20 } ); is( Metrics::Any::Adapter::Test->metrics, "the_GHI_counter label:value = 2\n" . "the_JKL_counter x:10 y:20 = 2\n", 'Metrics::Any::Adapter::Test->metrics after increment with label by HASHref' ); # legacy inc by list of values $metrics->inc_counter( ghi => "value" ); $metrics->inc_counter( jkl => 10, 20 ); is( Metrics::Any::Adapter::Test->metrics, "the_GHI_counter label:value = 3\n" . "the_JKL_counter x:10 y:20 = 3\n", 'Metrics::Any::Adapter::Test->metrics after increment with label by legacy value list' ); } # distributions { Metrics::Any::Adapter::Test->clear; $metrics->make_distribution( distribution => name => "the_ABC_distribution" ); $metrics->report_distribution( distribution => 150 ); is( Metrics::Any::Adapter::Test->metrics, "the_ABC_distribution_count = 1\n" . "the_ABC_distribution_total = 150\n", 'Metrics::Any::Adapter::Test->metrics after ->report_distribution' ); } # gauges { Metrics::Any::Adapter::Test->clear; $metrics->make_gauge( gauge => name => "the_ABC_gauge" ); $metrics->set_gauge_to( gauge => 30 ); is( Metrics::Any::Adapter::Test->metrics, "the_ABC_gauge = 30\n", 'Metrics::Any::Adapter::Test->metrics after ->set_gauge_to' ); $metrics->inc_gauge_by( gauge => 10 ); is( Metrics::Any::Adapter::Test->metrics, "the_ABC_gauge = 40\n", 'Metrics::Any::Adapter::Test->metrics after ->inc_gauge_by' ); } # timers { Metrics::Any::Adapter::Test->clear; $metrics->make_timer( timer => name => "the_ABC_timer" ); $metrics->report_timer( timer => 0.02 ); is( Metrics::Any::Adapter::Test->metrics, "the_ABC_timer_count = 1\n" . "the_ABC_timer_total = 0.02\n", 'Metrics::Any::Adapter::Test->metrics after ->report_timer' ); } ok( $metrics, '$metrics is still true at EOF' ); done_testing; Metrics-Any-0.07/t/20name-prefix.t000444001750001750 272714076045756 15504 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; use Metrics::Any '$metrics', name_prefix => [qw( testing )]; use Metrics::Any::Adapter 'Test'; # Force the adapter to exist $metrics->adapter; # Prefix is applied { Metrics::Any::Adapter::Test->clear; $metrics->make_counter( c => name => [qw( counter )] ); $metrics->inc_counter( c => ); $metrics->make_distribution( d => name => [qw( distribution )] ); $metrics->report_distribution( d => 100 ); $metrics->make_gauge( g => name => [qw( gauge )] ); $metrics->inc_gauge( g => ); $metrics->make_timer( t => name => [qw( timer )] ); $metrics->report_timer( t => 2 ); is( Metrics::Any::Adapter::Test->metrics, <<'EOF', testing_counter = 1 testing_distribution_count = 1 testing_distribution_total = 100 testing_gauge = 1 testing_timer_count = 1 testing_timer_total = 2 EOF 'Metrics have name prefices' ); } # Default names { Metrics::Any::Adapter::Test->clear; $metrics->make_counter( 'c2' ); $metrics->inc_counter( c2 => ); $metrics->make_distribution( 'd2' ); $metrics->report_distribution( d2 => 100 ); $metrics->make_gauge( 'g2' ); $metrics->inc_gauge( g2 => ); $metrics->make_timer( 't2' ); $metrics->report_timer( t2 => 2 ); is( Metrics::Any::Adapter::Test->metrics, <<'EOF', testing_c2 = 1 testing_d2_count = 1 testing_d2_total = 100 testing_g2 = 1 testing_t2_count = 1 testing_t2_total = 2 EOF 'Metrics have name prefices' ); } done_testing; Metrics-Any-0.07/t/21nonstrict.t000444001750001750 176214076045756 15313 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; use Test::Fatal; use Metrics::Any '$metrics', strict => 0; use Metrics::Any::Adapter 'Test'; # Force the adapter to exist $metrics->adapter; # without labels { Metrics::Any::Adapter::Test->clear; $metrics->inc_counter( auto_counter => ); $metrics->report_distribution( auto_distribution => 5 ); $metrics->inc_gauge( auto_gauge => ); $metrics->report_timer( auto_timer => 0.1 ); is( Metrics::Any::Adapter::Test->metrics, <<'EOF', auto_counter = 1 auto_distribution_count = 1 auto_distribution_total = 5 auto_gauge = 1 auto_timer_count = 1 auto_timer_total = 0.1 EOF 'Metrics are registered' ); } # labelled { Metrics::Any::Adapter::Test->clear; $metrics->inc_counter( by_ARRAY => [ one => 1 ] ); $metrics->inc_counter( by_HASH => [ two => 2 ] ); is( Metrics::Any::Adapter::Test->metrics, <<'EOF', by_ARRAY one:1 = 1 by_HASH two:2 = 1 EOF 'Metrics are registered with labels' ); } done_testing; Metrics-Any-0.07/t/22disable-package.t000444001750001750 320114076045756 16253 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; BEGIN { $ENV{METRICS_ANY_DISABLE} = "APackage,ANamespace::*"; } use Metrics::Any::Adapter 'Test'; require Metrics::Any::Adapter::Test; package APackage { use Metrics::Any '$metrics'; $metrics->adapter; Test::More::ok( !$metrics, '$metrics is false in disabled package' ); $metrics->make_counter( c => name => [qw( counter )] ); $metrics->inc_counter( c => ); Test::More::is( Metrics::Any::Adapter::Test->metrics, "", 'No metrics in disabled package' ); } package ANamespace { use Metrics::Any '$metrics'; $metrics->adapter; Test::More::ok( !$metrics, '$metrics is false in disabled namespace' ); $metrics->make_counter( c => name => [qw( counter )] ); $metrics->inc_counter( c => ); Test::More::is( Metrics::Any::Adapter::Test->metrics, "", 'No metrics in disabled namespace' ); } package ANamespace::here { use Metrics::Any '$metrics'; $metrics->adapter; Test::More::ok( !$metrics, '$metrics is false in subpackage of disabled namespace' ); $metrics->make_counter( c => name => [qw( counter )] ); $metrics->inc_counter( c => ); Test::More::is( Metrics::Any::Adapter::Test->metrics, "", 'No metrics in subpackage of disabled namespace' ); } package BPackage { use Metrics::Any '$metrics'; Test::More::ok( $metrics, '$metrics is true in non-disabled package' ); $metrics->make_counter( c => name => [qw( counter )] ); $metrics->inc_counter( c => ); Test::More::is( Metrics::Any::Adapter::Test->metrics, <<'EOF', counter = 1 EOF 'Metrics in non-disabled package still work' ); } done_testing; Metrics-Any-0.07/t/99pod.t000444001750001750 25614076045756 14046 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();