设为首页 收藏本站
查看: 1231|回复: 0

[经验分享] 分析Mysql慢日志脚本及快速定位慢Sql

[复制链接]

尚未签到

发表于 2018-10-24 06:01:22 | 显示全部楼层 |阅读模式
#!/usr/bin/python  
#coding=utf-8  #字符编码
  
import re  #导入正则匹配模块
  
import sys  #导入sys模块
  
import time #导入时间模块
  
import MySQLdb #导入连接mysql模块
  
canshu=len(sys.argv) #参数个数
  
def help():
  
    #帮助函数
  
    print "分析当天慢日志执行命令python %s today today" %sys.argv[0]
  
    print "分析以前慢日志执行命令python %s before 日志名字" %sys.argv[0]
  
def create_table():
  
    # 打开数据库连接
  
    db=MySQLdb.connect("192.168.1.10","mysql_slow","mysql_slow","log_fenxi")
  
    # 使用cursor()方法获取操作游标
  
    cursor=db.cursor()
  
    # 如果数据表已经存在使用 execute() 方法删除表。
  
    cursor.execute("DROP TABLE IF EXISTS `mysql_slow_log`;")
  
    # 创建数据表SQL语句
  
    sql="""CREATE TABLE `mysql_slow_log` (
  
      `id` int(11)  unsigned NOT NULL AUTO_INCREMENT,
  
      `IP` varchar(15) NOT NULL,
  
      `Query_time` float(11,6) NOT NULL,
  
      `Lock_time` char(11) NOT NULL,
  
      `Rows_sent` int(11) NOT NULL,
  
      `Rows_examined` int(11) NOT NULL,
  
      `sql_time` datetime NOT NULL,
  
      `slow_sql` text NOT NULL,
  
      PRIMARY KEY (`id`),
  
      KEY `Query_time` (`Query_time`),
  
      KEY `Rows_examined` (`Rows_examined`),
  
      KEY `sql_time` (`sql_time`)
  
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
  
    cursor.execute(sql)
  
    # 关闭数据库连接
  
    db.close()
  
def insert_table():
  
    log_file=open(log_name) #读取慢日志
  
    # 打开数据库连接
  
    db=MySQLdb.connect("192.168.1.10","mysql_slow","mysql_slow","log_fenxi")
  
    # 使用cursor()方法获取操作游标
  
    cursor = db.cursor()
  
    content=''  #默认匹配正则文本
  
    for line in log_file.readlines(): #把日志文件一次性读入内存,以列表方式显示
  
        line=line.strip('\n') #删除空白行回车
  
        content =content+line #添加到coneent默认文本
  
    re_mysql = re.findall('@\s+\[(.*?)\]#.*?Query_time: (.*?) Lock_time: (.*?) Rows_sent: (.*?)  Rows_examined: (.*?) Rows_affected: (.*?)  Rows_read: (.*?)#.*?timestamp=(.*?);(.*?);',content,re.I);  #具体匹配慢日志需要的参数,re.I忽略大小写
  
    for record in re_mysql:
  
           IP=record[0].strip()
  
           Query_time=record[1].strip()
  
           Lock_time=record[2].strip()
  
           Rows_sent=record[3].strip()
  
           Rows_examined=record[4].strip()
  
           timestamp=int(record[7])
  
           timeArray=time.localtime(timestamp)
  
           sql_time=time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
  
           slow_sql=record[8].strip()
  
           set_charset="set names utf8"
  
           sql = """INSERT INTO mysql_slow_log(IP,Query_time,Lock_time,Rows_sent,Rows_examined,sql_time,slow_sql)
  
                VALUES ('"""+IP+"""',"""+Query_time+""",'"""+Lock_time+"""',"""+Rows_sent+""","""+Rows_examined+""",'"""+sql_time+"""',\""""+slow_sql+"""\;\")""";
  
           try:
  
               # 执行sql语句
  
               cursor.execute(set_charset)
  
               cursor.execute(sql)
  
               print sql
  
               # 提交到数据库执行
  
               db.commit()
  
           except:
  
               # Rollback in case there is any error
  
               db.rollback()
  
    log_file.close()
  
    # 关闭数据库连接
  
    db.close()
  
def main():
  
    global log_name
  
    if canshu!=3:
  
       print "参数数量错误,请检查!"
  
       help()
  
    else:
  
       create_table()
  
       xuanze=sys.argv[1]   #第一个参数(慢日志时间)
  
       log_before=sys.argv[2] #慢日志具体时间
  
       if xuanze=='today':
  
            log_name='/data/mysqlp/mysql_slow.log'
  
            insert_table()
  
       elif xuanze=='before':
  
            log_name='/data/logs/mysql_slow/%s' %log_before
  
            insert_table()
  
       else:
  
            print '参数类型选择错误,类型只包含today|before'
  
            help()
  
main()



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-625564-1-1.html 上篇帖子: 【笔记】第1、2讲:sql概述 下篇帖子: Server 对象 错误 'ASP 0177 : 800401f3' Server.CreateObject 失败
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

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