Monitor_数据分析篇(字段解释)

本文介绍了一个基于Python的系统监控程序的设计与实现。该程序利用多线程技术周期性收集CPU、内存、磁盘I/O等关键性能指标,并将数据记录到指定路径下的文件中。通过对配置文件的设置,用户可以灵活调整监控频率、监控时段等参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

监控程序:

#!/usr/bin/env python
#
-*- coding: cp936 -*-
import threading,os,time

class Config_th:
    
    
def Config_m(self):
        
        
#global set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday
        path = "monitor_config."
        monitor_config_path 
= open(path,'r')
        config_list 
= monitor_config_path.readlines()
        
#Set WorkPath Config 
        set_workpath = config_list[1][10:-1]
        
#set CommandPath Config
        set_commandpath = config_list[2][13:-1]
        
#set looptime Config
        set_looptime = config_list[3][17:-1]
        
#set loopdata Config
        set_loophour = config_list[4][14:-1]
        
#set loopday Config
        set_loopday = config_list[5][14:-1]
        
#test(os.system("echo %s" % (set_loopday)))
        return set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday

class Cpuinfo_th(threading.Thread,Config_th):
    
    
def __init__(self):
        threading.Thread.
__init__(self)
    
def run(self):
        
#global set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday
        set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday = self.Config_m()
        os.system(
"%s/iostat -t -c 1 1 >> %s/cpu_info.txt" % (set_commandpath,set_workpath))
            
class Memoryinfo_th(threading.Thread,Config_th):
    
    
def __init__(self):
        threading.Thread.
__init__(self)
    
def run(self):
        
#global set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday
        set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday = self.Config_m()
        os.system(
"/usr/bin/vmstat -S K 1 1 >> %s/memory_info.txt" % (set_workpath))
        
class Deciveinfo_th(threading.Thread,Config_th):
    
    
def __init__(self):
        threading.Thread.
__init__(self)
    
def run(self):
        
#global set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday
        set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday = self.Config_m()
        os.system(
"%s/iostat -d 1 1 >> %s/decive_io_info.txt" % (set_commandpath,set_workpath))

class Totalinfo_th(threading.Thread,Config_th):
    
    
def __init__(self):
        threading.Thread.
__init__(self)
    
def run(self):
        
#global set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday
        set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday = self.Config_m()
        os.system(
"%s/sar -u 1 1 >> %s/total_info.txt" % (set_commandpath,set_workpath))
        
class Control(Config_th):
    
    
def console(self):
        
#application object
        global set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday
        cpuinfo_th 
= Cpuinfo_th()
        memoryinfo_th 
= Memoryinfo_th()
        deciveinfo_th 
= Deciveinfo_th()
        totalinfo_th 
= Totalinfo_th()
        set_workpath,set_commandpath,set_looptime,set_loophour,set_loopday 
= self.Config_m()
        
#loop control main()
        for i in range(float(str(set_loopday))):
            
for i in range(float(str(set_loophour))):
                time.sleep(float(str(set_looptime)))
                
print "Execute OK!,run cpuinfo,%d" % (i)
                cpuinfo_th.run()
                time.sleep(
0.001)
                
print "Execute OK!,run memoryinfo,%d" % (i)
                memoryinfo_th.run()
                time.sleep(
0.001)
                
print "Execute OK!,run deciveinfo,%d" % (i)
                deciveinfo_th.run()
                time.sleep(
0.001)
                
print "Execute OK!,run totalinfo,%d" % (i)
                totalinfo_th.run()
                time.sleep(
0.001)
                
print "Total Execute %d......" % (i)
   
if __name__ == "__main__":
    
    control 
= Control()
    control.console()
        
        

 参数配置:

[Config]
work_path=/home/data
command_path=/usr/local/bin
loop_time_second=10
loop_day_hour=224
loop_week_day=7

