Event listener method for metrics, pushing metrics to spmsender module
@param {Object} metric  Object
340966
function shipMetrics (metric) {
    try {
      this.emit('metric', metric)
      this.spmSender.collectMetric(metric)
    } catch (ex) {
      logger.error('Error in shipMetrics' + ex.stack)
    }
  }
340872
def process(self, metric):
        

        self.queue.append(metric)
        if len(self.queue) >= self.queue_size:
            logging.debug("Queue is full, sending logs to Logentries")
            self._send()
1155926
def log_metrics(self, metrics_by_name, info):
        
        if self.metrics is None:
            # If, for whatever reason, the metrics collection has not been set
            # do not try to save anything there.
            return
        for key in metrics_by_name:
            query = {"run_id": self.run_entry['_id'],
                     "name": key}
            push = {"steps": {"$each": metrics_by_name[key]["steps"]},
                    "values": {"$each": metrics_by_name[key]["values"]},
                    "timestamps": {"$each": metrics_by_name[key]["timestamps"]}
                    }
            update = {"$push": push}
            result = self.metrics.update_one(query, update, upsert=True)
            if result.upserted_id is not None:
                # This is the first time we are storing this metric
                info.setdefault("metrics", []) \
                    .append({"name": key, "id": str(result.upserted_id)})
116119
private void addConditionalFieldsToAttemptEvent(AWSRequestMetrics metrics, HandlerAfterAttemptContext context,
                                                    ApiCallAttemptMonitoringEvent event) {
        TimingInfo timingInfo = metrics == null ? null : metrics.getTimingInfo();
        Response<?> response = context.getResponse();
        Integer statusCode = null;
        String xAmznRequestId = null;
        String xAmzRequestId = null;
        String xAmzId2 = null;
        Long requestLatency = null;

        Map<String, String> responseHeaders = null;
        if (response != null && response.getHttpResponse() != null) {
            responseHeaders = response.getHttpResponse().getHeaders();
            statusCode = response.getHttpResponse().getStatusCode();
            requestLatency = calculateRequestLatency(timingInfo);
        } else if (context.getException() instanceof AmazonServiceException) {
            responseHeaders = ((AmazonServiceException) context.getException()).getHttpHeaders();
            statusCode = extractHttpStatusCode((AmazonServiceException) context.getException());
            requestLatency = calculateRequestLatency(timingInfo);
        }

        if (responseHeaders != null) {
            xAmznRequestId = responseHeaders.get(X_AMZN_REQUEST_ID_HEADER_KEY);
            xAmzRequestId = responseHeaders.get(X_AMZ_REQUEST_ID_HEADER_KEY);
            xAmzId2 = responseHeaders.get(X_AMZ_REQUEST_ID_2_HEADER_KEY);
        }

        event.withXAmznRequestId(xAmznRequestId)
             .withXAmzRequestId(xAmzRequestId)
             .withXAmzId2(xAmzId2)
             .withHttpStatusCode(statusCode)
             .withRequestLatency(requestLatency);
        addException(context.getException(), event);
    }
444086
def _process_metrics(
        self, data, url, services_incl_filter=None, services_excl_filter=None, custom_tags=None, active_tag=None
    ):
        
        hostname = data['svname']
        service_name = data['pxname']
        back_or_front = data['back_or_front']
        custom_tags = [] if custom_tags is None else custom_tags
        active_tag = [] if active_tag is None else active_tag
        tags = ["type:%s" % back_or_front, "instance_url:%s" % url, "service:%s" % service_name]
        tags.extend(custom_tags)
        tags.extend(active_tag)

        if self._is_service_excl_filtered(service_name, services_incl_filter, services_excl_filter):
            return

        if back_or_front == Services.BACKEND:
            tags.append('backend:%s' % hostname)
            if data.get('addr'):
                tags.append('server_address:{}'.format(data.get('addr')))

        for key, value in data.items():
            if HAProxy.METRICS.get(key):
                suffix = HAProxy.METRICS[key][1]
                name = "haproxy.%s.%s" % (back_or_front.lower(), suffix)
                try:
                    if HAProxy.METRICS[key][0] == 'rate':
                        self.rate(name, float(value), tags=tags)
                    else:
                        self.gauge(name, float(value), tags=tags)
                except ValueError:
                    pass
