class PrometheusPushMetric: """ This class pushes cost metrics to the given prometheus push gateway. """ def __init__(self, aws_account_id, prom_gateway, metric_name, metric_desc, **labels): """ Args: aws_account_id : 12 digit AWS account id without hyphen prom_gateway : IP or DNS name of push gateway instance metric_name : Name of the prometheus metric metric_desc : Short description about the metric **labels : Is a dict object with key as label name and value as label values """ self.util = Utils() self.logger = LOGGER('__PrometheusPushMetric__').config() # Create a list of Metric objects self.registry = CollectorRegistry() self.account_id = aws_account_id self.prom_gateway = prom_gateway self.metric_name = metric_name self.labels = list(labels.keys()) # Add year, month, day labels if not all(label in self.labels for label in ['year', 'month', 'day']): self.labels.extend(['year', 'month', 'day']) # Update labels dict with key account_id and value 12 digit account id, if account_id label is not passed # account_id is a mandatory label required for each metric if 'account_id' not in self.labels: self.labels.extend(['account_id']) self.metric = Gauge(metric_name, metric_desc, self.labels, registry=self.registry) def push(self, metric_value, **labels): """ Push metrics to prometheus push gateway instance Args: metric_value : string data type, prometheus metric name, examp **labels : Dict data type with promethous labels and values Returns: """ today = self.util.get_day_month_year() # job label to be attached to all pushed metrics job_name = "AWS_%s_%s" % (self.account_id, self.metric_name) timestamp_labels = { 'year': today.year, 'month': today.month, 'day': today.day } labels.update(timestamp_labels) # Update the account_id label value if 'account_id' not in labels.keys(): labels['account_id'] = self.account_id # Validate if metric has all required params: name, documentation, type, unit self.metric.describe() self.logger.info(labels) # Update metrics labels self.metric.labels(**labels).set(metric_value) # Push metrics to Prometheus gateway instance push_to_gateway(self.prom_gateway, job=job_name, registry=self.registry)