详解grep获取MySQL错误日志信息的方法
为方便维护MySQL,写了个脚本用以提供收集错误信息的接口。这些错误信息来自与MySQL错误日志,而通过grepmysql可以获取error-log的路径。
以下是全部相关代码:
#!/usr/bin/envpython2.7 #-*-encoding:utf-8-*- """ 该模块用于提取每天mysql日志中的异常或错误信息 author:xiaomo email:moxiaomomo@gmail.com """ importos importsys importstring fromdatetimeimport* #預設字符解碼器為utf-8 reload(sys) sys.setdefaultencoding('utf-8') COMMON_FLAGS=["error","exception","fail","crash","repair"] def_contain_flag(cur_str): forflaginCOMMON_FLAGS: ifflaginstring.lower(cur_str): returnTrue returnFalse """ 获取当前mysql实例的error_log文件路径 """ def_get_mysql_error_log_path(): log_path='' grep_infos=os.popen('psaux|grepmysql|grep"log-error"').read() iflen(grep_infos)>1: grep_infos=grep_infos.split("log-error=") iflen(grep_infos)>1: grep_infos=grep_infos[1].split('') iflen(grep_infos)>1: log_path=grep_infos[0] returnlog_path """ 读取mysql错误日志中包含异常或错误信息的行 """ def_get_error_info(error_log,begin_date): error_infos=[] f=open(error_log,'r') lines=f.readlines() forlineinlines: data_array=line.split('') iflen(data_array)>0andlen(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])) ifcur_date>=begin_dateand_contain_flag(line): error_infos.append(line) f.close() returnerror_infos """ 组装并返回mysql错误日志信息 """ defget_mysql_errors(begin_date=date.today()-timedelta(1)): try: err_log_path=_get_mysql_error_log_path() iflen(err_log_path)>1: return_get_error_info(err_log_path,begin_date) exceptException,e: print"[get_mysql_errors]%s"%e return[]
有兴趣的朋友们参考学习下,感谢大家对毛票票的支持。