Package: prometheus-aioexporter
prometheus-aioexporteris an aysncio-based library to simplify writingPrometheusexporters.Exporters are usually implemented as small daemons that expose metrics
in text format through a web endpoint (usually/metrics).UsageThe library provides aPrometheusExporterScriptclass that serves as an
entry point to create services that export Prometheus metrics via an HTTP(s)
endpoint.Creating a new exporter is just a matter of subclassingPrometheusExporterScriptand implementing a few methods as needed.An example usage is the following:fromprometheus_aioexporterimportPrometheusExporterScriptclassMyExporter(PrometheusExporterScript):"""My Prometheus exporter."""name="my-exporter"defconfigure_argument_parser(self,parser:argparse.ArgumentParser)->None:# Additional arguments to the scriptparser.add_argument("--custom-option",help="a custom option")# ...defconfigure(self,args:argparse.Namespace)->None:# Save attributes that are needed for laterself.data=do_stuff()# ...asyncdefon_application_startup(self,application:aiohttp.web.Application)->None:# Start other asyncio tasks at application startupuse(self.data)# ...asyncdefon_application_shutdown(self,application:aiohttp.web.Application)->None:# Stop other asyncio tasks at application shutdownuse(self.data)# ...script=MyExporter()Exporter command-linePrometheusExporterScriptprovides a few command-line arguments by default:optional arguments:
  -h, --help            show this help message and exit
  -H HOST [HOST ...], --host HOST [HOST ...]
                        host addresses to bind (default: ['localhost'])
  -p PORT, --port PORT  port to run the webserver on (default: 9090)
  --metrics-path METRICS_PATH
                        path under which metrics are exposed (default: /metrics)
  -L {CRITICAL,ERROR,WARNING,INFO,DEBUG}, --log-level {CRITICAL,ERROR,WARNING,INFO,DEBUG}
                        minimum level for log messages (default: WARNING)
  --process-stats       include process stats in metrics (default: False)
  --ssl-private-key     full path to the ssl private key
  --ssl-public-key      full path to the ssl public key
  --ssl-ca              full path to the ssl certificate authority (CA)Further options can be added by implementingconfigure_argument_parser(),
which receives theargparse.ArgumentParserinstance used by the script.Thescriptvariable from the example above can be referenced inpyproject.tomlto generate the script, like[project.scripts]my-exporter="path.to.script:script"Thedescriptionof the exporter can be customized by setting the docstring
in the script class.In order to serve metrics on the HTTPS endpoint bothssl-private-keyandssl-public-keyneed to be define. The ssl certificate authority
(i.e.ssl-ca) is optional.Startup configurationAdditional initial setup (e.g. config file parsing) can be performed by the
script by implementing theconfigure(). This is called at startup with the
parsed argument (anargparse.Namespaceinstance).Metrics configurationThe metrics exported by the script can be set up by callingcreate_metricswith a list ofMetricConfigs. This is typically done inconfigure():defconfigure(self,args:argparse.Namespace)->None:# ...self.create_metrics([MetricConfig("metric1","a metric","gauge"),MetricConfig("metric2","another metric","counter",labels=("l1","l2")),])Web application setupOn startup,PrometheusExporterScriptcreates aPrometheusExporterwhich
includes a web application that exposes metrics.It’s possible to customize and perform additional startup/shutdown tasks by
implementing theon_application_startupandon_application_shutdowncoroutine methods, which are called with the application as parameter.ThePrometheusExporterinstance is accessible viaapplication['exporter']), and provides aset_metric_update_handlermethod to register a hook to update metrics on each request, before the
response is returned to the client.  The registered function must return a
coroutine and is called with a dict mapping metric names to metric objects:asyncdefon_application_startup(self,application:aiohttp.web.Application)->None:# ...application["exporter"].set_metric_update_handler(self._update_handler)asyncdef_update_handler(self,metrics:dict[str,prometheus_client.metrics.MetricWrapperBase]):forname,metricinmetrics.items():metric.set(...)Seeprometheus_aioexporter.samplefor a complete example (the script can be
run asprometheus-aioexporter-sample).