[Cpu]
%usr:CPU处在用户模式下的时间百分比。 
%sys:CPU处在系统模式下的时间百分比。  
%wio:CPU等待输入输出完成时间的百分比。
%idle:CPU空闲时间百分比。
在所有的显示中,我们应主要注意%wio和%idle,%wio的值过高,表示硬盘存在I/O瓶颈, 
%idle值高,表示CPU较空闲,如果%idle值高但系统响应慢时,有可能是CPU等待分配内存, 
此时应加大内存容量。%idle值如果持续低于10,那么系统的CPU处理能力相对较低,表 
明系统中最需要解决的资源是CPU.

[Decive]
bread/s: 每秒从硬盘读入系统缓冲区buffer的物理块数。 
lread/s: 平均每秒从系统buffer读出的逻辑块数。 
%rcache: 在buffer cache中进行逻辑读的百分比。 
bwrit/s: 平均每秒从系统buffer向磁盘所写的物理块数。 
lwrit/s: 平均每秒写到系统buffer逻辑块数。 
%wcache: 在buffer cache中进行逻辑读的百分比。 
pread/s: 平均每秒请求物理读的次数。 
pwrit/s: 平均每秒请求物理写的次数。
在显示的内容中,最重要的是%cache和%wcache两列,它们的值体现着buffer的使用效 
率,%rcache的值小于90或者%wcache的值低于65,应适当增加系统buffer的数量,buffer 
数量由核心参数NBUF控制,使%rcache达到90左右,%wcache达到80左右。但buffer参数 
值的多少影响I/O效率,增加buffer,应在较大内存的情况下,否则系统效率反而得不到 
提高。

[Memory]
procs: 
r-->
;在运行队列中等待的进程数 
b-->;在等待io的进程数 
w-->;可以进入运行队列但被替换的进程 
memoy 
swap-->
;现时可用的交换内存(k表示) 
free-->;空闲的内存(k表示) 
pages 
re--》回收的页面 
mf--》非严重错误的页面 
pi--》进入页面数(k表示) 
po--》出页面数(k表示) 
fr--》空余的页面数(k表示) 
de--》提前读入的页面中的未命中数 
sr--》通过时钟算法扫描的页面 
disk 显示每秒的磁盘操作。 s表示scsi盘,0表示盘号 
fault 显示每秒的中断数 
in--》设备中断 
sy--》系统中断 
cy--》cpu交换 
cpu 表示cpu的使用状态 
cs--》用户进程使用的时间 
sy--》系统进程使用的时间 
id--》cpu空闲的时间 
 
