當(dāng)我們需要優(yōu)化MySQL查詢時(shí),第一想到的是開啟慢日志,慢日志可以看到執(zhí)行消耗超過一定時(shí)間的SQL語句和未使用索引的SQL。但如果我們想分析所有SQL查詢的分布,即哪類SQL查詢次數(shù)最多的時(shí)候,我們可以開啟general log來統(tǒng)計(jì)。
創(chuàng)新互聯(lián)長期為上1000+客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為佳木斯企業(yè)提供專業(yè)的網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè),佳木斯網(wǎng)站改版等技術(shù)服務(wù)。擁有十余年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。mysql> show variables like '%general%';
+——————+————————————-+
| Variable_name | Value |
+——————+————————————-+
| general_log | OFF |
| general_log_file | /usr/local/mysql/data/localhost.log |
+——————+————————————-+
mysql> set global general_log = "ON";
#!/usr/bin/python # sort and count mysql general log # Author: Jason # Url: www.centos.bz # Email: admin#centos.bz # Created: UTC 2015-02-15 17:51:53 import re import sys import os if len(sys.argv) == 2: logPath = sys.argv[1] if not os.path.exists(logPath): print ("file " + logPath + " does not exists.") sys.exit(1) else: print ("Usage: " + sys.argv[0] + " logPath") sys.exit(1) logFo = open(logPath) match = 0 for line in logFo: line = re.sub(r"\n","",line) if match == 0: # match line begin with numbers lineMatch = re.match(r"\s+[0-9]+\s+.*",line,flags=re.I) if lineMatch: lineTmp = lineMatch.group(0) match = match + 1 continue elif match == 1: # match line begin with numbers lineMatch = re.match(r"\s+[0-9]+\s+.*",line,flags=re.I) if lineMatch: # match only query lineMatchQuery = re.match(r".*Query\s+(.*)",lineTmp,flags=re.I) if lineMatchQuery: lineTmp = lineMatchQuery.group(1) # remove extra space lineTmp = re.sub(r"\s+", " ",lineTmp) # replace values (value) to values (x) lineTmp = re.sub(r"values\s*\(.*?\)", "values (x)",lineTmp,flags=re.I) # replace filed = 'value' to filed = 'x' lineTmp = re.sub(r"(=|>|<|>=|<=)\s*('|\").*?\2","\\1 'x'",lineTmp) # replace filed = value to filed = x lineTmp = re.sub(r"(=|>|<|>=|<=)\s*[0-9]+","\\1 x",lineTmp) # replace like 'value' to like 'x' lineTmp = re.sub(r"like\s+('|\").*?\1","like 'x'",lineTmp,flags=re.I) # replace in (value) to in (x) lineTmp = re.sub(r"in\s+\(.*?\)","in (x)",lineTmp,flags=re.I) # replace limit x,y to limit lineTmp = re.sub(r"limit.*","limit",lineTmp,flags=re.I) print (lineTmp) match = 1 lineTmp = lineMatch.group(0) else: lineTmp += line match = 1 logFo.close()
使用方法:
analysis-general-log.py general.log | sort | uniq -c | sort -nr
該python腳本使用與python2.7以上環(huán)境
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)cdcxhl.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。