get MetricSnapshot formatted value string
1748
public static String getMetricValue(MetricSnapshot snapshot) {
        if (snapshot == null) return null;
        MetricType type = MetricType.parse(snapshot.get_metricType());
        switch (type) {
            case COUNTER:
                return format(snapshot.get_longValue());
            case GAUGE:
                return format(snapshot.get_doubleValue());
            case METER:
                return format(snapshot.get_m1());
            case HISTOGRAM:
                return format(snapshot.get_mean());
            default:
                return "0";
        }
    }
620588
function (metric) {
      var now = (new Date().getTime()).toFixed(0)
      var line = null
      if (metric.sct === 'OS' && /collectd/.test(metric.name)) {
        line = this.collectdFormatLine(metric)
      } else {
        if (metric.sct === 'OS') {
          // new OS metric format
          if (metric.filters instanceof Array) {
            line = util.format('%d\t%s\t%d\t%s\t%s', now, metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value))
          } else {
            line = util.format('%d\t%s\t%d\t%s', now, metric.name, metric.ts, formatArray(metric.value))
          }
          logger.log(line)
        } else {
          line = util.format('%d\t%s\t%d\t%s\t%s', now, (metric.type || this.defaultType) + '-' + metric.name, metric.ts, formatArray(metric.filters), formatArray(metric.value))
          logger.log(line)
        }
      }
      return line
    }
806325
def metric(self, measurement_name, values, tags=None, timestamp=None):
        
        if not measurement_name or values in (None, {}):
            # Don't try to send empty data
            return

        tags = tags or {}

        # Do a shallow merge of the metric tags and global tags
        all_tags = dict(self.tags, **tags)

        # Create a metric line from the input and then send it to socket
        line = Line(measurement_name, values, all_tags, timestamp)
        self.send(line.to_line_protocol())
1210309
def log_metrics(self, metrics_by_name, info):
        
        try:
            metrics_path = os.path.join(self.dir, "metrics.json")
            with open(metrics_path, 'r') as f:
                saved_metrics = json.load(f)
        except IOError:
            # We haven't recorded anything yet. Start Collecting.
            saved_metrics = {}

        for metric_name, metric_ptr in metrics_by_name.items():

            if metric_name not in saved_metrics:
                saved_metrics[metric_name] = {"values": [],
                                              "steps": [],
                                              "timestamps": []}

            saved_metrics[metric_name]["values"] += metric_ptr["values"]
            saved_metrics[metric_name]["steps"] += metric_ptr["steps"]

            # Manually convert them to avoid passing a datetime dtype handler
            # when we're trying to convert into json.
            timestamps_norm = [ts.isoformat()
                               for ts in metric_ptr["timestamps"]]
            saved_metrics[metric_name]["timestamps"] += timestamps_norm

        self.save_json(saved_metrics, 'metrics.json')
842840
def format_metric_values(self, metric_values):
    """"""

    # Early in training, metric_values may actually be None.
    loss_str = 'N/A'
    accuracy_str = 'N/A'
    try:
      loss_str = 'loss: %.3f' % metric_values[0]
      accuracy_str = 'accuracy: %.3f' % metric_values[1]
    except (TypeError, IndexError):
      pass

    return '%s, %s' % (loss_str, accuracy_str)
424486
def format(file_metrics, build_metrics):
    """"""
    metrics = {'files': file_metrics}
    if build_metrics:
        metrics['build'] = build_metrics
    body = json.dumps(metrics, sort_keys=True, indent=4) + '\n'
    return body
1046383
def _get_value_from_json(self, dict_path, metrics_json):
        
        for key in dict_path.split('.'):
            if key in metrics_json:
                metrics_json = metrics_json.get(key)
            else:
                return None
        return metrics_json
341102
function getValueText(data) {
            let value = data[valueLabel];
            let valueText;

            if (data.missingValue) {
                valueText = '-';
            } else {
                valueText = getFormattedValue(value).toString();
            }

            return valueText;
        }
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);
		}
	}
