• Log inStart now

Now that we've migrated this site's content to docs.newrelic.com, we're EOLing this site on June 21st 2024.

Send events from your product

Course

This procedure is a part of a course that teaches you how to build a quickstart. If you haven't already, checkout the course introduction.

Each procedure in this course builds on top of the last one, so make sure you've completed the last procedure, send metrics from your product before proceeding with this one.

Events capture things that occur in your product. For example, if your platform automates application deployments, you might generate an event every time a job runs. If your application scans for security vulnerabilities, you might generate an event every time you detect one.

New Relic, provides you a variety of ways to instrument your application to send events to our Event API.

In this lesson, you send events from your product using our telemetry software development kit (SDK).

Use our SDK

We offer an open source telemetry SDK in several of the most popular programming languages. These send data to our data ingest APIs, including our Event API. Of these language SDKs, two work with the Event API: Python and Java.

Here, you use the Python telemetry SDK to send events to New Relic.

Step 1 of 7

Change to the send-events/flashDB direcrory of the course repository.

bash
$
cd ../../send-events/flashDB
Step 2 of 7

If you haven't already, install the newrelic-telemetry-sdk package.

bash
$
pip install newrelic-telemetry-sdk
Step 3 of 7

Open db.py file in the IDE of your choice and configure the EventClient.

1
import os
2
import random
3
import datetime
4
from sys import getsizeof
5
6
from newrelic_telemetry_sdk import MetricClient, GaugeMetric, CountMetric, SummaryMetric
7
from newrelic_telemetry_sdk import EventClient
8
9
metric_client = MetricClient(os.environ["NEW_RELIC_LICENSE_KEY"])
10
event_client = EventClient(os.environ["NEW_RELIC_LICENSE_KEY"])
11
12
db = {}
13
stats = {
14
"read_response_times": [],
15
"read_errors": 0,
16
"read_count": 0,
17
"create_response_times": [],
18
"create_errors": 0,
19
"create_count": 0,
20
"update_response_times": [],
21
"update_errors": 0,
22
"update_count": 0,
23
"delete_response_times": [],
24
"delete_errors": 0,
25
"delete_count": 0,
26
"cache_hit": 0,
27
}
28
last_push = {
29
"read": datetime.datetime.now(),
30
"create": datetime.datetime.now(),
31
"update": datetime.datetime.now(),
32
"delete": datetime.datetime.now(),
33
}
34
35
def read(key):
36
37
print(f"Reading...")
38
39
if random.randint(0, 30) > 10:
40
stats["cache_hit"] += 1
41
42
stats["read_response_times"].append(random.uniform(0.5, 1.0))
43
if random.choice([True, False]):
44
stats["read_errors"] += 1
45
stats["read_count"] += 1
46
try_send("read")
47
48
def create(key, value):
49
50
print(f"Writing...")
51
52
db[key] = value
53
stats["create_response_times"].append(random.uniform(0.5, 1.0))
54
if random.choice([True, False]):
55
stats["create_errors"] += 1
56
stats["create_count"] += 1
57
try_send("create")
58
59
def update(key, value):
60
61
print(f"Updating...")
62
63
db[key] = value
64
stats["update_response_times"].append(random.uniform(0.5, 1.0))
65
if random.choice([True, False]):
66
stats["update_errors"] += 1
67
stats["update_count"] += 1
68
try_send("update")
69
70
def delete(key):
71
72
print(f"Deleting...")
73
74
db.pop(key, None)
75
stats["delete_response_times"].append(random.uniform(0.5, 1.0))
76
if random.choice([True, False]):
77
stats["delete_errors"] += 1
78
stats["delete_count"] += 1
79
try_send("delete")
80
81
def try_send(type_):
82
83
print("try_send")
84
85
now = datetime.datetime.now()
86
interval_ms = (now - last_push[type_]).total_seconds() * 1000
87
if interval_ms >= 2000:
88
send_metrics(type_, interval_ms)
89
90
def send_metrics(type_, interval_ms):
91
92
print("sending metrics...")
93
94
keys = GaugeMetric("fdb_keys", len(db))
95
db_size = GaugeMetric("fdb_size", getsizeof(db))
96
97
errors = CountMetric(
98
name=f"fdb_{type_}_errors",
99
value=stats[f"{type_}_errors"],
100
interval_ms=interval_ms
101
)
102
103
cache_hits = CountMetric(
104
name=f"fdb_cache_hits",
105
value=stats["cache_hit"],
106
interval_ms=interval_ms
107
)
108
109
response_times = stats[f"{type_}_response_times"]
110
response_time_summary = SummaryMetric(
111
f"fdb_{type_}_responses",
112
count=len(response_times),
113
min=min(response_times),
114
max=max(response_times),
115
sum=sum(response_times),
116
interval_ms=interval_ms,
117
)
118
119
batch = [keys, db_size, errors, cache_hits, response_time_summary]
120
response = metric_client.send_batch(batch)
121
response.raise_for_status()
122
print("Sent metrics successfully!")
123
clear(type_)
124
125
def clear(type_):
126
stats[f"{type_}_response_times"] = []
127
stats[f"{type_}_errors"] = 0
128
stats["cache_hit"] = 0
129
stats[f"{type_}_count"] = 0
130
last_push[type_] = datetime.datetime.now()
db.py

