Sample app for collecting metrics into Prometheus by specific event class.
- Python 3.7.x or higher
- Pipfile
Initiate virtual environment and generate Pipfile and Pipfile.lock by running:
pipenv lockInstall dependencies and get into virtual environment.
pipenv install && pipenv shellRunning in local by
python app.pyin case of you want to create your own event
- implement your event class (must end with
_eventsuffix) tometrics/event/ - add your new event class into constant
WHITELISTED_EVENTinmetrics/__init__.py - add
Metrics.record("{event_name}", "{value}")in the last line of code blockwith Metrics("{event_name}") as metrics:.
eg. sample event in metrics/event/sample_event.py
from metrics import Metrics
with Metrics("sample") as metrics:
try:
result = "response"
except Exception as e:
result = {"error": e}
metrics.record(result)- add label(s) you want to save to metric into
LABELSconstant
LABELS["error", "status"]- modify
_transform_result_to_labelsmethod which is responsible for wrapping labels to dict before saving to Prometheus in event class.
def _transform_result_to_labels(self, result: Union[dict, Any]) -> dict:
if isinstance(result, dict) and "error" in result:
return {"status": "error", "error": result["error"]}
else:
return {"status": result["status"], "error": None}