搜索
查看: 4786|回复: 0

Mysql实时监控脚本

[复制链接]

714

主题

354

回帖

2669

积分

管理员

本论坛第一帅

积分
2669

热心会员推广达人宣传达人突出贡献优秀版主荣誉管理论坛元老

QQ
发表于 2018-7-10 14:15:05 | 显示全部楼层 |阅读模式 来自 甘肃
环境(Python 2.7)

[pre]
#-*-coding:utf-8-*-
import time

#mysql log位置
file = '/Applications/XAMPP/xamppfiles/var/mysql/ADog.log'

#去重函数
def removal(string):
        log_list_new = []
        num = string[:2]
        log_list = string.split(num)
        for i in log_list:
                i = i.rstrip('\t').rstrip()
                log_list_new.append(i)
        log_list_new = list(set(log_list_new))
        string = num + ' '
        for j in log_list_new:
                string += j
        return string

#获取当前时间函数
def GetNowTime():
    return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))

#监控日志文件函数
def monitorLog(logFile):
  print '监控的日志文件 是%s' % logFile
  print '当前时间 是%s' % GetNowTime()
  with open(file , 'r') as fp:
    fp.seek(0,2)
    try:
      while True:
        last_pos = fp.tell()
        line = fp.readline().strip()
        #这里只读取预编译和执行语句
        if ('Prepare' in line) or ('Execute' in line) or ('Query' in line):
          print removal(line)
          print '--------------------------------------------------------------------------------------------------------------------'
    except KeyboardInterrupt:
      print 'exit...'

               
if __name__ == '__main__':
    monitorLog(file)


#-*-coding:utf-8-*-
import time

#mysql log位置
file = '/Applications/XAMPP/xamppfiles/var/mysql/ADog.log'

#去重函数
def removal(string):
        log_list_new = []
        num = string[:2]
        log_list = string.split(num)
        for i in log_list:
                i = i.rstrip('\t').rstrip()
                log_list_new.append(i)
        log_list_new = list(set(log_list_new))
        string = num + ' '
        for j in log_list_new:
                string += j
        return string

#获取当前时间函数
def GetNowTime():
    return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))

#监控日志文件函数
def monitorLog(logFile):
  print '监控的日志文件 是%s' % logFile
  print '当前时间 是%s' % GetNowTime()
  with open(file , 'r') as fp:
    fp.seek(0,2)
    try:
      while True:
        last_pos = fp.tell()
        line = fp.readline().strip()
        #这里只读取预编译和执行语句
        if ('Prepare' in line) or ('Execute' in line) or ('Query' in line):
          print removal(line)
          print '--------------------------------------------------------------------------------------------------------------------'
    except KeyboardInterrupt:
      print 'exit...'

               
if __name__ == '__main__':
    monitorLog(file)
[/pre]
这里需要说明下测试时候用的是某最新款cms,典型的TP5框架,所以通篇都是预编译,因此这里只选取了预编译相关的执行语句,后来再测试时候发现最普通的query语句没加入选取规则,不知道其他还有没有遗漏的,这里可以根据需要自行添加~

下面放出效果图(感觉还是有点复杂,,可能是打开了首页导致加载了过多的sql语句吧)
222.png
有志者,事竟成,破釜沉舟,百二秦关终属楚. 苦心人,天不负, 卧薪尝胆 ,三千越甲可吞吴
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表