1095311
public static void collectMetric(
    MetricsRecordBuilder metricsRecordBuilder, String name, Metric metric) {

    if (metric instanceof Timer) {
      Timer t = (Timer) metric;
      metricsRecordBuilder
        .addCounter(new ShuffleServiceMetricsInfo(name + "_count", "Count of timer " + name),
          t.getCount())
        .addGauge(
          new ShuffleServiceMetricsInfo(name + "_rate15", "15 minute rate of timer " + name),
          t.getFifteenMinuteRate())
        .addGauge(
          new ShuffleServiceMetricsInfo(name + "_rate5", "5 minute rate of timer " + name),
          t.getFiveMinuteRate())
        .addGauge(
          new ShuffleServiceMetricsInfo(name + "_rate1", "1 minute rate of timer " + name),
          t.getOneMinuteRate())
        .addGauge(new ShuffleServiceMetricsInfo(name + "_rateMean", "Mean rate of timer " + name),
          t.getMeanRate());
    } else if (metric instanceof Meter) {
      Meter m = (Meter) metric;
      metricsRecordBuilder
        .addCounter(new ShuffleServiceMetricsInfo(name + "_count", "Count of meter " + name),
          m.getCount())
        .addGauge(
          new ShuffleServiceMetricsInfo(name + "_rate15", "15 minute rate of meter " + name),
          m.getFifteenMinuteRate())
        .addGauge(
          new ShuffleServiceMetricsInfo(name + "_rate5", "5 minute rate of meter " + name),
          m.getFiveMinuteRate())
        .addGauge(
          new ShuffleServiceMetricsInfo(name + "_rate1", "1 minute rate of meter " + name),
          m.getOneMinuteRate())
        .addGauge(new ShuffleServiceMetricsInfo(name + "_rateMean", "Mean rate of meter " + name),
          m.getMeanRate());
    } else if (metric instanceof Gauge) {
      final Object gaugeValue = ((Gauge) metric).getValue();
      if (gaugeValue instanceof Integer) {
        metricsRecordBuilder.addGauge(getShuffleServiceMetricsInfo(name), (Integer) gaugeValue);
      } else if (gaugeValue instanceof Long) {
        metricsRecordBuilder.addGauge(getShuffleServiceMetricsInfo(name), (Long) gaugeValue);
      } else if (gaugeValue instanceof Float) {
        metricsRecordBuilder.addGauge(getShuffleServiceMetricsInfo(name), (Float) gaugeValue);
      } else if (gaugeValue instanceof Double) {
        metricsRecordBuilder.addGauge(getShuffleServiceMetricsInfo(name), (Double) gaugeValue);
      } else {
        throw new IllegalStateException(
                "Not supported class type of metric[" + name + "] for value " + gaugeValue);
      }
    } else if (metric instanceof Counter) {
      Counter c = (Counter) metric;
      long counterValue = c.getCount();
      metricsRecordBuilder.addGauge(new ShuffleServiceMetricsInfo(name, "Number of " +
          "connections to shuffle service " + name), counterValue);
    }
  }
1253314
private void postMetricMetadata(String metricName, DatadogMetricMetadata metadata) {
        // already posted the metadata for this metric
        if (verifiedMetadata.contains(metricName))
            return;

        try {
            httpClient
                    .put(config.uri() + "/api/v1/metrics/" + URLEncoder.encode(metricName, "UTF-8")
                            + "?api_key=" + config.apiKey() + "&application_key=" + config.applicationKey())
                    .withJsonContent(metadata.editMetadataBody())
                    .send()
                    .onSuccess(response -> verifiedMetadata.add(metricName))
                    .onError(response -> {
                        if (logger.isErrorEnabled()) {
                            String msg = response.body();

                            // Ignore when the response content contains "metric_name not found".
                            // Metrics that are newly created in Datadog are not immediately available
                            // for metadata modification. We will keep trying this request on subsequent publishes,
                            // where it will eventually succeed.
                            if (!msg.contains("metric_name not found")) {
                                logger.error("failed to send metric metadata to datadog: {}", msg);
                            }
                        }
                    });
        } catch (Throwable e) {
            logger.warn("failed to send metric metadata to datadog", e);
        }
    }
1332713
public void onInternalMessage(Metrics.MetricPublisher request,
                                Metrics.MetricPublisherPublishMessage message) {
    handlePublisherPublishMessage(request, message);
  }
