主页 > 知识库 > 详解grep获取MySQL错误日志信息的方法

详解grep获取MySQL错误日志信息的方法

热门标签:服务外包 Linux服务器 百度竞价排名 地方门户网站 网站排名优化 呼叫中心市场需求 AI电销 铁路电话系统

为方便维护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 []

有兴趣的朋友们参考学习下,感谢大家对脚本之家的支持。

您可能感兴趣的文章:
  • 通过案例分析MySQL中令人头疼的Aborted告警
  • MYSQL SERVER收缩日志文件实现方法
  • MySQL中常见的几种日志汇总
  • 详解 Mysql 事务和Mysql 日志
  • MySQL读取Binlog日志常见的3种错误
  • MySQL开启慢查询日志功能的方法
  • mysql binlog(二进制日志)查看方法
  • MySQL慢查询日志的基本使用教程
  • MySQL Aborted connection告警日志的分析

标签:崇左 兰州 湖南 湘潭 仙桃 衡水 铜川 黄山

巨人网络通讯声明:本文标题《详解grep获取MySQL错误日志信息的方法》,本文关键词  ;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 收缩
    • 微信客服
    • 微信二维码
    • 电话咨询

    • 400-1100-266