#coding=utf8
import 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:
if p.status() != 'stopped':
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 @staticmethod
def monitor_system():
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:
#p = psutil.Process(0)
""":type :psutil.Process"""
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)
print p.status(),str(p.status()) 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:
monitor = Monitor()
monitor.monitor_system()
monitor.monitor_specified_process() time.sleep(10) if __name__ == "__main__":
monitoring()
监控linux的系统资源和自定义进程。
填入要监控的进程 ,只要ps -ef的command中包含need_monitor_procces_names中的字符串就可以,也可以监控java njinx。