945823
function addListeners() {
	if (listenersAdded) return;
	listenersAdded = true;

	if (cluster.isMaster) {
		// Listen for worker responses to requests for local metrics
		cluster.on('message', (worker, message) => {
			if (message.type === GET_METRICS_RES) {
				const request = requests.get(message.requestId);
				message.metrics.forEach(registry => request.responses.push(registry));
				request.pending--;

				if (request.pending === 0) {
					// finalize
					requests.delete(message.requestId);
					clearTimeout(request.errorTimeout);

					if (request.failed) return; // Callback already run with Error.

					const registry = AggregatorRegistry.aggregate(request.responses);
					const promString = registry.metrics();
					request.done(null, promString);
				}
			}
		});
	}
}
782665
public synchronized void pushMetric(final MetricsRecord mr) {
    if (changed) 
      mr.setMetric(getName(), value);
    changed = false;
  }
88588
@SuppressWarnings("unchecked")
  private void gatherOneMetric(
      String metricName,
      Metrics.MetricPublisherPublishMessage.Builder builder) {
    Object metricValue = metrics.get(metricName).getValueAndReset();
    // Decide how to handle the metric based on type
    if (metricValue == null) {
      return;
    }
    if (metricValue instanceof Map) {
      for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) metricValue).entrySet()) {
        if (entry.getKey() != null && entry.getValue() != null) {
          addDataToMetricPublisher(
              builder, metricName + "/" + entry.getKey().toString(), entry.getValue());
        }
      }
    } else if (metricValue instanceof Collection) {
      int index = 0;
      for (Object value : (Collection) metricValue) {
        addDataToMetricPublisher(builder, metricName + "/" + (index++), value);
      }
    } else {
      addDataToMetricPublisher(builder, metricName, metricValue);
    }
  }
130735
def update_metric(self, eval_metric, labels, pre_sliced=False):
        
        assert self.binded and self.params_initialized

        for meta, module in zip(self._metas, self._modules):
            if SequentialModule.META_TAKE_LABELS in meta and \
                    meta[SequentialModule.META_TAKE_LABELS]:
                module.update_metric(eval_metric, labels, pre_sliced)
22762
function(name, value) {
			if (typeof metricsAvgStorage[name] === 'undefined') {
				metricsAvgStorage[name] = [];
			}

			metricsAvgStorage[name].push(value);

			this.setMetric(name, getAverage(metricsAvgStorage[name]));
		}
504140
@SuppressWarnings("FutureReturnValueIgnored")
  public void reportMetric(final IMetric<?> metric) {
    if (metric != null && isAvailable()) {
      try {
        final IMetric<?> metricSnapshot;
        // take snapshot
        synchronized (metric) {
          metricSnapshot = metric.getSnapshot();
        }
        logger.debug(String
            .format("Submitting %s metric for metric emission pool", metricSnapshot.getName()));
        // report to all emitters
        for (final IMetricEmitter metricEmitter : this.metricEmitters) {
          this.executorService.submit(() -> {
            try {
              metricEmitter.reportMetric(metricSnapshot);
            } catch (final Exception ex) {
              logger.error(
                  String.format("Failed to report %s metric due to ", metricSnapshot.getName()),
                  ex);
            }
          });
        }
      } catch (final CloneNotSupportedException ex) {
        logger.error(
            String.format("Failed to take snapshot for %s metric", metric.getClass().getName()),
            ex);
      }
    }
  }
1185029
private void pushEvent(GobblinTrackingEvent event) throws IOException {

    Map<String, String> metadata = event.getMetadata();
    String name = getMetricName(metadata, event.getName());
    long timestamp = event.getTimestamp() / 1000l;
    MultiPartEvent multipartEvent = MultiPartEvent.getEvent(metadata.get(EventSubmitter.EVENT_TYPE));
    if (multipartEvent == null) {
      graphitePusher.push(JOINER.join(prefix, name), EMTPY_VALUE, timestamp);
    }
    else {
      for (String field : multipartEvent.getMetadataFields()) {
        String value = metadata.get(field);
        if (value == null) {
          graphitePusher.push(JOINER.join(prefix, name, field), EMTPY_VALUE, timestamp);
        } else {
          if (emitAsKey(field)) {
            // metric value is emitted as part of the keys
            graphitePusher.push(JOINER.join(prefix, name, field, value), EMTPY_VALUE, timestamp);
          } else {
            graphitePusher.push(JOINER.join(prefix, name, field), convertValue(field, value), timestamp);
          }
        }
      }
    }
  }
