Package: prometheus-metrics-proto
prometheus_metrics_protoTheprometheus_metrics_protopackage provides Prometheus Protobuf data
structures and a set of helper functions to assist generating Prometheus
Protocol Buffer format metrics and serializing them in preparation for
network transfer.The collection of metrics and the management of Summary Quantiles and
Histogram Buckets are outside the scope of functionality provided by
this package.An example of a project usingprometheus_metrics_protoisaioprometheuswhich uses it
within the the BinaryFormatter.The Protocol Buffer specification used byprometheus_metrics_protowas
obtained from the Prometheus [client model[(https://github.com/prometheus/client_model/blob/master/metrics.proto)
repo.Install$pipinstallprometheus_metrics_protoExampleTheprometheus_metrics_protopackage provides helper functions to assist with
generating Prometheus metrics objects.The example below shows how these functions can be used to construct metrics
and encode them into a format suitable to send to Prometheus server in a
response.#!/usr/bin/env python"""This script demonstrates the high level helper functions used to assistcreating various metrics kinds as well as how to encode the metrics intoa form that can be sent to Prometheus server."""importprometheus_metrics_protoaspmpdefmain():# Define some labels that we want added to all metrics. These labels are# independent of the instance labels that define a metric as unique.# These could be used to add hostname, app name, etc.const_labels={"host":"examplehost","app":"my_app"}# Create a Counter metric to track logged in users. This counter has# 5 separate instances.# We'll make use of the optional const_labels argument to add extra# constant labels.# We will also add a timestamp to the metric instances.# We will request that the labels be sorted.cm=pmp.create_counter("logged_users_total","Logged users in the application.",(({"country":"sp","device":"desktop"},520),({"country":"us","device":"mobile"},654),({"country":"uk","device":"desktop"},1001),({"country":"de","device":"desktop"},995),({"country":"zh","device":"desktop"},520),),timestamp=True,const_labels=const_labels,ordered=True,)# Create a Gauge metric, similar to the counter above.gm=pmp.create_gauge("logged_users_total","Logged users in the application.",(({"country":"sp","device":"desktop"},520),({"country":"us","device":"mobile"},654),({"country":"uk","device":"desktop"},1001),({"country":"de","device":"desktop"},995),({"country":"zh","device":"desktop"},520),),timestamp=True,const_labels=const_labels,ordered=True,)# Now lets create a Summary and Histogram metric object. These forms# of metrics are slightly more complicated.## Remember, the collection of metrics and the management of Summary# Quantiles and Histogram Buckets are outside the scope of# functionality provided by this package.## The following examples assume they are taking the data values from# a management library that can also emit the sum and count fields# expected for both Summary and Histogram metrics.# Create a Summary metric. The values for a summary are slightly# different to a Counter or Gauge. They are composed of a dict representing# the various quantile values of the metric. The count and sum are# expected to be present in this dict.sm=pmp.create_summary("request_payload_size_bytes","Request payload size in bytes.",(({"route":"/"},{0.5:4.0,0.9:5.2,0.99:5.2,"sum":25.2,"count":4}),({"route":"/data"},{0.5:4.0,0.9:5.2,0.99:5.2,"sum":25.2,"count":4},),),timestamp=True,const_labels=const_labels,ordered=True,)# Create a Histogram metric. The values for a histogram are slightly# different to a Counter or Gauge. They are composed of a dict representing# the various bucket values of the metric. The cumulative count and sum# values are expected to be present in this dict.## Libraries manageing buckets typically have add a POS_INF upper bound to# catch values beyond the largest bucket bound. Simulate this behavior in# the data below.POS_INF=float("inf")hm=pmp.create_histogram("request_latency_seconds","Request latency in seconds.",(({"route":"/"},{5.0:3,10.0:2,15.0:1,POS_INF:0,"count":6,"sum":46.0},),({"route":"/data"},{5.0:3,10.0:2,15.0:1,POS_INF:0,"count":6,"sum":46.0},),),timestamp=True,const_labels=const_labels,ordered=True,)# Serialize a sequence of metrics into a payload suitable for network# transmission.input_metrics=(cm,gm,sm,hm)payload=pmp.encode(*input_metrics)assertisinstance(payload,bytes)# De-serialize the payload into a sequence of MetricsFamily objects.recovered_metrics=pmp.decode(payload)# Confirm that the round trip re-produced the same number of metrics# and that the metrics are identical.assertlen(recovered_metrics)==len(input_metrics)forrecovered_metric,input_metricinzip(recovered_metrics,input_metrics):assertrecovered_metric==input_metricformetricininput_metrics:print(metric)if__name__=="__main__":main()If you simply want to access the Prometheus Protocol Buffer objects directly
and generate instances yourself simply import them from the package as
follows:fromprometheus_metrics_protoimport(COUNTER,GAUGE,SUMMARY,HISTOGRAM,Bucket,Counter,Gauge,Histogram,LabelPair,Metric,MetricFamily,Summary,Quantile)LicenseThis project is released under the MIT license.BackgroundCreating metrics that can be ingested by Prometheus is relatively simple,
but does require knowledge of how they are composed.The Prometheus server expects to ingestMetricsFamilyobjects when it
scrapes an endpoint exposing Protocol Buffer format data.AMetricFamilyobject is a container that holds the metric name, a help
string andMetricobjects. EachMetricFamilywithin the same
exposition must have a unique name.AMetricobject is a container for a single instance of a specific metric
type. Valid metric types are Counter, Gauge, Histogram and Summary. EachMetricwithin the sameMetricFamilymust have a unique set ofLabelPairfields. This is commonly referred to as multi-dimensional metrics.DevelopmentGet the source$gitclonegit@github.com:claws/prometheus_metrics_proto.git$cdprometheus_metrics_protoSetupThe best way to work onprometheus_metrics_protois to create a virtual env.
This isolates your work from other project's dependencies and ensures that any
commands are pointing at the correct tools.You may need to explicitly specify which Python to use if you have
multiple Python's available on your system  (e.g.python3,python3.8).$python3-mvenvvenv--promptpmp$sourcevenv/bin/activate(pmp)$(pmp)$pipinstallpip--upgradeThe following steps assume you are operating in a virtual environment.To exit the virtual environment simply typedeactivate.Install Development EnvironmentRules in the convenience Makefile depend on the development dependencies
being installed. Install the developmental dependencies usingpip. Then
install theprometheus_metrics_protopackage (and its normal dependencies)
in a way that allows you to edit the code after it is installed so that any
changes take effect immediately.(pmp)$pipinstall-rrequirements.dev.txt(pmp)$pipinstall-e.Familiarise yourself with the convenience Makefile rules by running make
without any rule specified.$makeCode StyleThis project uses the Black code style formatter for consistent code style.
A Makefile convenience rule is available to apply code style compliance.(pmp)$makestyleTestThe easiest method to run all of the unit tests is to run themake testrule from the top level directory. This runs the standard libraryunittesttool which discovers all the unit tests and runs them.(pmp)$maketestor(pmp)$maketest-verboseCoverageA Makefile convenience rule is available to check how much of the code is
covered by tests.(pmp)$makecoverageThe test code coverage report can be foundhere <htmlcov/index.html>_RegenerateThe project has placed the code stub (prometheus_metrics_pb2.py),
generated by the Google Protocol Buffers code generation tool, under source
control.If this file needs to be regenerated in the future use the following procedure:(pmp)$makeregenerateRelease ProcessThe following steps are used to make a new software release:Ensure that the version label in__init__.pyis updated.Create the distribution. This project produces an artefact called a pure
Python wheel. Only Python3 is supported by this package.(pmp)$makedistTest distribution. This involves creating a virtual environment, installing
the distribution in it and running the tests. These steps have been captured
for convenience in a Makefile rule.(pmp)$makedist-testUpload to PyPI.(pmp)$makedist-uploadCreate and push a repo tag to Github.git tag YY.MM.MICRO -m "A meaningful release tag comment"git tag  # check release tag is in listgit push --tags origin masterGithub will create a release tarball at:https://github.com/{username}/{repo}/tarball/{tag}.tar.gz