如果 r经常大于 
4 ,且id经常少于40,表示cpu的负荷很重。 
如果pi,po 长期不等于0,表示内存不足。 
如果disk 经常不等于0, 且在 b中的队列 大于3, 表示 io性能不好。 

 
""" 第一步读取数据,取出我们想要的指标 服务器地址:localhost 数据库:bdpd_rmv 账户名:root 密码:123456 端口:3306 字符编码:'utf8mb4' 表名:RMV_KDSQ_MODEL_INDEX_INFO 提取指定字段:SCORE,BAD_FLAG """ import pandas as pd from sqlalchemy import create_engine import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.font_manager as fm def calKs(): # 数据库连接配置 db_config = { 'host': 'localhost', # 服务器地址 'port': 3306, # 端口 'user': 'root', # 账户名 'password': '123456', # 密码 'database': 'bdpd_rmv', # 数据库名 'charset': 'utf8mb4' # 字符编码(默认使用utf8mb4) } # 步骤1: 创建数据库连接 # 格式: mysql+pymysql://用户名:密码@主机:端口/数据库名 engine = create_engine( f"mysql+pymysql://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['database']}?charset={db_config['charset']}" ) # 步骤2: 读取数据并提取指定字段 query = "SELECT * FROM RMV_KDSQ_MODEL_INDEX_INFO" # SQL查询语句 data = pd.read_sql(query, engine) # 执行查询并读取到DataFrame data.columns=data.columns.str.upper() # 检查数据 print(f"成功读取 {len(data)} 条记录") print(data.head()) # 打印前5行数据 # 修复步骤1: 确保所有列使用正确数据类型 # 将SCORE转换为浮点数 data['SCORE'] = pd.to_numeric(data['SCORE'], errors='coerce') # 将BAD_FLAG转换为整数(0/1) data['BAD_FLAG'] = pd.to_numeric(data['BAD_FLAG'], errors='coerce').fillna(0).astype(int) #定义一个新的分组,按照FLAG和MONITOR_DT做分组 cols=['FLAG','MONITOR_DT'] modelInfo=data[cols].groupby(by=cols).first().reset_index() flag_list,monitor_list=modelInfo['FLAG'].to_list(),modelInfo['MONITOR_DT'].to_list() print(flag_list,monitor_list) modelInfo_len=len(flag_list) for i in range(modelInfo_len): print(flag_list[i],monitor_list[i]) # df=data.where((data['FLAG']==flag_list[i]) & (data['MONITOR_DT']==monitor_list[i])) # df=data[(data['FLAG']==flag_list[i]) & (data['MONITOR_DT']==monitor_list[i])] df=data.query(f"FLAG == '{flag_list[i]}' and MONITOR_DT == '{monitor_list[i]}'") df=df[['SCORE','BAD_FLAG']] print(df) # 步骤2: 按SCORE升序排序 df.sort_values('SCORE', ascending=True, inplace=True) # 步骤3: 添加行号 df.reset_index(drop=True, inplace=True) df['row_number'] = range(1, len(df) + 1) # 步骤4: 计算累计值(修复后) total_samples = len(df) total_bad = df['BAD_FLAG'].sum() # 现在返回数值 total_good = total_samples - total_bad # 不再报错 # 继续计算累计值... df['cum_bad'] = df['BAD_FLAG'].cumsum() df['GOOD_FLAG'] = 1 - df['BAD_FLAG'] df['cum_good'] = df['GOOD_FLAG'].cumsum() df['cum_bad_pct'] = df['cum_bad'] / total_bad if total_bad>0 else 0 df['cum_good_pct'] = df['cum_good'] / total_good if total_good>0 else 0 # 步骤5: 计算KS值(好坏占比差值的最大绝对值) # 计算每个分数点的好坏占比差值 df['cum_diff'] = abs(df['cum_bad_pct'] - df['cum_good_pct']) # 找到最大差值(即KS值) ks_value = df['cum_diff'].max() # 找到KS值对应的分数点 print(i,'找到KS值对应的分数点:',df['cum_diff'].idxmax()) ks_point = df.loc[df['cum_diff'].idxmax(), 'SCORE'] # 输出结果 print(f"\nKS值计算结果:") print(f"最大KS值: {ks_value:.4f}") print(f"KS值对应的分数点: {ks_point}") # 绘图 ks_plot(ks=ks_value,x=df['row_number'],y1=df['cum_bad_pct'],y2=df['cum_good_pct'],ks_point=ks_point,num=i) def ks_plot(ks,x,y1,y2,ks_point,num): # 可视化KS曲线(可选) import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.font_manager as fm # 解决方案1:使用系统支持的中文字体 plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'KaiTi', 'SimSun'] # 常用中文字体 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 plt.figure(figsize=(10, 6)) plt.plot(x, y1, label='累计坏客户占比') plt.plot(x, y2, label='累计好客户占比') # plt.axvline(x=ks_point, color='r', linestyle='--', label=f'KS点(分数={ks_point})') plt.title(f'KS曲线 (KS值={ks:.4f})') plt.xlabel('样本数') plt.ylabel('累计占比') plt.legend() plt.grid(True) # plt.savefig('ks.png') # 保存为图片 plt.show() #展示图片 if __name__ == '__main__': calKs() 逐行加注释,分析这边的代码
07-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值