溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何通過grep 獲取MySQL錯(cuò)誤日志信息

發(fā)布時(shí)間:2020-10-14 16:07:47 來源:億速云 閱讀:186 作者:小新 欄目:MySQL數(shù)據(jù)庫(kù)

小編給大家分享一下如何通過grep 獲取MySQL錯(cuò)誤日志信息,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

為方便維護(hù)MySQL,寫了個(gè)腳本用以提供收集錯(cuò)誤信息的接口。這些錯(cuò)誤信息來自與MySQL錯(cuò)誤日志,而 通過grep mysql可以獲取error-log的路徑。

#!/usr/bin/env python2.7
#-*- encoding: utf-8 -*-

"""
該模塊用于提取每天mysql日志中的異?;蝈e(cuò)誤信息
author: xiaomo
email: moxiaomomo@gmail.com
"""

import os
import sys
import string
from datetime import *

# 預(yù)設(shè)字符解碼器為utf-8
reload(sys)
sys.setdefaultencoding('utf-8') 

COMMON_FLAGS = ["error", "exception", "fail", "crash", "repair"]

def _contain_flag(cur_str):
    for flag in COMMON_FLAGS:
        if flag in string.lower(cur_str):
            return True
    return False

"""
獲取當(dāng)前mysql實(shí)例的error_log文件路徑
"""
def _get_mysql_error_log_path():
    log_path = ''
    grep_infos = os.popen('ps aux | grep mysql | grep "log-error"').read()
    if len(grep_infos) > 1:
        grep_infos = grep_infos.split("log-error=")
    if len(grep_infos) > 1:
        grep_infos = grep_infos[1].split(' ')
    if len(grep_infos) > 1:
        log_path = grep_infos[0]
    return log_path

"""
讀取mysql錯(cuò)誤日志中包含異常或錯(cuò)誤信息的行
"""
def _get_error_info(error_log, begin_date):
    error_infos = []
    f = open(error_log, 'r')
    lines = f.readlines()
    for line in lines:
        data_array = line.split(' ')
        if len(data_array) > 0 and len(data_array[0]) == 10:
            dt_strs = data_array[0].split('-')
            cur_date = date(int(dt_strs[0]), int(dt_strs[1]), int(dt_strs[2]))
            if cur_date >= begin_date and _contain_flag(line):
                error_infos.append(line)
    f.close()
    return error_infos

"""
組裝并返回mysql錯(cuò)誤日志信息
"""
def get_mysql_errors(begin_date=date.today()-timedelta(1)):
    try:
        err_log_path = _get_mysql_error_log_path()
        if len(err_log_path) > 1:
            return _get_error_info(err_log_path, begin_date)
    except Exception,e:
        print "[get_mysql_errors]%s"%e   
    return []

以上是如何通過grep 獲取MySQL錯(cuò)誤日志信息的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI