Utility method to create and return new metrics record instance within the
given context. This record is tagged with the host name.

@param context the context
@param recordName name of the record
@return newly created metrics record
170736
public static MetricsRecord createRecord(MetricsContext context, 
                                           String recordName) 
  {
    MetricsRecord metricsRecord = context.createRecord(recordName);
    metricsRecord.setTag("hostName", getHostName());
    return metricsRecord;        
  }
29387
public static String getMetricNameWithUserTag(String metricName, String userName) {
    UserMetricKey k = new UserMetricKey(metricName, userName);
    String result = CACHED_METRICS.get(k);
    if (result != null) {
      return result;
    }
    return CACHED_METRICS.computeIfAbsent(k, key -> metricName + "." + CommonMetrics.TAG_USER
        + TAG_SEPARATOR + userName);
  }
1218934
Map<String, Map<String, List<TagsMetricsPair>>> makeMap(
       Collection<MetricsContext> contexts) throws IOException {
    Map<String, Map<String, List<TagsMetricsPair>>> map = 
      new TreeMap<String, Map<String, List<TagsMetricsPair>>>();

    for (MetricsContext context : contexts) {
      Map<String, List<TagsMetricsPair>> records = 
        new TreeMap<String, List<TagsMetricsPair>>();
      map.put(context.getContextName(), records);
    
      for (Map.Entry<String, Collection<OutputRecord>> r : 
          context.getAllRecords().entrySet()) {
        List<TagsMetricsPair> metricsAndTags = 
          new ArrayList<TagsMetricsPair>();
        records.put(r.getKey(), metricsAndTags);
        for (OutputRecord outputRecord : r.getValue()) {
          TagMap tagMap = outputRecord.getTagsCopy();
          MetricMap metricMap = outputRecord.getMetricsCopy();
          metricsAndTags.add(new TagsMetricsPair(tagMap, metricMap));
        }
      }
    }
    return map;
  }
1082590
public static Counter newCounter(String name, TaggingContext context) {
    final MonitorConfig config = MonitorConfig.builder(name).build();
    return new ContextualCounter(config, context, COUNTER_FUNCTION);
  }
92653
public static <I extends Request, O extends Response>
    Function<Service<I, O>, MetricCollectingService<I, O>> newDecorator(
            MeterIdPrefixFunction meterIdPrefixFunction) {

        requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction");
        return delegate -> new MetricCollectingService<>(delegate, meterIdPrefixFunction);
    }
1099561
protected String getMetricNamePrefix(Map<String, Object> tags){
    String currentContextName = (String) tags.get(MetricContext.METRIC_CONTEXT_NAME_TAG_NAME);
    if (metricContextName == null || (currentContextName.indexOf(metricContextName) > -1)) {
      return currentContextName;
    }

    return JOINER.join(Strings.emptyToNull(metricsPrefix),
            metricContextName, tags.get("taskId"), tags.get("forkBranchName"), tags.get("class"));
  }
989363
public DirRecord newRecord(String entryDn) throws NamingException {
    DirRecord rec = new BasicDirRecord();
    rec.setDn(entryDn);
    return rec;
  }
544225
@Override
    public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
        // For MP Metrics 1.0, MetricType.from(Class in) does not support lambdas or proxy classes
        return register(name, metric, new Metadata(name, from(metric)));
    }
120207
def create(self, name):
        
        timer = metrics.Timer()
        timer.start()
        type = self.resolver.find(name)
        if type is None:
            raise TypeNotFound(name)
        if type.enum():
            result = sudsobject.Factory.object(name)
            for e, a in type.children():
                setattr(result, e.name, e.name)
        else:
            try:
                result = self.builder.build(type)
            except Exception, e:
                log.error("create '%s' failed", name, exc_info=True)
                raise BuildError(name, e)
        timer.stop()
        metrics.log.debug("%s created: %s", name, timer)
        return result
1152073
def CreateCounterMetadata(metric_name, fields=None, docstring=None, units=None):
  """"""
  return rdf_stats.MetricMetadata(
      varname=metric_name,
      metric_type=rdf_stats.MetricMetadata.MetricType.COUNTER,
      value_type=rdf_stats.MetricMetadata.ValueType.INT,
      fields_defs=FieldDefinitionProtosFromTuples(fields or []),
      docstring=docstring,
      units=units)
324307
def new_tank_metric(self, _type, name, hostname=None, group=None, source=None, *kw):
        
        if not _type:
            raise ValueError('Metric type should be defined.')

        if _type in available_metrics:
            metric_obj = available_metrics[_type](None, self.routing_queue)  # create metric object
            metric_info = {'type': _type,
                           'source': source,
                           'name': name,
                           'hostname': hostname,
                           'group': group}
            if kw is not None:
                metric_info.update(kw)
            metric_meta = pd.DataFrame({metric_obj.local_id: metric_info}).T  # create metric meta
            self.metrics_meta = self.metrics_meta.append(metric_meta)  # register metric meta
            self.metrics[metric_obj.local_id] = metric_obj  # register metric object

            # find subscribers for this metric
            this_metric_subscribers = self.__reversed_filter(self.subscribers, metric_info)
            if this_metric_subscribers.empty:
                logger.debug('subscriber for metric %s not found', metric_obj.local_id)
            else:
                logger.debug('Found subscribers for this metric, subscribing...: %s', this_metric_subscribers)
                # attach this metric id to discovered subscribers and select id <-> callbacks
                this_metric_subscribers['id'] = metric_obj.local_id
                found_callbacks = this_metric_subscribers[['id', 'callback']].set_index('id')
                # add this metric callbacks to DataManager's callbacks
                self.callbacks = self.callbacks.append(found_callbacks)
            return metric_obj
        else:
            raise NotImplementedError('Unknown metric type: %s' % _type)
1288121
def _create_record(self, rtype, name, content):
        """"""
        if not self._list_records(rtype, name, content):
            self._update_records([{}], {
                'type': rtype,
                'hostname': self._relative_name(name),
                'destination': content,
                'priority': self._get_lexicon_option('priority'),
            })
        LOGGER.debug('create_record: %s', True)
        return True
758652
public Metric createMetricAsync(String metricName)
      throws ExecutionException, InterruptedException {
    // [START createMetricAsync]
    MetricInfo metricInfo = MetricInfo.of(metricName, "severity>=ERROR");
    Future<Metric> future = logging.createAsync(metricInfo);
    // ...
    Metric metric = future.get();
    // [END createMetricAsync]
    return metric;
  }
1355249
def new_metric(name, class_, *args, **kwargs):
    

    with LOCK:
        try:
            item = REGISTRY[name]
        except KeyError:
            item = REGISTRY[name] = class_(*args, **kwargs)
            return item

    raise DuplicateMetricError("Metric {} already exists of type {}".format(name, type(item).__name__))
985799
public static Log instance(Context context) {
        Log instance = context.get(logKey);
        if (instance == null)
            instance = new Log(context);
        return instance;
    }
547572
public void registerNewMetrics(MetricName name, Metric metric) {
		final Set<MetricName> registeredNames = getNames();
		if (!registeredNames.contains(name)) {
			try {
				register(name, metric);
			} catch (IllegalArgumentException e){/* exception due to race condition*/}
		}
	}
1265535
public <T extends ContextAwareMetric> T register(T metric) throws IllegalArgumentException {
    return register(metric.getName(), metric);
  }