Important

This example expects an environment variable called $NEW_RELIC_LICENSE_KEY.

Step 4 of 7

Instrument your app to send an event to New Relic.

1
import os
2
import random
3
import datetime
4
from sys import getsizeof
5
6
from newrelic_telemetry_sdk import MetricClient, GaugeMetric, CountMetric, SummaryMetric
7
from newrelic_telemetry_sdk import EventClient, Event
8
9
metric_client = MetricClient(os.environ["NEW_RELIC_LICENSE_KEY"])
10
event_client = EventClient(os.environ["NEW_RELIC_LICENSE_KEY"])
11
12
db = {}
13
stats = {
14
"read_response_times": [],
15
"read_errors": 0,
16
"read_count": 0,
17
"create_response_times": [],
18
"create_errors": 0,
19
"create_count": 0,
20
"update_response_times": [],
21
"update_errors": 0,
22
"update_count": 0,
23
"delete_response_times": [],
24
"delete_errors": 0,
25
"delete_count": 0,
26
"cache_hit": 0,
27
}
28
last_push = {
29
"read": datetime.datetime.now(),
30
"create": datetime.datetime.now(),
31
"update": datetime.datetime.now(),
32
"delete": datetime.datetime.now(),
33
}
34
35
def read(key):
36
37
print(f"Reading...")
38
39
if random.randint(0, 30) > 10:
40
stats["cache_hit"] += 1
41
42
stats["read_response_times"].append(random.uniform(0.5, 1.0))
43
if random.choice([True, False]):
44
stats["read_errors"] += 1
45
stats["read_count"] += 1
46
try_send("read")
47
48
def create(key, value):
49
50
print(f"Writing...")
51
52
db[key] = value
53
stats["create_response_times"].append(random.uniform(0.5, 1.0))
54
if random.choice([True, False]):
55
stats["create_errors"] += 1
56
stats["create_count"] += 1
57
try_send("create")
58
59
def update(key, value):
60
61
print(f"Updating...")
62
63
db[key] = value
64
stats["update_response_times"].append(random.uniform(0.5, 1.0))
65
if random.choice([True, False]):
66
stats["update_errors"] += 1
67
stats["update_count"] += 1
68
try_send("update")
69
70
def delete(key):
71
72
print(f"Deleting...")
73
74
db.pop(key, None)
75
stats["delete_response_times"].append(random.uniform(0.5, 1.0))
76
if random.choice([True, False]):
77
stats["delete_errors"] += 1
78
stats["delete_count"] += 1
79
try_send("delete")
80
81
def try_send(type_):
82
83
print("try_send")
84
85
now = datetime.datetime.now()
86
interval_ms = (now - last_push[type_]).total_seconds() * 1000
87
if interval_ms >= 2000:
88
send_metrics(type_, interval_ms)
89
90
def send_metrics(type_, interval_ms):
91
92
print("sending metrics...")
93
94
keys = GaugeMetric("fdb_keys", len(db))
95
db_size = GaugeMetric("fdb_size", getsizeof(db))
96
97
errors = CountMetric(
98
name=f"fdb_{type_}_errors",
99
value=stats[f"{type_}_errors"],
100
interval_ms=interval_ms
101
)
102
103
cache_hits = CountMetric(
104
name=f"fdb_cache_hits",
105
value=stats["cache_hit"],
106
interval_ms=interval_ms
107
)
108
109
response_times = stats[f"{type_}_response_times"]
110
response_time_summary = SummaryMetric(
111
f"fdb_{type_}_responses",
112
count=len(response_times),
113
min=min(response_times),
114
max=max(response_times),
115
sum=sum(response_times),
116
interval_ms=interval_ms,
117
)
118
119
batch = [keys, db_size, errors, cache_hits, response_time_summary]
120
response = metric_client.send_batch(batch)
121
response.raise_for_status()
122
print("Sent metrics successfully!")
123
clear(type_)
124
125
def send_event(type_):
126
127
print("sending event...")
128
129
count = Event(
130
"fdb_method", {"method": type_}
131
)
132
133
response = event_client.send_batch(count)
134
response.raise_for_status()
135
print("Event sent successfully!")
136
137
def clear(type_):
138
stats[f"{type_}_response_times"] = []
139
stats[f"{type_}_errors"] = 0
140
stats["cache_hit"] = 0
141
stats[f"{type_}_count"] = 0
142
last_push[type_] = datetime.datetime.now()
db.py

Here, you instrument your platform to send a count event to New Relic.

Step 5 of 7

Amend the try_send module to send the event every 2 second.

