forked from newrelic/newrelic-telemetry-sdk-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GaugeExample.java
72 lines (59 loc) · 2.46 KB
/
GaugeExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Copyright 2019 New Relic Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.newrelic.telemetry.examples;
import com.newrelic.telemetry.Attributes;
import com.newrelic.telemetry.SimpleMetricBatchSender;
import com.newrelic.telemetry.metrics.Gauge;
import com.newrelic.telemetry.metrics.MetricBatchSender;
import com.newrelic.telemetry.metrics.MetricBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
* The purpose of this example is to demonstrate sending Gauge metrics to New Relic.
*
* <p>A gauge represents a numeric value measured at a point in time.
*
* <p>Additionally, this provides an example of using a {@code
* com.newrelic.telemetry.metrics.MetricBuffer} to hold on to metrics and send them as a batch.
*
* <p>To run this example, provide a command line argument for your Insights Insert key.
*/
public class GaugeExample {
private static final ThreadLocalRandom random = ThreadLocalRandom.current();
private static final List<String> rooms =
Arrays.asList("bedroom", "dining_room", "living_room", "basement");
public static void main(String[] args) throws Exception {
String insightsInsertKey = args[0];
MetricBatchSender sender = SimpleMetricBatchSender.builder(insightsInsertKey).build();
MetricBuffer metricBuffer = new MetricBuffer(getCommonAttributes());
for (int i = 0; i < 10; i++) {
Gauge currentTemperature = getCurrentTemperature();
System.out.println("Recording temperature: " + currentTemperature);
metricBuffer.addMetric(currentTemperature);
TimeUnit.SECONDS.sleep(5); // 5 seconds between measurements
}
sender.sendBatch(metricBuffer.createBatch());
}
/** These attributes are shared across all metrics submitted in the batch. */
private static Attributes getCommonAttributes() {
return new Attributes().put("exampleName", "GaugeExample");
}
private static Gauge getCurrentTemperature() {
return new Gauge(
"temperature",
random.nextDouble(60, 90),
System.currentTimeMillis(),
getTemperatureAttributes());
}
private static Attributes getTemperatureAttributes() {
Attributes attributes = new Attributes();
attributes.put("room", rooms.get(random.nextInt(rooms.size())));
attributes.put("occupied", random.nextBoolean());
attributes.put("humidity", random.nextInt(40, 60));
return attributes;
}
}