Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple server usage monitoring, writing json to stdout. depends on psutil and python3.4, but should work with any python version with minor modifications.
#!/usr/bin/env python3.4
"""
simple server usage monitoring, writing json to stdout. depends on
psutil and python3.4, but should work with any python version with
minor modifications.
to add usage to your log: $ nohup python3.4 usage.py 3 >> /var/log/your_normal_app_log.log &
to isolate usage in your log: $ grep [-v] '^usage: ' /var/log/your_normal_app_log.log
"""
import sys
import psutil
import json
import time
interval = int(sys.argv[1]) if len(sys.argv) == 2 else 1
bytes_in_last = bytes_out_last = 0
while True:
net = psutil.net_io_counters()
bytes_in, bytes_out = net.bytes_recv, net.bytes_sent
usage = json.dumps({
'cpu_percent': psutil.cpu_percent(),
'memory_percent': psutil.virtual_memory().percent,
'cache_percent': psutil.virtual_memory().cached / psutil.virtual_memory().total * 100,
'swap_percent': psutil.swap_memory().percent,
'disk_percent': psutil.disk_usage('/').percent,
'bytes_in': bytes_in - bytes_in_last,
'bytes_out': bytes_out - bytes_out_last,
'net_fds': len(psutil.net_connections()),
'pids': len(psutil.pids())
})
print('usage:', usage, flush=True)
time.sleep(interval)
bytes_in_last, bytes_out_last = bytes_in, bytes_out
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.