708773
def send_metrics_to_cloudwatch(self, rule, metric, dimensions):
        

        timestamp = datetime.datetime.utcfromtimestamp(metric.timestamp)

        self.log.debug(
            "CloudWatch: Attempting to publish metric: %s to %s "
            "with value (%s) for dimensions %s @%s",
            rule['name'],
            rule['namespace'],
            str(metric.value),
            str(dimensions),
            str(metric.timestamp)
        )

        try:
            self.connection.put_metric_data(
                str(rule['namespace']),
                str(rule['name']),
                str(metric.value),
                timestamp, str(rule['unit']),
                dimensions)
            self.log.debug(
                "CloudWatch: Successfully published metric: %s to"
                " %s with value (%s) for dimensions %s",
                rule['name'],
                rule['namespace'],
                str(metric.value),
                str(dimensions))
        except AttributeError as e:
            self.log.error(
                "CloudWatch: Failed publishing - %s ", str(e))
        except Exception as e:  # Rough connection re-try logic.
            self.log.error(
                "CloudWatch: Failed publishing - %s\n%s ",
                str(e),
                str(sys.exc_info()[0]))
            self._bind()
463263
function flushMetrics() {
  var time_stamp = Math.round(new Date().getTime() / 1000);
  if (old_timestamp > 0) {
    gauges[timestamp_lag_namespace] = (time_stamp - old_timestamp - (Number(conf.flushInterval)/1000));
  }
  old_timestamp = time_stamp;

  var metrics_hash = {
    counters: counters,
    gauges: gauges,
    timers: timers,
    timer_counters: timer_counters,
    sets: sets,
    counter_rates: counter_rates,
    timer_data: timer_data,
    pctThreshold: pctThreshold,
    histogram: conf.histogram
  };

  // After all listeners, reset the stats
  backendEvents.once('flush', function clear_metrics(ts, metrics) {
    // TODO: a lot of this should be moved up into an init/constructor so we don't have to do it every
    // single flushInterval....
    // allows us to flag all of these on with a single config but still override them individually
    conf.deleteIdleStats = conf.deleteIdleStats !== undefined ? conf.deleteIdleStats : false;
    if (conf.deleteIdleStats) {
      conf.deleteCounters = conf.deleteCounters !== undefined ? conf.deleteCounters : true;
      conf.deleteTimers = conf.deleteTimers !== undefined ? conf.deleteTimers : true;
      conf.deleteSets = conf.deleteSets !== undefined ? conf.deleteSets : true;
      conf.deleteGauges = conf.deleteGauges !== undefined ? conf.deleteGauges : true;
    }

    // Clear the counters
    conf.deleteCounters = conf.deleteCounters || false;
    for (var counter_key in metrics.counters) {
      if (conf.deleteCounters) {
        if ((counter_key.indexOf("packets_received") != -1) ||
            (counter_key.indexOf("metrics_received") != -1) ||
            (counter_key.indexOf("bad_lines_seen") != -1)) {
          metrics.counters[counter_key] = 0;
        } else {
         delete(metrics.counters[counter_key]);
        }
      } else {
        metrics.counters[counter_key] = 0;
      }
    }

    // Clear the timers
    conf.deleteTimers = conf.deleteTimers || false;
    for (var timer_key in metrics.timers) {
      if (conf.deleteTimers) {
        delete(metrics.timers[timer_key]);
        delete(metrics.timer_counters[timer_key]);
      } else {
        metrics.timers[timer_key] = [];
        metrics.timer_counters[timer_key] = 0;
     }
    }

    // Clear the sets
    conf.deleteSets = conf.deleteSets || false;
    for (var set_key in metrics.sets) {
      if (conf.deleteSets) {
        delete(metrics.sets[set_key]);
      } else {
        metrics.sets[set_key] = new set.Set();
      }
    }

    // Normally gauges are not reset.  so if we don't delete them, continue to persist previous value
    conf.deleteGauges = conf.deleteGauges || false;
    if (conf.deleteGauges) {
      for (var gauge_key in metrics.gauges) {
        delete(metrics.gauges[gauge_key]);
      }
    }
  });

  pm.process_metrics(metrics_hash, flushInterval, time_stamp, function emitFlush(metrics) {
    backendEvents.emit('flush', time_stamp, metrics);
  });

  // Performing this setTimeout at the end of this method rather than the beginning
  // helps ensure we adapt to negative clock skew by letting the method's latency
  // introduce a short delay that should more than compensate.
  setTimeout(flushMetrics, getFlushTimeout(flushInterval));
}