1030022
def run_tag_from_session_and_metric(session_name, metric_name):
  
  assert isinstance(session_name, six.string_types)
  assert isinstance(metric_name, api_pb2.MetricName)
  # os.path.join() will append a final slash if the group is empty; it seems
  # like multiplexer.Tensors won't recognize paths that end with a '/' so
  # we normalize the result of os.path.join() to remove the final '/' in that
  # case.
  run = os.path.normpath(os.path.join(session_name, metric_name.group))
  tag = metric_name.tag
  return run, tag
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)
666418
def get_metrics_from_perfdata(self, service, perf_data):
        """"""
        result = []
        metrics = PerfDatas(perf_data)

        for metric in metrics:
            logger.debug("service: %s, metric: %s (%s)", service, metric, metric.__dict__)

            if metric.name in ['time']:
                metric.name = "duration"
            name = sanitize_name(metric.name)
            name = self.multiple_values.sub(r'.\1', name)
            if not name:
                continue

            # get metric value and its thresholds values if they exist
            name_value = {
                name: metric.value,
                'uom_' + name: metric.uom
            }

            # Get or ignore extra values depending upon module configuration
            if metric.warning and self.send_warning:
                name_value[name + '_warn'] = metric.warning

            if metric.critical and self.send_critical:
                name_value[name + '_crit'] = metric.critical

            if metric.min and self.send_min:
                name_value[name + '_min'] = metric.min

            if metric.max and self.send_max:
                name_value[name + '_max'] = metric.max

            for key, value in name_value.items():
                result.append((key, value, metric.uom))

        logger.debug("Metrics: %s - %s", service, result)
        return result
725572
public static Metric getMetricToAnnotate(String metric) {
        Metric result = null;

        if (metric != null && !metric.isEmpty()) {
            Pattern pattern = Pattern.compile(
                "([\\w,\\-,\\.,/]+):([\\w,\\-,\\.,/]+)(\\{(?:[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)(?:,[\\w,\\-,\\.,/]+=[\\w,\\-,\\.,/,\\*,|]+)*\\})?:([\\w,\\-,\\.,/]+)");
            Matcher matcher = pattern.matcher(metric.replaceAll("\\s", ""));

            if (matcher.matches()) {
                String scopeName = matcher.group(1);
                String metricName = matcher.group(2);
                String tagString = matcher.group(3);
                Map<String, String> tags = new HashMap<>();

                if (tagString != null) {
                    tagString = tagString.replaceAll("\\{", "").replaceAll("\\}", "");
                    for (String tag : tagString.split(",")) {
                        String[] entry = tag.split("=");

                        tags.put(entry[0], entry[1]);
                    }
                }
                result = new Metric(scopeName, metricName);
                result.setTags(tags);
            }
        }
        return result;
    }
265448
def _get_thumbnail_filename(self, source, geometry_string, options):
        
        key = tokey(source.key, geometry_string, serialize(options))
        # make some subdirs
        path = '%s/%s/%s' % (key[:2], key[2:4], key)
        return '%s%s.%s' % (settings.THUMBNAIL_PREFIX, path, EXTENSIONS[options['format']])
963188
private Map<MetricName, MetricValue> get_metrics_(DateTime now, Context ctx) {
        final Consumer<Alert> alert_manager = ctx.getAlertManager();
        final long failed_collections = registry_.getFailedCollections();
        final boolean has_config = registry_.hasConfig();
        final Optional<Duration> scrape_duration = registry_.getScrapeDuration();
        final Optional<Duration> rule_eval_duration = registry_.getRuleEvalDuration();
        final Optional<Duration> processor_duration = registry_.getProcessorDuration();
        first_scrape_ts_.compareAndSet(null, now);  // First time, register the timestamp.
        final Duration uptime = new Duration(first_scrape_ts_.get(), now);

        final Optional<DateTime> last_scrape = last_scrape_;
        last_scrape_ = Optional.of(now);

        final long metric_count = ctx.getTSData().getCurrentCollection().getTSValues().stream()
                .map(TimeSeriesValue::getMetrics)
                .collect(Collectors.summingLong(Map::size));

        alert_manager.accept(new Alert(now, MONITOR_FAIL_ALERT, () -> "builtin rule", Optional.of(failed_collections != 0), MON_ALERT_DURATION, "builtin rule: some collectors failed", EMPTY_MAP));
        alert_manager.accept(new Alert(now, HAS_CONFIG_ALERT, () -> "builtin rule", Optional.of(!has_config), Duration.ZERO, "builtin rule: monitor has no configuration file", EMPTY_MAP));

        Map<MetricName, MetricValue> result = new HashMap<>();
        result.put(FAILED_COLLECTIONS_METRIC, MetricValue.fromIntValue(failed_collections));
        result.put(GROUP_COUNT_METRIC, MetricValue.fromIntValue(ctx.getTSData().getCurrentCollection().getGroups(x -> true).size()));
        result.put(METRIC_COUNT_METRIC, MetricValue.fromIntValue(metric_count));
        result.put(CONFIG_PRESENT_METRIC, MetricValue.fromBoolean(has_config));
        result.put(SCRAPE_DURATION, opt_duration_to_metricvalue_(scrape_duration));
        result.put(RULE_EVAL_DURATION, opt_duration_to_metricvalue_(rule_eval_duration));
        result.put(PROCESSOR_DURATION, opt_duration_to_metricvalue_(processor_duration));
        result.put(UPTIME_DURATION, duration_to_metricvalue_(uptime));
        result.put(SCRAPE_COUNT, MetricValue.fromIntValue(++scrape_count_));
        result.put(SCRAPE_INTERVAL, opt_duration_to_metricvalue_(last_scrape.map(prev -> new Duration(prev, now))));
        result.put(SCRAPE_TS, MetricValue.fromIntValue(now.getMillis()));
        return result;
    }
