温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何通过grep 获取MySQL错误日志信息

发布时间:2020-10-14 16:07:47 来源:亿速云 阅读:174 作者:小新 栏目:MySQL数据库

小编给大家分享一下如何通过grep 获取MySQL错误日志信息,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

为方便维护MySQL,写了个脚本用以提供收集错误信息的接口。这些错误信息来自与MySQL错误日志,而 通过grep mysql可以获取error-log的路径。

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

"""
该模块用于提取每天mysql日志中的异常或错误信息
author: xiaomo
email: moxiaomomo@gmail.com
"""

import os
import sys
import string
from datetime import *

# 預設字符解碼器為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

"""
获取当前mysql实例的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错误日志中包含异常或错误信息的行
"""
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错误日志信息
"""
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错误日志信息的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI