Send a metric to Statsd.

        :param list path: The metric path to record
        :param mixed value: The value to record
        :param str metric_type: The metric type
540053
def send(self, path, value, metric_type):
        
        msg = self._msg_format.format(
            path=self._build_path(path, metric_type),
            value=value,
            metric_type=metric_type)

        LOGGER.debug('Sending %s to %s:%s', msg.encode('ascii'),
                     self._host, self._port)

        try:
            if self._tcp:
                if self._sock.closed():
                    return
                return self._sock.write(msg.encode('ascii'))

            self._sock.sendto(msg.encode('ascii'), (self._host, self._port))
        except iostream.StreamClosedError as error:  # pragma: nocover
            LOGGER.warning('Error sending TCP statsd metric: %s', error)
        except (OSError, socket.error) as error:  # pragma: nocover
            LOGGER.exception('Error sending statsd metric: %s', error)
1090101
def assert_metric(self, name, value=None, tags=None, count=None, at_least=1, hostname=None, metric_type=None):
        
        self._asserted.add(name)
        tags = normalize_tags(tags, sort=True)

        candidates = []
        for metric in self.metrics(name):
            if value is not None and not self.is_aggregate(metric.type) and value != metric.value:
                continue

            if tags and tags != sorted(metric.tags):
                continue

            if hostname and hostname != metric.hostname:
                continue

            if metric_type is not None and metric_type != metric.type:
                continue

            candidates.append(metric)

        if value is not None and candidates and all(self.is_aggregate(m.type) for m in candidates):
            got = sum(m.value for m in candidates)
            msg = "Expected count value for '{}': {}, got {}".format(name, value, got)
            assert value == got, msg

        if count is not None:
            msg = "Needed exactly {} candidates for '{}', got {}".format(count, name, len(candidates))
            assert len(candidates) == count, msg
        else:
            msg = "Needed at least {} candidates for '{}', got {}".format(at_least, name, len(candidates))
            assert len(candidates) >= at_least, msg
627611
def get_validation_metric_points(model_path: str, metric: str):
    
    metrics_path = os.path.join(model_path, C.METRICS_NAME)
    data = read_metrics_file(metrics_path)
    return [(d['%s-val' % metric], cp) for cp, d in enumerate(data, 1)]
73930
def _submit_gauges_from_histogram(self, metric_name, metric, scraper_config, hostname=None):
        
        for sample in metric.samples:
            val = sample[self.SAMPLE_VALUE]
            if not self._is_value_valid(val):
                self.log.debug("Metric value is not supported for metric {}".format(sample[self.SAMPLE_NAME]))
                continue
            custom_hostname = self._get_hostname(hostname, sample, scraper_config)
            if sample[self.SAMPLE_NAME].endswith("_sum"):
                tags = self._metric_tags(metric_name, val, sample, scraper_config, hostname)
                self.gauge(
                    "{}.{}.sum".format(scraper_config['namespace'], metric_name),
                    val,
                    tags=tags,
                    hostname=custom_hostname,
                )
            elif sample[self.SAMPLE_NAME].endswith("_count"):
                tags = self._metric_tags(metric_name, val, sample, scraper_config, hostname)
                self.gauge(
                    "{}.{}.count".format(scraper_config['namespace'], metric_name),
                    val,
                    tags=tags,
                    hostname=custom_hostname,
                )
            elif (
                scraper_config['send_histograms_buckets']
                and sample[self.SAMPLE_NAME].endswith("_bucket")
                and "Inf" not in sample[self.SAMPLE_LABELS]["le"]
            ):
                sample[self.SAMPLE_LABELS]["le"] = float(sample[self.SAMPLE_LABELS]["le"])
                tags = self._metric_tags(metric_name, val, sample, scraper_config, hostname)
                self.gauge(
                    "{}.{}.count".format(scraper_config['namespace'], metric_name),
                    val,
                    tags=tags,
                    hostname=custom_hostname,
                )
965159
def parse_expvar_data(self, data, tags, metrics, max_metrics, namespace):
        '''
        
        '''
        count = 0
        for metric in metrics:
            path = metric.get(PATH)
            metric_type = metric.get(TYPE, DEFAULT_TYPE)
            metric_tags = list(metric.get(TAGS, []))
            metric_tags += tags
            alias = metric.get(ALIAS)

            if not path:
                self.warning("Metric %s has no path" % metric)
                continue

            if metric_type not in SUPPORTED_TYPES:
                self.warning("Metric type %s not supported for this check" % metric_type)
                continue

            keys = path.split("/")
            values = self.deep_get(data, keys)

            if len(values) == 0:
                self.warning("No results matching path %s" % path)
                continue

            tag_by_path = alias is not None

            for traversed_path, value in values:
                actual_path = ".".join(traversed_path)
                path_tag = ["path:%s" % actual_path] if tag_by_path else []

                metric_name = alias or self.normalize(actual_path, namespace, fix_case=True)

                try:
                    float(value)
                except ValueError:
                    self.log.warning("Unreportable value for path %s: %s" % (path, value))
                    continue

                if count >= max_metrics:
                    self.warning(
                        "Reporting more metrics than the allowed maximum. "
                        "Please contact support@datadoghq.com for more information."
                    )
                    return

                SUPPORTED_TYPES[metric_type](self, metric_name, value, metric_tags + path_tag)
                count += 1
110591
def MetricValueTypeFromPythonType(python_type):
  """"""
  if python_type in (int, long):
    return rdf_stats.MetricMetadata.ValueType.INT
  elif python_type == float:
    return rdf_stats.MetricMetadata.ValueType.FLOAT
  else:
    raise ValueError("Invalid value type: %s" % python_type)
613788
def submit_metric(self, name, snmp_value, forced_type, tags=None):
        '''
        
        '''
        tags = [] if tags is None else tags
        if reply_invalid(snmp_value):
            # Metrics not present in the queried object
            self.log.warning("No such Mib available: {}".format(name))
            return

        metric_name = self.normalize(name, prefix="snmp")

        if forced_type:
            if forced_type.lower() == "gauge":
                value = int(snmp_value)
                self.gauge(metric_name, value, tags)
            elif forced_type.lower() == "counter":
                value = int(snmp_value)
                self.rate(metric_name, value, tags)
            else:
                self.warning("Invalid forced-type specified: {} in {}".format(forced_type, name))
                raise Exception("Invalid forced-type in config file: {}".format(name))

            return

        # Ugly hack but couldn't find a cleaner way
        # Proper way would be to use the ASN1 method isSameTypeWith but it
        # wrongfully returns True in the case of CounterBasedGauge64
        # and Counter64 for example
        snmp_class = snmp_value.__class__.__name__
        if snmp_class in SNMP_COUNTERS:
            value = int(snmp_value)
            self.rate(metric_name, value, tags)
            return
        if snmp_class in SNMP_GAUGES:
            value = int(snmp_value)
            self.gauge(metric_name, value, tags)
            return

        self.log.warning("Unsupported metric type %s for %s", snmp_class, metric_name)
503180
def put(self, data):
        
        if not isinstance(data, list):
            data = [data]

        r = collections.defaultdict(list)

        for d in data:
            metric_type = d.pop('type', None)
            if metric_type is None:
                raise HawkularError('Undefined MetricType')
            r[metric_type].append(d)

        # This isn't transactional, but .. ouh well. One can always repost everything.
        for l in r:
            self._post(self._get_metrics_raw_url(self._get_url(l)), r[l],parse_json=False)
75816
protected void processOneMetric(List<String> resultStrings, Server server, Result result, Object value, String addTagName,
									String addTagValue) {
		String metricName = this.metricNameStrategy.formatName(result);

		//
		// Skip any non-numeric values since OpenTSDB only supports numeric metrics.
		//
		if (isNumeric(value)) {
			StringBuilder resultString = new StringBuilder();

			formatResultString(resultString, metricName, result.getEpoch() / 1000L, value);
			addTags(resultString, server);

			if (addTagName != null) {
				addTag(resultString, addTagName, addTagValue);
			}

			if (!typeNames.isEmpty()) {
				this.addTypeNamesTags(resultString, result);
			}

			resultStrings.add(resultString.toString());
		} else {
			log.debug("Skipping non-numeric value for metric {}; value={}", metricName, value);
		}
	}
365172
async def send(self, metric):
        
        message = json.dumps(metric).encode('utf-8')
        await self.loop.create_datagram_endpoint(
            lambda: UDPClientProtocol(message),
            remote_addr=(self.ip, self.port))
997828
def _build_path(self, path, metric_type):
        
        path = self._get_prefixes(metric_type) + list(path)
        return '{}.{}'.format(self._namespace,
                              '.'.join(str(p).replace('.', '-') for p in path))
1248506
def visdom_send_metrics(vis, metrics, update='replace'):
    
    visited = {}

    sorted_metrics = sorted(metrics.columns, key=_column_original_name)
    for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name):
        metric_list = list(metric_list)

        for metric in metric_list:
            if vis.win_exists(metric_basename) and (not visited.get(metric, False)):
                update = update
            elif not vis.win_exists(metric_basename):
                update = None
            else:
                update = 'append'

            vis.line(
                metrics[metric].values,
                metrics.index.values,
                win=metric_basename,
                name=metric,
                opts={
                    'title': metric_basename,
                    'showlegend': True
                },
                update=update
            )

            if metric_basename != metric and len(metric_list) > 1:
                if vis.win_exists(metric):
                    update = update
                else:
                    update = None

                vis.line(
                    metrics[metric].values,
                    metrics.index.values,
                    win=metric,
                    name=metric,
                    opts={
                        'title': metric,
                        'showlegend': True
                    },
                    update=update
                )
276277
def update_stats(self, stats, value, _type, sample_rate=1):
        
        stats = self.format(stats, value, _type, self.prefix)
        self.send(self.sample(stats, sample_rate), self.addr)
564537
def PythonTypeFromMetricValueType(value_type):
  """"""
  if value_type == rdf_stats.MetricMetadata.ValueType.INT:
    return int
  elif value_type == rdf_stats.MetricMetadata.ValueType.FLOAT:
    return float
  else:
    raise ValueError("Unknown value type: %s" % value_type)
1303576
def set_metric_ids(self, key, metric_ids):
        
        with self._lock:
            self._metric_ids[key] = metric_ids
512206
def handle_report_metric_data(self, data):
        
        if data['type'] == 'FINAL':
            self._handle_final_metric_data(data)
        elif data['type'] == 'PERIODICAL':
            if self.assessor is not None:
                self._handle_intermediate_metric_data(data)
            else:
                pass
        else:
            raise ValueError('Data type not supported: {}'.format(data['type']))
1015481
def add_metric(self, labels, value, created=None, timestamp=None):
        
        self.samples.append(Sample(self.name + '_total', dict(zip(self._labelnames, labels)), value, timestamp))
        if created is not None:
            self.samples.append(Sample(self.name + '_created', dict(zip(self._labelnames, labels)), created, timestamp))