Skip to content

Instantly share code, notes, and snippets.

@carlok
Last active August 5, 2022 21:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlok/759e52c4e1e9c15e9e903a82868191aa to your computer and use it in GitHub Desktop.
Save carlok/759e52c4e1e9c15e9e903a82868191aa to your computer and use it in GitHub Desktop.
How to send cpu, disk and memory percentage to InfluxDB (InfluxData) with callbacks (using psutil for operating system data)
"""
A python example regarding how to send CPU, disk and memory usage percentages to InfluxDB, using callbacks and psutil
(using psutil for operating system data)
There is also a basic query to plot the data on an Influx dashboard.
pip3 install influxdb-client psutil
On Influx, then you can query "memory", for example, with
from(bucket: "xxx")
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r["_measurement"] == "my_business_domain")
|> filter(fn: (r) => r["server"] == "local")
|> filter(fn: (r) => r["_field"] == "memory")
"""
import time
import psutil
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
def cpu_value_get():
return psutil.cpu_percent(interval=1)
def disk_value_get():
return psutil.disk_usage('/').percent
def memory_value_get():
return psutil.virtual_memory().percent
def field_point_get(custom_measurement, custom_tag, field, _callback):
return influxdb_client.Point(custom_measurement).tag(custom_tag['name'], custom_tag['value']).field(field, _callback())
def main():
while True:
point = {
'cpu': field_point_get(custom_measurement, custom_tag, 'cpu', cpu_value_get),
'disk': field_point_get(custom_measurement, custom_tag, 'disk', disk_value_get),
'memory': field_point_get(custom_measurement, custom_tag, 'memory', memory_value_get)
}
write_api.write(bucket=bucket, org=org, record=point['cpu'])
write_api.write(bucket=bucket, org=org, record=point['disk'])
write_api.write(bucket=bucket, org=org, record=point['memory'])
time.sleep(1)
#
# customize:
# endpoint, org, token, bucket
# custom_measurement, custom_tag
#
endpoint = 'https://eu-central-1-1.aws.cloud2.influxdata.com'
org = 'xxx@xxx.xx'
token = 'xxx'
bucket = "xxx"
custom_measurement = 'my_business_domain'
custom_tag = {'name': 'server', 'value': 'local'}
client = influxdb_client.InfluxDBClient(url=endpoint, token=token, org=org)
write_api = client.write_api(write_options=SYNCHRONOUS)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment