詳解grep獲取MySQL錯誤日志信息的方法
更新時間:2018年09月29日 10:51:32 投稿:laozhang
在本篇文章中小編給大家整理了關于通過grep 獲取MySQL錯誤日志信息的方法的相關知識點內容,有需要的朋友們跟著學習下。
為方便維護MySQL,寫了個腳本用以提供收集錯誤信息的接口。這些錯誤信息來自與MySQL錯誤日志,而 通過grep mysql可以獲取error-log的路徑。
以下是全部相關代碼:
#!/usr/bin/env python2.7 #-*- encoding: utf-8 -*- """ 該模塊用于提取每天mysql日志中的異?;蝈e誤信息 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錯誤日志中包含異?;蝈e誤信息的行 """ 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 []
有興趣的朋友們參考學習下,感謝大家對腳本之家的支持。
相關文章
MySQL重置root密碼提示"Unknown column ‘password"的解決方法
這篇文章主要介紹了MySQL重置root密碼提示"Unknown column ‘password"的解決方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-02-02使用SKIP-GRANT-TABLES 解決 MYSQL ROOT密碼丟失
這篇文章主要介紹了使用SKIP-GRANT-TABLES 解決 MYSQL ROOT密碼丟失的相關資料,需要的朋友可以參考下2015-09-09