Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.