1+ import logging
2+ import os
3+ import shutil
14import warnings
25from time import perf_counter as time_now
36
1518 prometheus_module = None
1619
1720
21+ logger = logging .getLogger (__name__ )
22+
1823_METRICS = {}
1924_REGISTRY = None
2025
2126
27+ PROMETHEUS_MULTIPROC_DIR = os .getenv ("PROMETHEUS_MULTIPROC_DIR" )
28+
29+
2230def get_registry ():
2331 global _REGISTRY
2432
2533 if _REGISTRY is None :
26- _REGISTRY = prometheus_module .CollectorRegistry ()
34+ if PROMETHEUS_MULTIPROC_DIR : # pragma: no cover
35+ from prometheus_client import multiprocess
36+
37+ _reset_multiproc_folder_content ()
38+ # Ref: https://prometheus.github.io/client_python/multiprocess/
39+ _REGISTRY = prometheus_module .CollectorRegistry ()
40+ multiprocess .MultiProcessCollector (_REGISTRY )
41+ else :
42+ _REGISTRY = prometheus_module .REGISTRY
43+ logger .warning ("Prometheus metrics will run in single-process mode only." )
2744 return _REGISTRY
2845
2946
@@ -170,6 +187,12 @@ def metrics_view(request):
170187 return resp
171188
172189
190+ def _reset_multiproc_folder_content (): # pragma: no cover
191+ if os .path .exists (PROMETHEUS_MULTIPROC_DIR ):
192+ shutil .rmtree (PROMETHEUS_MULTIPROC_DIR )
193+ os .mkdir (PROMETHEUS_MULTIPROC_DIR )
194+
195+
173196def includeme (config ):
174197 if prometheus_module is None :
175198 error_msg = (
@@ -190,6 +213,7 @@ def includeme(config):
190213 # This is mainly useful in tests, where the plugin is included
191214 # several times with different settings.
192215 registry = get_registry ()
216+
193217 for collector in _METRICS .values ():
194218 try :
195219 registry .unregister (collector )
0 commit comments