一个监控linux系统资源和指定进程资源的程序
#coding=utf8import time
import psutil
from pprint import pprint
from logger_until import LoggerUntil
logger = LoggerUntil(name="Monitor").getlog(logfilename='Monitor.log', loglevel=2, add_StreamHandler=1)
need_monitor_procces_names = [
'touna0627.py',
'dailiip.py',
'redis-server',
'mongod',
]
class Monitor(object):
def __init__(self):
self.specified_process_list = self.get_specified_process()
def print_all_cmd_lines(self):
pass
def get_specified_process(self):
all_pids = psutil.pids()
process_list = []
for pid in all_pids:
p = psutil.Process(pid)
p_cmdline = p.cmdline()
for argx in p_cmdline:
for name in need_monitor_procces_names:
if argx.find(name) > -1:
process_list.append(p)
p_pid_set = set()
process_list2 = []
for p in process_list :
if p.pid not in p_pid_set:
process_list2.append(p)
p_pid_set.add(p.pid)
return process_list2
def monitor_system(self):
psutil.cpu_percent()
time.sleep(1)
mem = psutil.virtual_memory()
mem_total = mem.total/1000000
mem_available =mem.available/1000000
mem_percent = str(mem.percent) + '%'
cpu_count = psutil.cpu_count()
cpu_percent = psutil.cpu_percent()
msg = '本机总内存是:{0}M , 本机可用内存是:{1}M, 本机内存使用率是:{2}, 本机cpu核数是:{3}, 本机cpu使用率是:{4}'.format(mem_total, mem_available, mem_percent,cpu_count,cpu_percent)
logger.info(msg)
def monitor_specified_process(self):
for p in self.specified_process_list:
p.cpu_percent(None)
time.sleep(1)
for p in self.specified_process_list:
cmdline_str =' '.join(p.cmdline()).ljust(60,' ')
p_cpu_percent_str = str(round(p.cpu_percent(),2)) +'%'
p_memory_percent_str = str(round(p.memory_percent(),2)) + '%'
p_strated_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(p.create_time()))
p_pid_str = str(p.pid)
msg = '进程' + cmdline_str + ' 的pid是:' + p_pid_str +' cpu使用率是:' + p_cpu_percent_str + ' 内存使用率是:' + p_memory_percent_str \
+' 进程的启动时间是:' + p_strated_time
logger.info(msg)
def monitoring():
while 1:
time.sleep(10)
monitor = Monitor()
monitor.monitor_system()
monitor.monitor_specified_process()
print '\n'
监控linux的系统资源和自定义进程。
填入要监控的进程 ,只要ps -ef的command中包含need_monitor_procces_names中的字符串就可以,也可以监控java njinx。
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。