1
import os
2
import random
3
import datetime
4
from sys import getsizeof
5
6
from newrelic_telemetry_sdk import MetricClient, GaugeMetric, CountMetric, SummaryMetric
7
from newrelic_telemetry_sdk import EventClient, Event
8
9
metric_client = MetricClient(os.environ["NEW_RELIC_LICENSE_KEY"])
10
event_client = EventClient(os.environ["NEW_RELIC_LICENSE_KEY"])
11
12
db = {}
13
stats = {
14
"read_response_times": [],
15
"read_errors": 0,
16
"read_count": 0,
17
"create_response_times": [],
18
"create_errors": 0,
19
"create_count": 0,
20
"update_response_times": [],
21
"update_errors": 0,
22
"update_count": 0,
23
"delete_response_times": [],
24
"delete_errors": 0,
25
"delete_count": 0,
26
"cache_hit": 0,
27
}
28
last_push = {
29
"read": datetime.datetime.now(),
30
"create": datetime.datetime.now(),
31
"update": datetime.datetime.now(),
32
"delete": datetime.datetime.now(),
33
}
34
35
def read(key):
36
37
print(f"Reading...")
38
39
if random.randint(0, 30) > 10:
40
stats["cache_hit"] += 1
41
42
stats["read_response_times"].append(random.uniform(0.5, 1.0))
43
if random.choice([True, False]):
44
stats["read_errors"] += 1
45
stats["read_count"] += 1
46
try_send("read")
47
48
def create(key, value):
49
50
print(f"Writing...")
51
52
db[key] = value
53
stats["create_response_times"].append(random.uniform(0.5, 1.0))
54
if random.choice([True, False]):
55
stats["create_errors"] += 1
56
stats["create_count"] += 1
57
try_send("create")
58
59
def update(key, value):
60
61
print(f"Updating...")
62
63
db[key] = value
64
stats["update_response_times"].append(random.uniform(0.5, 1.0))
65
if random.choice([True, False]):
66
stats["update_errors"] += 1
67
stats["update_count"] += 1
68
try_send("update")
69
70
def delete(key):
71
72
print(f"Deleting...")
73
74
db.pop(key, None)
75
stats["delete_response_times"].append(random.uniform(0.5, 1.0))
76
if random.choice([True, False]):
77
stats["delete_errors"] += 1
78
stats["delete_count"] += 1
79
try_send("delete")
80
81
def try_send(type_):
82
83
print("try_send")
84
85
now = datetime.datetime.now()
86
interval_ms = (now - last_push[type_]).total_seconds() * 1000
87
if interval_ms >= 2000:
88
send_metrics(type_, interval_ms)
89
send_event(type_)
90
91
def send_metrics(type_, interval_ms):
92
93
print("sending metrics...")
94
95
keys = GaugeMetric("fdb_keys", len(db))
96
db_size = GaugeMetric("fdb_size", getsizeof(db))
97
98
errors = CountMetric(
99
name=f"fdb_{type_}_errors",
100
value=stats[f"{type_}_errors"],
101
interval_ms=interval_ms
102
)
103
104
cache_hits = CountMetric(
105
name=f"fdb_cache_hits",
106
value=stats["cache_hit"],
107
interval_ms=interval_ms
108
)
109
110
response_times = stats[f"{type_}_response_times"]
111
response_time_summary = SummaryMetric(
112
f"fdb_{type_}_responses",
113
count=len(response_times),
114
min=min(response_times),
115
max=max(response_times),
116
sum=sum(response_times),
117
interval_ms=interval_ms,
118
)
119
120
batch = [keys, db_size, errors, cache_hits, response_time_summary]
121
response = metric_client.send_batch(batch)
122
response.raise_for_status()
123
print("Sent metrics successfully!")
124
clear(type_)
125
126
def send_event(type_):
127
128
print("sending event...")
129
130
count = Event(
131
"fdb_method", {"method": type_}
132
)
133
134
response = event_client.send_batch(count)
135
response.raise_for_status()
136
print("Event sent successfully!")
137
138
def clear(type_):
139
stats[f"{type_}_response_times"] = []
140
stats[f"{type_}_errors"] = 0
141
stats["cache_hit"] = 0
142
stats[f"{type_}_count"] = 0
143
last_push[type_] = datetime.datetime.now()
db.py

Your platform will now report the configured event every 2 seconds.

Step 6 of 7

Navigate to the root of your application at build-a-quickstart-lab/send-events/flashDB.

Step 7 of 7

Run your services to verify that it is reporting events.

bash
$
python simulator.py
Writing...
try_send
Writing...
try_send
Reading...
try_send
Reading...
try_send
Writing...
try_send
Writing...
try_send
Reading...
sending metrics...
Sent metrics successfully!
sending event...
Event sent successfully!

Alternative Options

If the language SDK doesn't fit your needs, try out one of our other options:

  • Manual Implementation: If our SDK in your preferred language doesn't support events, you can always manually instrument your own library to make a POST request to the New Relic Event API.
  • Prometheus Data: Prometheus data can be sent to New Relic in two ways, remote write and OpenMetrics. At a very high level, you should use remote write if you manage your own Prometheus servers and OpenMetrics if you don't.
  • Flex Agent: Our serverless Flex agent is a possibility, but might be a more complex integration to get started.

In this procedure, you instrumented your service to send events to New Relic. Next, instrument it to send logs.

Course

This procedure is a part of course that teaches you how to build a quickstart. Continue to next lesson, send logs from your product.

Copyright © 2024 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.