372975
private function getMetrics($rawValue)
    {
        $metrics = [];

        foreach ($rawValue as $metricName => $value) {
            if (!is_array($value) || !isset($value['buckets'])) {
                $metricName = $metricName == 'doc_count' ? 'count' : $metricName;
                if (is_array($value) && isset($value['value_as_string'])) {
                    $value = $value['value_as_string'];
                } elseif (is_array($value) && isset($value['value'])) {
                    $value = $value['value'];
                }
                $metrics[$metricName] = $value;
            }
        }

        return $metrics;
    }
874207
def _extract_metric_from_map(self, _m, messages, obj_map, obj_help):
        
        _obj = metrics_pb2.MetricFamily()
        _obj.name = _m
        _obj.type = self.METRIC_TYPES.index(obj_map[_m])
        if _m in obj_help:
            _obj.help = obj_help[_m]
        # trick for histograms
        _newlbl = _m
        if obj_map[_m] == 'histogram':
            _newlbl = '{}_bucket'.format(_m)
        # Loop through the array of metrics ({labels, value}) built earlier
        for _metric in messages[_newlbl]:
            # in the case of quantiles and buckets, they need to be grouped by labels
            if obj_map[_m] in ['summary', 'histogram'] and len(_obj.metric) > 0:
                _label_exists = False
                _metric_minus = {k: v for k, v in list(iteritems(_metric['labels'])) if k not in ['quantile', 'le']}
                _metric_idx = 0
                for mls in _obj.metric:
                    _tmp_lbl = {idx.name: idx.value for idx in mls.label}
                    if _metric_minus == _tmp_lbl:
                        _label_exists = True
                        break
                    _metric_idx = _metric_idx + 1
                if _label_exists:
                    _g = _obj.metric[_metric_idx]
                else:
                    _g = _obj.metric.add()
            else:
                _g = _obj.metric.add()
            if obj_map[_m] == 'counter':
                _g.counter.value = float(_metric['value'])
            elif obj_map[_m] == 'gauge':
                _g.gauge.value = float(_metric['value'])
            elif obj_map[_m] == 'summary':
                if '{}_count'.format(_m) in messages:
                    _g.summary.sample_count = long(self.get_metric_value_by_labels(messages, _metric, _m, 'count'))
                if '{}_sum'.format(_m) in messages:
                    _g.summary.sample_sum = self.get_metric_value_by_labels(messages, _metric, _m, 'sum')
            # TODO: see what can be done with the untyped metrics
            elif obj_map[_m] == 'histogram':
                if '{}_count'.format(_m) in messages:
                    _g.histogram.sample_count = long(self.get_metric_value_by_labels(messages, _metric, _m, 'count'))
                if '{}_sum'.format(_m) in messages:
                    _g.histogram.sample_sum = self.get_metric_value_by_labels(messages, _metric, _m, 'sum')
            # last_metric = len(_obj.metric) - 1
            # if last_metric >= 0:
            for lbl in _metric['labels']:
                # In the string format, the quantiles are in the labels
                if lbl == 'quantile':
                    # _q = _obj.metric[last_metric].summary.quantile.add()
                    _q = _g.summary.quantile.add()
                    _q.quantile = float(_metric['labels'][lbl])
                    _q.value = float(_metric['value'])
                # The upper_bounds are stored as "le" labels on string format
                elif obj_map[_m] == 'histogram' and lbl == 'le':
                    # _q = _obj.metric[last_metric].histogram.bucket.add()
                    _q = _g.histogram.bucket.add()
                    _q.upper_bound = float(_metric['labels'][lbl])
                    _q.cumulative_count = long(float(_metric['value']))
                else:
                    # labels deduplication
                    is_in_labels = False
                    for _existing_lbl in _g.label:
                        if lbl == _existing_lbl.name:
                            is_in_labels = True
                    if not is_in_labels:
                        _l = _g.label.add()
                        _l.name = lbl
                        _l.value = _metric['labels'][lbl]
        return _obj