Makes counter measurements as updated and dumps them when timeout expires.

@see #dump()
160163
protected void update() {
		_updated = true;
		if (System.currentTimeMillis() > _lastDumpTime + _interval) {
			try {
				dump();
			} catch (InvocationException ex) {
				// Todo: decide what to do
			}
		}
	}
505017
@Override
	public void resetStats()
    {
    	super.resetStats();
    	sentToQueueCount.set(0);
    	receivedFromQueueCount.set(0);
    	acknowledgedGetCount.set(0);
    	rollbackedGetCount.set(0);
    	expiredCount.set(0);
    }
1303871
public int flush(final MetricSender sender) throws IOException, HttpException {
		Preconditions.checkNotNull(sender);
				
		// aggregate metrics that were enqueued before the current minute
		
		long currentMinute = (System.currentTimeMillis() / MS_IN_MIN) * MS_IN_MIN;
		
		LOGGER.debug("Flushing metrics < {}", currentMinute);
		LOGGER.debug("Metrics queue size {}", queue.size());
		
		MetricAggregator aggregator = new MetricAggregator(currentMinute, lastValues);
		
		while ((!queue.isEmpty()) && (queue.peek().getOccurredMillis() < currentMinute)) {
			aggregator.add(queue.remove());
		}

		// handle the auto reports
		
		if (lastFlush < currentMinute) {
			aggregator.autoReportZero(autoReportZeroMetrics);
			aggregator.autoReportLast(autoReportLastMetrics);
		}
		
		lastFlush = currentMinute;
		
		// get the aggregates
		
		List<MetricAggregate> aggregates = aggregator.getAggregates();

		// Save the values of gauge and average metrics for the next iteration
		// Gauge last value = aggregate last value
		// Average last value = aggregate last value / aggregate count
		
		if ((aggregates != null) && (!aggregates.isEmpty())) {
			for (MetricAggregate aggregate : aggregates) {
				if (aggregate.getIdentity().getType().equals(MetricMonitorType.GAUGE)) {
					lastValues.put(aggregate.getIdentity(), aggregate.getValue());
				} else if (aggregate.getIdentity().getType().equals(MetricMonitorType.AVERAGE)) {
					lastValues.put(aggregate.getIdentity(), aggregate.getValue() / aggregate.getCount());
				}
			}
		}
		
		// send the aggregates to Stackify
		
		int numSent = 0;
		
		if ((aggregates != null) && (!aggregates.isEmpty())) {
			LOGGER.debug("Sending aggregate metrics: {}", aggregates);
			sender.send(aggregates);
			numSent = aggregates.size();
		}
		
		return numSent;
	}
683035
public void stats(String name, float value) {
		for (ICounters counter : _counters)
			counter.stats(name, value);
	}

	/**
	 * Records the last calculated measurement value.
	 * 
	 * Usually this method is used by metrics calculated externally.
	 * 
	 * @param name  a counter name of Last type.
	 * @param value a last value to record.
	 */
	public void last(String name, float value) {
		for (ICounters counter : _counters)
			counter.last(name, value);
	}

	/**
	 * Records the current time as a timestamp.
	 * 
	 * @param name a counter name of Timestamp type.
	 */
	public void timestampNow(String name) {
		timestamp(name, ZonedDateTime.now());
	}

	/**
	 * Records the given timestamp.
	 * 
	 * @param name  a counter name of Timestamp type.
	 * @param value a timestamp to record.
	 */
	public void timestamp(String name, ZonedDateTime value) {
		for (ICounters counter : _counters)
			counter.timestamp(name, value);
	}

	/**
	 * Increments counter by 1.
	 * 
	 * @param name a counter name of Increment type.
	 */
	public void incrementOne(String name) {
		increment(name, 1);
	}

	/**
	 * Increments counter by given value.
	 * 
	 * @param name  a counter name of Increment type.
	 * @param value a value to add to the counter.
	 */
	public void increment(String name, int value) {
		for (ICounters counter : _counters)
			counter.increment(name, value);
	}

}
1097376
void measure(Registry registry, JmxData data, List<Measurement> ms) {
    Map<String, String> tags = tagMappings.entrySet().stream().collect(Collectors.toMap(
        Map.Entry::getKey,
        e -> MappingExpr.substitute(e.getValue(), data.getStringAttrs())
    ));
    Id id = registry
        .createId(MappingExpr.substitute(nameMapping, data.getStringAttrs()))
        .withTags(tags);

    Map<String, Number> numberAttrs = new HashMap<>(data.getNumberAttrs());
    JmxData previous = previousData.put(data.getName(), data);
    if (previous != null) {
      previous.getNumberAttrs().forEach((key, value) -> numberAttrs.put("previous:" + key, value));
    }

    Double v = MappingExpr.eval(valueMapping, numberAttrs);

    if (v != null && !v.isNaN()) {
      if (counter) {
        updateCounter(registry, id, v.longValue());
      } else {
        ms.add(new Measurement(id, registry.clock().wallTime(), v));
      }
    }
  }
1287471
private void checkTimeout() {
        if (timerMDC != null) {
            MDC.put("name", timerMDC);
        }
        if (docBuffer.isEmpty()) {
            return;
        }

        // How long has the NEWest item been waiting?
        long wait = ((new Date().getTime()) - bufferYoungest) / 1000;
        // If the buffer has been updated in the last 20s ignore it
        if (wait < 20) {
            return;
        }

        // Else, time to flush the buffer
        log.debug("=== Flushing old buffer: {}s", wait);
        submitBuffer(true);
    }
