Private: Prepare a metric name before it is sent to the adapter's client.
340266
def prepare(metric, replacement = Separator)
      escaped = Regexp.escape(replacement)
      replace_begin_end_regex = /\A#{escaped}|#{escaped}\Z/

      metric = metric.to_s.gsub(ReplaceRegex, replacement)
      metric.squeeze!(replacement)
      metric.gsub!(replace_begin_end_regex, Nothing)
      metric
    end
646890
def _resolve_metric(self, original_metric_name, metrics_to_collect, prefix=""):
        

        submit_method = (
            metrics_to_collect[original_metric_name][0]
            if isinstance(metrics_to_collect[original_metric_name], tuple)
            else metrics_to_collect[original_metric_name]
        )
        metric_name = (
            metrics_to_collect[original_metric_name][1]
            if isinstance(metrics_to_collect[original_metric_name], tuple)
            else original_metric_name
        )

        return submit_method, self._normalize(metric_name, submit_method, prefix)
235095
function (metric) {
      metric.workerId = workerId
      metric.pid = process.pid
      if (!metric.sct) {
        if (metric.name && /collectd/.test(metric.name)) {
          metric.sct = 'OS'
        } else {
          metric.sct = 'APP'
        }
      }
      if (!metric.ts) {
        metric.ts = new Date().getTime()
      }
      if (!metric.type) {
        metric.type = this.defaultType
      }
      if (!metric.filters && metric.type === 'njs') {
        metric.filters = this.defaultFilters()
      }
      metric.spmLine = this.formatLine(metric)
      this.emit('metric', metric)
      if (metric.name) {
        this.emit(metric.name, metric)
      }
    }
445685
public MetricNameBuilder addDimension(String name, String value) throws MetricsNameSyntaxException {
        return addDimension(name, value, false);
    }
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)
1212910
private String getQualifiedMetricName(String metricName) {
    try {
      if (SecurityUtils.isAuthenticationEnabled(mConfiguration)
          && AuthenticatedClientUser.get(mConfiguration) != null) {
        return Metric.getMetricNameWithTags(metricName, CommonMetrics.TAG_USER,
            AuthenticatedClientUser.get(mConfiguration).getName(), WorkerMetrics.TAG_UFS,
            MetricsSystem.escape(new AlluxioURI(mPath)), WorkerMetrics.TAG_UFS_TYPE,
            mUnderFileSystem.getUnderFSType());
      }
    } catch (IOException e) {
      // fall through
    }
    return Metric.getMetricNameWithTags(metricName, WorkerMetrics.TAG_UFS,
        MetricsSystem.escape(new AlluxioURI(mPath)), WorkerMetrics.TAG_UFS_TYPE,
        mUnderFileSystem.getUnderFSType());
  }
854568
def wf_metric_name?(metric)
      if metric.is_a?(String) && metric.size < 1024 &&
         (metric.match(/^#{DELTA}?[\w\-\.]+$/) ||
          metric.match(%r{^\"#{DELTA}?[\w\-\.\/,]+\"$}))
        return true
      end

      raise Wavefront::Exception::InvalidMetricName
    end
958819
@Override
  public String metricNamePrefix(boolean includeTagKeys) {
    return Joiner.on('.').join(includeTagKeys ? getTags() : this.tags.values());
  }
109543
private void handleGetAllMetricName(final int executorId, final HttpServletRequest req,
      final HashMap<String, Object> ret) throws IOException {
    final Map<String, Object> result;
    try {
      result =
          this.execManagerAdapter.callExecutorStats(executorId,
              ConnectorParams.STATS_GET_ALLMETRICSNAME,
              (Pair<String, String>[]) null);

      if (result.containsKey(ConnectorParams.RESPONSE_ERROR)) {
        ret.put("error", result.get(ConnectorParams.RESPONSE_ERROR).toString());
      } else {
        ret.put("metricList", result.get("data"));
      }
    } catch (final ExecutorManagerException e) {
      logger.error(e.getMessage(), e);
      ret.put("error", "Failed to fetch metric names for executor : "
          + executorId);
    }
  }
1294845
@Nonnull
    public static List<Map.Entry<String, String>> parseMetricName(@Nonnull String metricName) {
        if (metricName.charAt(0) != '[' || metricName.charAt(metricName.length() - 1) != ']') {
            throw new IllegalArgumentException("key not enclosed in []: " + metricName);
        }

        StringBuilder sb = new StringBuilder();
        List<Map.Entry<String, String>> result = new ArrayList<Map.Entry<String, String>>();
        int l = metricName.length() - 1;
        String tag = null;
        boolean inTag = true;
        for (int i = 1; i < l; i++) {
            char ch = metricName.charAt(i);
            switch (ch) {
                case '=':
                    tag = handleEqualsSign(metricName, sb, inTag);
                    inTag = false;
                    continue;

                case ',':
                    handleComma(metricName, sb, result, tag, inTag);
                    inTag = true;
                    tag = null;
                    continue;

                default:
                    if (ch == '\\') {
                        // the next character will be treated literally
                        ch = metricName.charAt(++i);
                    }
                    if (i == l) {
                        throw new IllegalArgumentException("backslash at the end: " + metricName);
                    }
                    sb.append(ch);
            }
        }
        // final entry
        if (tag != null) {
            result.add(new SimpleImmutableEntry<String, String>(tag, sb.toString()));
        } else if (sb.length() > 0) {
            throw new IllegalArgumentException("unfinished tag at the end: " + metricName);
        }
        return result;
    }
709177
protected void addMetric(String name, Metric metric) {
		if (metric == null) {
			LOG.warn("Ignoring attempted registration of a metric due to being null for name {}.", name);
			return;
		}
		// add the metric only if the group is still open
		synchronized (this) {
			if (!closed) {
				// immediately put without a 'contains' check to optimize the common case (no collision)
				// collisions are resolved later
				Metric prior = metrics.put(name, metric);

				// check for collisions with other metric names
				if (prior == null) {
					// no other metric with this name yet

					if (groups.containsKey(name)) {
						// we warn here, rather than failing, because metrics are tools that should not fail the
						// program when used incorrectly
						LOG.warn("Name collision: Adding a metric with the same name as a metric subgroup: '" +
								name + "'. Metric might not get properly reported. " + Arrays.toString(scopeComponents));
					}

					registry.register(metric, name, this);
				}
				else {
					// we had a collision. put back the original value
					metrics.put(name, prior);

					// we warn here, rather than failing, because metrics are tools that should not fail the
					// program when used incorrectly
					LOG.warn("Name collision: Group already contains a Metric with the name '" +
							name + "'. Metric will not be reported." + Arrays.toString(scopeComponents));
				}
			}
		}
	}
693749
private static String getForkMetricsName(TaskMetrics taskMetrics, State state, int index) {
    return taskMetrics.getName() + "." + getForkMetricsId(state, index);
  }
53069
public static String stripInstanceAndHost(String metricsName) {
    String[] pieces = metricsName.split("\\.");
    Preconditions.checkArgument(pieces.length > 1, "Incorrect metrics name: %s.", metricsName);

    // Master metrics doesn't have hostname included.
    if (!pieces[0].equals(MetricsSystem.InstanceType.MASTER.toString())) {
      pieces[1] = null;
    }
    pieces[0] = null;
    return Joiner.on(".").skipNulls().join(pieces);
  }
644267
def do_metric_name_list(mc, args):
    ''''''
    fields = {}
    if args.dimensions:
        fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
    if args.limit:
        fields['limit'] = args.limit
    if args.offset:
        fields['offset'] = args.offset
    if args.tenant_id:
        fields['tenant_id'] = args.tenant_id

    try:
        metric_names = mc.metrics.list_names(**fields)
    except (osc_exc.ClientException, k_exc.HttpError) as he:
        raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
    else:
        if args.json:
            print(utils.json_formatter(metric_names))
            return
        if isinstance(metric_names, list):
            utils.print_list(metric_names, ['Name'], formatters={'Name': lambda x: x['name']})
743100
public MetricName withTag(String key, String value) {
		return name(name).tags(tags).tag(key, value).build();
	}
1057250
public Collection<Metric> metricNames(long applicationId, String name)
    {
        QueryParameterList queryParams = new QueryParameterList();
        if(name != null && name.length() > 0)
            queryParams.add("name", name);
        return HTTP.GET(String.format("/v2/mobile_applications/%d/metrics.json", applicationId), null, queryParams, METRICS).get();
    }
305014
function(name, incr /* =1 */ ) {
		var currVal = this.metrics[name] || 0;
		incr = incr || 1;

		//debug('incrMetric(%s) += %d', name, incr);
		this.setMetric(name, currVal + incr);
	}