广告
返回顶部
首页 > 资讯 > 数据库 >详解grep获取MySQL错误日志信息的方法
  • 482
分享到

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

2024-04-02 19:04:59 482人浏览 独家记忆
摘要

为方便维护Mysql,写了个脚本用以提供收集错误信息的接口。这些错误信息来自与mysql错误日志,而 通过grep mysql可以获取error-log的路径。 以下是全部相关代码: #!/usr/bi

为方便维护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 []
您可能感兴趣的文档:

--结束END--

本文标题: 详解grep获取MySQL错误日志信息的方法

本文链接: https://www.lsjlt.com/news/50781.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作