1234311
public String dumpCounters() {
    // CHECK IF STATISTICS ARE ACTIVED
    if (recording < 0)
      return "Counters: <no recording>";

    final StringBuilder buffer = new StringBuilder();

    synchronized (counters) {
      buffer.append("DUMPING COUNTERS (last reset on: " + lastReset.toString() + ")...");

      buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
      buffer.append(String.format("\n%50s | Value                                                             |", "Name"));
      buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));

      final List<String> keys = new ArrayList<String>(counters.keySet());
      Collections.sort(keys);

      for (String k : keys) {
        final Long stat = counters.get(k);
        buffer.append(String.format("\n%-50s | %-65d |", k, stat));
      }
    }

    buffer.append(String.format("\n%50s +-------------------------------------------------------------------+", ""));
    return buffer.toString();
  }
896532
@SuppressWarnings("UnusedDeclaration") public void dump() {
    Buffer buffer = new Buffer();
    try {
      dump(buffer);
    } catch (IOException e) {
      throw new AssertionError(e);
    }
    Log.i(TAG, buffer.readUtf8());
  }
747376
def dump(self):
        

        # Print out the collectd feedback.
        # This is sent to stdout while other log messages are sent to stderr.
        for k, v in sorted(self._dict.items()):
            print(self.formatter(k, v))

        # Reset each entry to zero
        for k, v in sorted(self._dict.items()):
            self._dict[k] = 0
1320844
public static Counter counter(Metrics metrics, String component, String methodName) {
    if (metrics != null) {
      return metrics.getCounter(component, methodName);
    } else {
      return null;
    }
  }
199603
public void fillMeasures(String measure, JSONObject jsonContent, Pattern pattern, HashMap<String,Double> i){
		String tem = (String)jsonContent.get(measure);
		if(tem != null){
			Matcher tM = pattern.matcher(tem);
			if(tM.find() && !tM.group(1).isEmpty()){
				try{
					i.put(measure, Double.valueOf(tM.group(1)));
				}catch(NumberFormatException e){
					e.printStackTrace();
				}
			}
		}
	}
106233
def send_metrics_now
      ms = registry_measurements

      if ms.empty?
        Spectator.logger.debug 'No measurements to send'
      else
        uri = @registry.config[:uri]
        ms.each_slice(@registry.batch_size) do |batch|
          payload = payload_for_measurements(batch)
          Spectator.logger.info "Sending #{batch.length} measurements to #{uri}"
          @http.post_json(uri, payload)
        end
      end
    end
628914
private Metric collectCounter(String dropwizardName, Counter counter) {
    String metricName = DropWizardUtils.generateFullMetricName(dropwizardName, "counter");
    String metricDescription =
        DropWizardUtils.generateFullMetricDescription(dropwizardName, counter);

    MetricDescriptor metricDescriptor =
        MetricDescriptor.create(
            metricName,
            metricDescription,
            DEFAULT_UNIT,
            Type.GAUGE_INT64,
            Collections.<LabelKey>emptyList());
    TimeSeries timeSeries =
        TimeSeries.createWithOnePoint(
            Collections.<LabelValue>emptyList(),
            Point.create(Value.longValue(counter.getCount()), clock.now()),
            null);
    return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
  }
39915
public function snapshot()
    {
        collect($this->measuredJobs())->each(function ($job) {
            $this->storeSnapshotForJob($job);
        });

        collect($this->measuredQueues())->each(function ($queue) {
            $this->storeSnapshotForQueue($queue);
        });

        $this->storeSnapshotTimestamp();
    }
1258359
synchronized void record(TagContext tags, MeasureMapInternal stats, Timestamp timestamp) {
    Iterator<Measurement> iterator = stats.iterator();
    Map<String, AttachmentValue> attachments = stats.getAttachments();
    while (iterator.hasNext()) {
      Measurement measurement = iterator.next();
      Measure measure = measurement.getMeasure();
      if (!measure.equals(registeredMeasures.get(measure.getName()))) {
        // unregistered measures will be ignored.
        continue;
      }
      Collection<MutableViewData> viewDataCollection = mutableMap.get(measure.getName());
      for (MutableViewData viewData : viewDataCollection) {
        viewData.record(
            tags, RecordUtils.getDoubleValueFromMeasurement(measurement), timestamp, attachments);
      }
    }
  }
1089952
public void record(double amount) {
    if (amount >= 0.0) {
      add(totalAmount, amount);
      add(totalOfSquares, amount * amount);
      max(max, amount);
      count.incrementAndGet();
      lastUpdateTime.set(clock.wallTime());
    }
  }
611261
protected void removeExpiredMeters() {
    int total = 0;
    int expired = 0;
    Iterator<Map.Entry<Id, Meter>> it = meters.entrySet().iterator();
    while (it.hasNext()) {
      ++total;
      Map.Entry<Id, Meter> entry = it.next();
      Meter m = entry.getValue();
      if (m.hasExpired()) {
        ++expired;
        it.remove();
      }
    }
    logger.debug("removed {} expired meters out of {} total", expired, total);
    cleanupCachedState();
  }