| 1 |
# Copyright (c) 2018, The Jaeger Authors |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
from jaeger_client.metrics import MetricsFactory |
| 16 |
from collections import defaultdict |
| 17 |
from prometheus_client import Counter, Gauge |
| 18 |
from typing import Any, Optional, Dict, Callable, DefaultDict |
| 19 |
|
| 20 |
|
| 21 |
class PrometheusMetricsFactory(MetricsFactory): |
| 22 |
""" |
| 23 |
Provides metrics backed by Prometheus |
| 24 |
""" |
| 25 |
def __init__(self, namespace: str = '', service_name_label: Optional[str] = None) -> None: |
| 26 |
self._cache: DefaultDict = defaultdict(object) |
| 27 |
self._namespace = namespace |
| 28 |
self._service_name_label = service_name_label |
| 29 |
|
| 30 |
def _get_tag_name_list(self, tags): |
| 31 |
if tags is None: |
| 32 |
return [] |
| 33 |
tag_name_list = [] |
| 34 |
for key in tags.keys(): |
| 35 |
tag_name_list.append(key) |
| 36 |
return tag_name_list |
| 37 |
|
| 38 |
def _get_metric(self, metricType, name, tags): |
| 39 |
if self._service_name_label: |
| 40 |
if tags is None: |
| 41 |
tags = {'service': self._service_name_label} |
| 42 |
else: |
| 43 |
tags['service'] = self._service_name_label |
| 44 |
|
| 45 |
label_name_list = self._get_tag_name_list(tags) |
| 46 |
cache_key = name + '@@'.join(label_name_list) |
| 47 |
|
| 48 |
metric = self._cache.get(cache_key) |
| 49 |
if metric is None: |
| 50 |
metric = metricType(name=name, documentation=name, |
| 51 |
labelnames=label_name_list, namespace=self._namespace) |
| 52 |
self._cache[cache_key] = metric |
| 53 |
|
| 54 |
if tags is not None and len(tags) > 0: |
| 55 |
metric = metric.labels(**tags) |
| 56 |
|
| 57 |
return metric |
| 58 |
|
| 59 |
def create_counter( |
| 60 |
self, name: str, tags: Optional[Dict[str, Any]] = None |
| 61 |
) -> Callable[[int], None]: |
| 62 |
counter = self._get_metric(Counter, name, tags) |
| 63 |
|
| 64 |
def increment(value): |
| 65 |
counter.inc(value) |
| 66 |
return increment |
| 67 |
|
| 68 |
def create_gauge( |
| 69 |
self, name: str, tags: Optional[Dict[str, Any]] = None |
| 70 |
) -> Callable[[float], None]: |
| 71 |
gauge = self._get_metric(Gauge, name, tags) |
| 72 |
|
| 73 |
def update(value): |
| 74 |
gauge.set(value) |
| 75 |
return update |