Skip to content

Instantly share code, notes, and snippets.

@driscollis
Forked from mostlyjason/gist:01d9af091a29d1c1975d
Last active August 29, 2015 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save driscollis/db11609833e408430d0d to your computer and use it in GitHub Desktop.
Save driscollis/db11609833e408430d0d to your computer and use it in GitHub Desktop.
import psutil
import simplejson
import time
import urllib2
# Sends the CPU and memory usage stats to Loggly. Sends both a machine total and per process.
def log():
""""""
proc_dict = {}
while True:
procs = psutil.get_process_list()
procs = sorted(procs, key=lambda proc: proc.name)
# log total usage
total_cpu = psutil.cpu_percent()
total_mem = psutil.virtual_memory().percent
data = {"process_name" : "total",
"cpu_percent": total_cpu,
"mem_percent": total_mem,
}
logData(data)
# log per-process usage
for proc in procs:
try:
name = proc.name()
cpu_percent = proc.get_cpu_percent()
mem_percent = proc.get_memory_percent()
except:
# this is a process with no name, so skip it
# or the process was killed
continue
data = {"process_name" : name,
"cpu_percent": cpu_percent,
"mem_percent": mem_percent,
}
logData(data)
time.sleep(5)
# send data to Loggly
def logData(data):
token = "8f9dc5df-a229-45ca-993c-d4a9d7249cce"
url = "http://logs-01.loggly.com/inputs/%s/tag/python,process_monitor/" % token
try:
log_data = simplejson.dumps(data)
urllib2.urlopen(url, log_data)
except:
# if there is a problem just skip it
return
if __name__ == "__main__":
log()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment