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.
Change to the send-events/flashDB direcrory of the course repository.
$cd ../../send-events/flashDB
If you haven't already, install the newrelic-telemetry-sdk
package.
$pip install newrelic-telemetry-sdk
Open db.py file in the IDE of your choice and configure the EventClient
.
1import os2import random3import datetime4from sys import getsizeof5
6from newrelic_telemetry_sdk import MetricClient, GaugeMetric, CountMetric, SummaryMetric7from newrelic_telemetry_sdk import EventClient8
9metric_client = MetricClient(os.environ["NEW_RELIC_LICENSE_KEY"])10event_client = EventClient(os.environ["NEW_RELIC_LICENSE_KEY"])11
12db = {}13stats = {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}28last_push = {29 "read": datetime.datetime.now(),30 "create": datetime.datetime.now(),31 "update": datetime.datetime.now(),32 "delete": datetime.datetime.now(),33}34
35def read(key):36
37 print(f"Reading...")38
39 if random.randint(0, 30) > 10:40 stats["cache_hit"] += 141
42 stats["read_response_times"].append(random.uniform(0.5, 1.0))43 if random.choice([True, False]):44 stats["read_errors"] += 145 stats["read_count"] += 146 try_send("read")47
48def create(key, value):49
50 print(f"Writing...")51
52 db[key] = value53 stats["create_response_times"].append(random.uniform(0.5, 1.0))54 if random.choice([True, False]):55 stats["create_errors"] += 156 stats["create_count"] += 157 try_send("create")58
59def update(key, value):60
61 print(f"Updating...")62
63 db[key] = value64 stats["update_response_times"].append(random.uniform(0.5, 1.0))65 if random.choice([True, False]):66 stats["update_errors"] += 167 stats["update_count"] += 168 try_send("update")69
70def 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"] += 178 stats["delete_count"] += 179 try_send("delete")80
81def try_send(type_):82
83 print("try_send")84
85 now = datetime.datetime.now()86 interval_ms = (now - last_push[type_]).total_seconds() * 100087 if interval_ms >= 2000:88 send_metrics(type_, interval_ms)89
90def 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_ms101 )102
103 cache_hits = CountMetric(104 name=f"fdb_cache_hits",105 value=stats["cache_hit"],106 interval_ms=interval_ms107 )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
125def clear(type_):126 stats[f"{type_}_response_times"] = []127 stats[f"{type_}_errors"] = 0128 stats["cache_hit"] = 0129 stats[f"{type_}_count"] = 0130 last_push[type_] = datetime.datetime.now()
Important
This example expects an environment variable called $NEW_RELIC_LICENSE_KEY
.
Instrument your app to send an event to New Relic.
1import os2import random3import datetime4from sys import getsizeof5
6from newrelic_telemetry_sdk import MetricClient, GaugeMetric, CountMetric, SummaryMetric7from newrelic_telemetry_sdk import EventClient, Event8
9metric_client = MetricClient(os.environ["NEW_RELIC_LICENSE_KEY"])10event_client = EventClient(os.environ["NEW_RELIC_LICENSE_KEY"])11
12db = {}13stats = {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}28last_push = {29 "read": datetime.datetime.now(),30 "create": datetime.datetime.now(),31 "update": datetime.datetime.now(),32 "delete": datetime.datetime.now(),33}34
35def read(key):36
37 print(f"Reading...")38
39 if random.randint(0, 30) > 10:40 stats["cache_hit"] += 141
42 stats["read_response_times"].append(random.uniform(0.5, 1.0))43 if random.choice([True, False]):44 stats["read_errors"] += 145 stats["read_count"] += 146 try_send("read")47
48def create(key, value):49
50 print(f"Writing...")51
52 db[key] = value53 stats["create_response_times"].append(random.uniform(0.5, 1.0))54 if random.choice([True, False]):55 stats["create_errors"] += 156 stats["create_count"] += 157 try_send("create")58
59def update(key, value):60
61 print(f"Updating...")62
63 db[key] = value64 stats["update_response_times"].append(random.uniform(0.5, 1.0))65 if random.choice([True, False]):66 stats["update_errors"] += 167 stats["update_count"] += 168 try_send("update")69
70def 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"] += 178 stats["delete_count"] += 179 try_send("delete")80
81def try_send(type_):82
83 print("try_send")84
85 now = datetime.datetime.now()86 interval_ms = (now - last_push[type_]).total_seconds() * 100087 if interval_ms >= 2000:88 send_metrics(type_, interval_ms)89
90def 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_ms101 )102
103 cache_hits = CountMetric(104 name=f"fdb_cache_hits",105 value=stats["cache_hit"],106 interval_ms=interval_ms107 )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
125def 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
137def clear(type_):138 stats[f"{type_}_response_times"] = []139 stats[f"{type_}_errors"] = 0140 stats["cache_hit"] = 0141 stats[f"{type_}_count"] = 0142 last_push[type_] = datetime.datetime.now()
Here, you instrument your platform to send a count
event to New Relic.
Amend the try_send
module to send the event every 2 second.
1import os2import random3import datetime4from sys import getsizeof5
6from newrelic_telemetry_sdk import MetricClient, GaugeMetric, CountMetric, SummaryMetric7from newrelic_telemetry_sdk import EventClient, Event8
9metric_client = MetricClient(os.environ["NEW_RELIC_LICENSE_KEY"])10event_client = EventClient(os.environ["NEW_RELIC_LICENSE_KEY"])11
12db = {}13stats = {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}28last_push = {29 "read": datetime.datetime.now(),30 "create": datetime.datetime.now(),31 "update": datetime.datetime.now(),32 "delete": datetime.datetime.now(),33}34
35def read(key):36
37 print(f"Reading...")38
39 if random.randint(0, 30) > 10:40 stats["cache_hit"] += 141
42 stats["read_response_times"].append(random.uniform(0.5, 1.0))43 if random.choice([True, False]):44 stats["read_errors"] += 145 stats["read_count"] += 146 try_send("read")47
48def create(key, value):49
50 print(f"Writing...")51
52 db[key] = value53 stats["create_response_times"].append(random.uniform(0.5, 1.0))54 if random.choice([True, False]):55 stats["create_errors"] += 156 stats["create_count"] += 157 try_send("create")58
59def update(key, value):60
61 print(f"Updating...")62
63 db[key] = value64 stats["update_response_times"].append(random.uniform(0.5, 1.0))65 if random.choice([True, False]):66 stats["update_errors"] += 167 stats["update_count"] += 168 try_send("update")69
70def 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"] += 178 stats["delete_count"] += 179 try_send("delete")80
81def try_send(type_):82
83 print("try_send")84
85 now = datetime.datetime.now()86 interval_ms = (now - last_push[type_]).total_seconds() * 100087 if interval_ms >= 2000:88 send_metrics(type_, interval_ms)89 send_event(type_)90
91def 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_ms102 )103
104 cache_hits = CountMetric(105 name=f"fdb_cache_hits",106 value=stats["cache_hit"],107 interval_ms=interval_ms108 )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
126def 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
138def clear(type_):139 stats[f"{type_}_response_times"] = []140 stats[f"{type_}_errors"] = 0141 stats["cache_hit"] = 0142 stats[f"{type_}_count"] = 0143 last_push[type_] = datetime.datetime.now()
Your platform will now report the configured event every 2 seconds.
Navigate to the root of your application at build-a-quickstart-lab/send-events/flashDB.
Run your services to verify that it is reporting events.
$python simulator.pyWriting...try_sendWriting...try_sendReading...try_sendReading...try_sendWriting...try_sendWriting...try_sendReading...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.