下面列出了怎么用com.codahale.metrics.Gauge的API类实例代码及写法,或者点击链接到github查看源代码。
private void registerContainerAppNumMetrics() {
metrics.register("variable.running.application",
new Gauge<Integer>() {
@Override
public Integer getValue() {
if (scheduler == null || scheduler.getRootQueueMetrics() == null) {
return 0;
} else {
return scheduler.getRootQueueMetrics().getAppsRunning();
}
}
}
);
metrics.register("variable.running.container",
new Gauge<Integer>() {
@Override
public Integer getValue() {
if(scheduler == null || scheduler.getRootQueueMetrics() == null) {
return 0;
} else {
return scheduler.getRootQueueMetrics().getAllocatedContainers();
}
}
}
);
}
@SuppressWarnings("unchecked")
private static <T> T getMetricValue(Map<String, Metric> metricMap, String name, Function<Object, T> valueExtractor) {
Metric metric = metricMap.get(name);
T value = null;
if (metric instanceof Gauge) {
Gauge gauge = (Gauge) metric;
value = (T) gauge.getValue();
}
if (metric instanceof Counter) {
Counter counter = (Counter) metric;
value = (T) (Long) counter.getCount();
}
if (value != null && valueExtractor != null) {
value = valueExtractor.apply(value);
}
return value;
}
private void initMetric() {
MetricSingleton.getMetricRegistry().register(MetricRegistry.name("data.registerInstanceCount"),
new Gauge<Long>() {
@Override
public Long getValue() {
return registCounter.get();
}
});
MetricSingleton.getMetricRegistry().register(MetricRegistry.name("data.registerInstanceTime"),
new Gauge<Long>() {
@Override
public Long getValue() {
return registTime;
}
});
}
@Test
public void reportMetersCountersGaugesWithZeroValuesOnlyWhenConfigured() throws Exception {
metricRegistry.register(ARBITRARY_GAUGE_NAME, (Gauge<Long>) () -> 0L);
metricRegistry.meter(ARBITRARY_METER_NAME).mark(0);
metricRegistry.counter(ARBITRARY_COUNTER_NAME).inc(0);
metricRegistry.timer(ARBITRARY_TIMER_NAME).update(-1L, TimeUnit.NANOSECONDS);
buildReportWithSleep(reporterBuilder
.withArithmeticMean()
.withOneMinuteMeanRate()
.withFiveMinuteMeanRate()
.withFifteenMinuteMeanRate()
.withZeroValuesSubmission()
.withMeanRate());
verify(mockAmazonCloudWatchAsyncClient, times(1)).putMetricData(metricDataRequestCaptor.capture());
final PutMetricDataRequest putMetricDataRequest = metricDataRequestCaptor.getValue();
final List<MetricDatum> metricData = putMetricDataRequest.metricData();
for (final MetricDatum metricDatum : metricData) {
assertThat(metricDatum.value()).isEqualTo(0.0);
}
}
@Test
public void testCounterDisabled() {
//create timer with id "testMetricAlerts" and register with metric registry, bump up value to 4.
Counter c = MetricsConfigurator.createCounter(metrics, "testCounterDisabled", PIPELINE_NAME, REVISION);
c.inc(100);
MetricsRuleDefinition metricsRuleDefinition = new MetricsRuleDefinition("testCounterDisabled",
"testCounterDisabled", "testCounterDisabled", MetricType.COUNTER,
MetricElement.COUNTER_COUNT, "${value()>98}", false, false, System.currentTimeMillis());
MetricRuleEvaluator metricRuleEvaluator = new MetricRuleEvaluator(metricsRuleDefinition, metrics,
new AlertManager(PIPELINE_NAME, PIPELINE_TITLE, REVISION, null, metrics, runtimeInfo, new EventListenerManager()),
new RuleDefinitionsConfigBean(), 0);
metricRuleEvaluator.checkForAlerts();
//get alert gauge
Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics,
AlertsUtil.getAlertGaugeName(metricsRuleDefinition.getId()));
Assert.assertNull(gauge);
}
private static Gauge getStatemachineGaugeWithName(RaftServerImpl server,
String gaugeName) {
MetricRegistryInfo info = new MetricRegistryInfo(server.getMemberId().toString(),
RATIS_APPLICATION_NAME_METRICS,
RATIS_STATEMACHINE_METRICS, RATIS_STATEMACHINE_METRICS_DESC);
Optional<RatisMetricRegistry> metricRegistry = MetricRegistries.global().get(info);
Assert.assertTrue(metricRegistry.isPresent());
RatisMetricRegistry ratisStateMachineMetricRegistry = metricRegistry.get();
SortedMap<String, Gauge> gaugeMap =
ratisStateMachineMetricRegistry.getGauges((s, metric) ->
s.contains(gaugeName));
return gaugeMap.get(gaugeMap.firstKey());
}
private void registerGauges() throws IllegalArgumentException {
if (!GAUGES_REGISTERED.getAndSet(true)) {
context.metricRegistry.register(
MetricRegistry.name(Heart.class, "runningThreadCount"),
(Gauge<Integer>) () -> forkJoinPool.getRunningThreadCount());
context.metricRegistry.register(
MetricRegistry.name(Heart.class, "activeThreadCount"),
(Gauge<Integer>) () -> forkJoinPool.getActiveThreadCount());
context.metricRegistry.register(
MetricRegistry.name(Heart.class, "queuedTaskCount"),
(Gauge<Long>) () -> forkJoinPool.getQueuedTaskCount());
context.metricRegistry.register(
MetricRegistry.name(Heart.class, "queuedSubmissionCount"),
(Gauge<Integer>) () -> forkJoinPool.getQueuedSubmissionCount());
}
}
private static void checkFollowerCommitLagsLeader(MiniRaftCluster cluster) {
List<RaftServerImpl> followers = cluster.getFollowers();
RaftServerImpl leader = cluster.getLeader();
Gauge leaderCommitGauge = RaftServerMetrics
.getPeerCommitIndexGauge(leader, leader);
for (RaftServerImpl follower : followers) {
Gauge followerCommitGauge = RaftServerMetrics
.getPeerCommitIndexGauge(leader, follower);
Assert.assertTrue((Long)leaderCommitGauge.getValue() >=
(Long)followerCommitGauge.getValue());
Gauge followerMetric = RaftServerMetrics
.getPeerCommitIndexGauge(follower, follower);
System.out.println(followerCommitGauge.getValue());
System.out.println(followerMetric.getValue());
Assert.assertTrue((Long)followerCommitGauge.getValue() <= (Long)followerMetric.getValue());
}
}
@Inject
public PlatformDriverExecutorRegistry(
DriverConfig config,
DriverRegistry registry,
DeviceDAO deviceDao,
Scheduler scheduler,
PlacePopulationCacheManager populationCacheMgr
) {
this.driverQueueBacklog = config.getDriverBacklogSize();
this.tombstonedDriverTimeoutMs = config.getDriverTombstoneTimeout(TimeUnit.MILLISECONDS);
this.registry = registry;
this.deviceDao = deviceDao;
this.scheduler = scheduler;
this.populationCacheMgr = populationCacheMgr;
IrisMetricSet drivers = IrisMetrics.metrics("drivers");
drivers.monitor("cache.executor", executorCache);
drivers.monitor("cache.protocol", protocolToDriverCache);
drivers.gauge("backlog", (Gauge<Map<String, Object>>) () -> queueBacklog());
}
@Test
public void testGaugeMetric() {
SortedMap<String, Gauge> gauges = new TreeMap<>();
Gauge<Number> gauge = new Gauge<Number>() {
@Override
public Number getValue() {
return new Double(METRIC_VALUE);
}
};
gauges.put(GAUGE_METRIC, gauge);
List<Metric> metrics = new GaugeConverter().convert(gauges, currentTimeMillis);
ConverterTestUtil util =
new ConverterTestUtil(metrics, GAUGE_METRIC, MetricType.GAUGE.getMetricTypeName(), currentTimeMillis);
util.checkMetric(SUFFIX_VALUE, METRIC_VALUE);
assertEquals(1, metrics.size());
}
@Test
public void testUpdateMetricsProcessor() throws InitializationException, IOException {
MetricsService ms = new MetricsService();
Map<String, Double> processorMetrics = ms.getProcessorMetrics(procStatus);
Map<String, String> tagsMap = ImmutableMap.of("env", "test");
DataDogReportingTask dataDogReportingTask = new TestableDataDogReportingTask();
dataDogReportingTask.initialize(initContext);
dataDogReportingTask.setup(configurationContext);
dataDogReportingTask.updateMetrics(processorMetrics, Optional.of("sampleProcessor"), tagsMap);
verify(metricRegistry).register(eq("nifi.sampleProcessor.FlowFilesReceivedLast5Minutes"), Mockito.<Gauge>any());
verify(metricRegistry).register(eq("nifi.sampleProcessor.ActiveThreads"), Mockito.<Gauge>any());
verify(metricRegistry).register(eq("nifi.sampleProcessor.BytesWrittenLast5Minutes"), Mockito.<Gauge>any());
verify(metricRegistry).register(eq("nifi.sampleProcessor.BytesReadLast5Minutes"), Mockito.<Gauge>any());
verify(metricRegistry).register(eq("nifi.sampleProcessor.FlowFilesSentLast5Minutes"), Mockito.<Gauge>any());
}
public void testMagickGetter() throws Exception {
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
// make one directly
SimpleOrderedMap<Object> info = new SimpleOrderedMap<>();
info.add( "name", os.getName() );
info.add( "version", os.getVersion() );
info.add( "arch", os.getArch() );
// make another using MetricUtils.addMXBeanMetrics()
SimpleOrderedMap<Object> info2 = new SimpleOrderedMap<>();
MetricUtils.addMXBeanMetrics( os, OperatingSystemMXBean.class, null, (k, v) -> {
info2.add(k, ((Gauge)v).getValue());
} );
// make sure they got the same thing
for (String p : Arrays.asList("name", "version", "arch")) {
assertEquals(info.get(p), info2.get(p));
}
}
public RootAllocator(final long limit) {
super(null, "ROOT", 0, limit);
DrillMetrics.register("drill.allocator.root.used", new Gauge<Long>() {
@Override
public Long getValue() {
return getAllocatedMemory();
}
});
DrillMetrics.register("drill.allocator.root.peak", new Gauge<Long>() {
@Override
public Long getValue() {
return getPeakMemoryAllocation();
}
});
}
public DynamoDbDelegate(final String endpoint, final String region, final AWSCredentialsProvider provider,
final ClientConfiguration clientConfig, final Configuration titanConfig,
final Map<String, RateLimiter> readRateLimit, final Map<String, RateLimiter> writeRateLimit,
final long maxRetries, final long retryMillis, final String prefix, final String metricsPrefix,
final RateLimiter controlPlaneRateLimiter) {
if (prefix == null) {
throw new IllegalArgumentException("prefix must be set");
}
if (metricsPrefix == null || metricsPrefix.isEmpty()) {
throw new IllegalArgumentException("metrics-prefix may not be null or empty");
}
this.metricsPrefix = metricsPrefix;
executorGaugeName = String.format("%s.%s_executor-queue-size", this.metricsPrefix, prefix);
clientThreadPool = getPoolFromNs(titanConfig);
if (!MetricManager.INSTANCE.getRegistry().getNames().contains(executorGaugeName)) {
MetricManager.INSTANCE.getRegistry().register(executorGaugeName, (Gauge<Integer>) () -> clientThreadPool.getQueue().size());
}
client = AmazonDynamoDBClientBuilder.standard()
.withCredentials(provider)
.withClientConfiguration(clientConfig)
.withEndpointConfiguration(getEndpointConfiguration(Optional.ofNullable(endpoint), region))
.build();
this.readRateLimit = readRateLimit;
this.writeRateLimit = writeRateLimit;
this.controlPlaneRateLimiter = controlPlaneRateLimiter;
this.maxConcurrentUsers = titanConfig.get(Constants.DYNAMODB_CLIENT_EXECUTOR_MAX_CONCURRENT_OPERATIONS);
this.maxRetries = maxRetries;
this.retryMillis = retryMillis;
if (maxConcurrentUsers < 1) {
throw new IllegalArgumentException("need at least one user otherwise wont make progress on scan");
}
this.listTablesApiName = String.format("%s_ListTables", prefix);
}
@SuppressWarnings( {"rawtypes", "unchecked"})
public Builder from(Gauge gauge) {
Object value = gauge.getValue();
if (value instanceof Map) {
Map<? extends String, ?> map = (Map<? extends String, ?>) value;
this.instance.putAll(map);
} else {
this.instance.put("value", value);
}
return this;
}
/**
* Return thread pool metrics
* @return thread pool metrics map
*/
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
gauges.put("pool-size", (Gauge<Integer>) executor::getPoolSize);
gauges.put("queued", (Gauge<Integer>) executor.getQueue()::size);
gauges.put("active", (Gauge<Integer>) executor::getActiveCount);
gauges.put("completed", (Gauge<Long>) executor::getCompletedTaskCount);
return gauges;
}
@Override
public Map<String, Metric> getMetrics() {
final Map<String, Metric> gauges = new HashMap<>();
gauges.put("log-lags",
(Gauge<Long>) () -> this.opts.getLogManager().getLastLogIndex() - (this.r.nextIndex - 1));
gauges.put("next-index", (Gauge<Long>) () -> this.r.nextIndex);
gauges.put("heartbeat-times", (Gauge<Long>) () -> this.r.heartbeatCounter);
gauges.put("install-snapshot-times", (Gauge<Long>) () -> this.r.installSnapshotCounter);
gauges.put("append-entries-times", (Gauge<Long>) () -> this.r.appendEntriesCounter);
return gauges;
}
private void initMetric() {
MetricSingleton.getMetricRegistry().register(key + ".Count", new Gauge<Integer>() {
@Override
public Integer getValue() {
return isMaster ? 1 : 0;
}
});
}
@Test
public void registerNamedMetric_registers_metric_using_sfx_mechanisms() {
// given
String gaugeName = UUID.randomUUID().toString();
// when
Gauge<String> result = sfxImpl.registerNamedMetric(gaugeName, gaugeMock);
// then
verifyMetricRegistration(gaugeTaggerMock, gaugeName, gaugeMock, result);
}
@Override
protected List<Metric> convertMetricEntry(Entry<String, Gauge> metricEntry, long timestamp) {
List<Metric> result = new ArrayList<>();
Object gaugeValue = metricEntry.getValue().getValue();
if (gaugeValue instanceof Number) {
Number number = (Number) gaugeValue;
result.add(buildCustomMetric(metricEntry.getKey() + ".value", number.doubleValue(), MetricType.GAUGE,
timestamp));
} else {
throw new IllegalArgumentException(String.format("The type {%s} for Gauge {%s} is invalid. The supported type is {%s}", gaugeValue.getClass().getName(), metricEntry.getKey(), Number.class.getName()));
}
return result;
}
private Gauge<BigDecimal> createLatencyGauge(int i, Top top, TimeUnit latencyUnit, int digitsAfterDecimalPoint) {
return () -> {
List<Position> positions = top.getPositionsInDescendingOrder();
if (positions.size() <= i) {
return zero;
}
double latencyNanos = positions.get(i).getLatencyInNanoseconds();
long scale = latencyUnit.toNanos(1);
double result = latencyNanos/scale;
return new BigDecimal(result).setScale(digitsAfterDecimalPoint, RoundingMode.CEILING);
};
}
@Test
public void gaugeReportsHeapMemoryUsageValue() throws Exception {
when(metricUnderTest.usedHeapMemory()).thenReturn(1L);
NettyAllocatorMetricSet metricSet = new NettyAllocatorMetricSet("test-metric", metricUnderTest);
Gauge<Long> metric = (Gauge<Long>) metricSet.getMetrics().get("test-metric.usedHeapMemory");
assertThat(metric.getValue(), is(1L));
}
/**
* Register desired metrics.
*/
private void registerMetrics()
{
metrics.register(BookKeeperMetrics.HealthMetric.LIVE_WORKER_GAUGE.getMetricName(), new Gauge<Long>()
{
@Override
public Long getValue()
{
// Clean up cache to ensure accurate size is reported.
liveWorkerCache.cleanUp();
log.debug(String.format("Reporting %d live workers", liveWorkerCache.size()));
return liveWorkerCache.size();
}
});
if (isValidationEnabled) {
metrics.register(BookKeeperMetrics.HealthMetric.CACHING_VALIDATED_WORKER_GAUGE.getMetricName(), new Gauge<Long>()
{
@Override
public Long getValue()
{
// Clean up cache to ensure accurate size is reported.
cachingValidatedWorkerCache.cleanUp();
log.debug(String.format("Caching validation passed for %d workers", cachingValidatedWorkerCache.size()));
return cachingValidatedWorkerCache.size();
}
});
metrics.register(BookKeeperMetrics.HealthMetric.FILE_VALIDATED_WORKER_GAUGE.getMetricName(), new Gauge<Long>()
{
@Override
public Long getValue()
{
// Clean up cache to ensure accurate size is reported.
fileValidatedWorkerCache.cleanUp();
log.debug(String.format("File validation passed for %d workers", fileValidatedWorkerCache.size()));
return fileValidatedWorkerCache.size();
}
});
}
}
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
Gauge gauge = (Gauge) object;
Object value = gauge.getValue();
SerializeWriter writer = serializer.getWriter();
if (value == null)
writer.write("0");
else
writer.write(value.toString());
}
public GossipCore(GossipManager manager, MetricRegistry metrics){
this.gossipManager = manager;
requests = new ConcurrentHashMap<>();
perNodeData = new ConcurrentHashMap<>();
sharedData = new ConcurrentHashMap<>();
eventManager = new DataEventManager(metrics);
metrics.register(PER_NODE_DATA_SIZE, (Gauge<Integer>)() -> perNodeData.size());
metrics.register(SHARED_DATA_SIZE, (Gauge<Integer>)() -> sharedData.size());
metrics.register(REQUEST_SIZE, (Gauge<Integer>)() -> requests.size());
messageSerdeException = metrics.meter(MESSAGE_SERDE_EXCEPTION);
transmissionException = metrics.meter(MESSAGE_TRANSMISSION_EXCEPTION);
transmissionSuccess = metrics.meter(MESSAGE_TRANSMISSION_SUCCESS);
}
private ConnectionsPool() {
String prefix = format("origins.%s.%s.connectionspool", origin.applicationId(), origin.id());
SortedMap<String, Gauge> gauges = metrics.getGauges();
availableGauge = gauges.get(prefix + ".available-connections");
busyGauge = gauges.get(prefix + ".busy-connections");
pendingGauge = gauges.get(prefix + ".pending-connections");
}
@Test
public void testHandleObserverRequestAlert() {
RulesConfigurationChangeRequest rulesConfigurationChangeRequest = createRulesConfigurationChangeRequest(true, false);
dataObserverRunner.handleConfigurationChangeRequest(rulesConfigurationChangeRequest);
dataObserverRunner.handleDataRulesEvaluationRequest(createProductionObserverRequest());
Gauge<Object> gauge = MetricsConfigurator.getGauge(metrics, AlertsUtil.getAlertGaugeName("myId"));
Assert.assertNotNull(gauge);
Assert.assertEquals((long) 3, ((Map<String, Object>) gauge.getValue()).get("currentValue"));
Assert.assertNotNull(((Map<String, Object>) gauge.getValue()).get("timestamp"));
}
private void registerJvmMetrics() {
// add JVM gauges
metrics.register("variable.jvm.free.memory",
new Gauge<Long>() {
@Override
public Long getValue() {
return Runtime.getRuntime().freeMemory();
}
}
);
metrics.register("variable.jvm.max.memory",
new Gauge<Long>() {
@Override
public Long getValue() {
return Runtime.getRuntime().maxMemory();
}
}
);
metrics.register("variable.jvm.total.memory",
new Gauge<Long>() {
@Override
public Long getValue() {
return Runtime.getRuntime().totalMemory();
}
}
);
}
@Test
public void reportsIncludedMeters() throws Exception {
InfluxDbReporter filteredReporter = InfluxDbReporter
.forRegistry(registry)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.filter(MetricFilter.ALL)
.groupGauges(true)
.includeMeterFields(Sets.newSet("m1_rate"))
.build(influxDb);
final Meter meter = mock(Meter.class);
when(meter.getCount()).thenReturn(1L);
when(meter.getOneMinuteRate()).thenReturn(2.0);
when(meter.getFiveMinuteRate()).thenReturn(3.0);
when(meter.getFifteenMinuteRate()).thenReturn(4.0);
when(meter.getMeanRate()).thenReturn(5.0);
filteredReporter.report(this.<Gauge>map(), this.<Counter>map(), this.<Histogram>map(), this.map("filteredMeter", meter), this.<Timer>map());
final ArgumentCaptor<InfluxDbPoint> influxDbPointCaptor = ArgumentCaptor.forClass(InfluxDbPoint.class);
verify(influxDb, atLeastOnce()).appendPoints(influxDbPointCaptor.capture());
InfluxDbPoint point = influxDbPointCaptor.getValue();
assertThat(point.getMeasurement()).isEqualTo("filteredMeter");
assertThat(point.getFields()).isNotEmpty();
assertThat(point.getFields()).hasSize(1);
assertThat(point.getFields()).contains(entry("m1_rate", 2.0));
assertThat(point.getTags()).containsEntry("metricName", "filteredMeter");
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void report(SortedMap<String, Gauge> gauges,
SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms,
SortedMap<String, Meter> meters,
SortedMap<String, Timer> timers) {
this.gauges = (SortedMap) gauges;
this.counters = counters;
this.histograms = histograms;
this.meters = meters;
this.timers = timers;
}