通过grep 获取MySQL错误日志信息的方法代码示例


本文摘自PHP中文网,作者坏嘻嘻,侵删。

本篇文章给大家带来的内容是关于怎么通过grep 获取MySQL错误日志信息的方法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

#!/usr/bin/env python2.7

#-*- encoding: utf-8 -*-

 

"""

该模块用于提取每天mysql日志中的异常或错误信息

author: xiaomo

email: moxiaomomo@gmail.com

"""

 

import os

import sys

import string

from datetime import *

 

# ?A?O字符解?a器??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错误日志信息的方法代码示例的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

mysql主键是什么?

mysql中exists、in及any的基本用法

mysql服务器中主从配置介绍

mysql 无法启动的几种常见问题

mysql20个高性能架构设计原则(值得收藏)

mysql分表、分库、分片和分区知识深入详解

简述mysql explain 命令

新手学习mysql索引

mysql 如何求数据的长度

mysql中的用户id如何使用nginx访问日志来记录?

更多相关阅读请进入《mysql》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...