• Zabbix日志监控插件


    #!/usr/bin/env python
    # coding:utf-8
    
    import re
    import os
    import sys
    import logging
    
    logging.basicConfig(level=logging.DEBUG,  # 定义输出到文件的log级别,大于此级别的都被输出
                        format='%(asctime)s  %(filename)s : %(levelname)s  %(message)s',  # 定义输出log的格式
                        datefmt='%Y-%m-%d %H:%M:%S',  # 时间
                        filename='/etc/zabbix/scripts/check_log/check.log',  # log文件名
                        filemode='a+')
    
    logfile=sys.argv[1]
    keyword=sys.argv[2]
    statfile='/tmp/logfilestat.txt'
    
    
    logging.info("======================================================Start======================================================")
    logging.info('log_file: {0}, keyword: {1} '.format(logfile, keyword))
    
    try:
        f = open(statfile, 'r')
        # 获取文件读取的offset
        offset = f.readlines()
        f.close()
    except Exception,e:
        logging.info('{0} file not exits,create stat file!'.format(statfile))
        # 如果是第一次使用,文件读取状态不存在,这重置读取标志为空
        offset = []
    
    alter = []
    
    with open(statfile, 'w+') as offwr:
        with open(logfile, 'r') as f:
            # 如果读取状态文件,为空,则重置为从头读取
            if len(offset) == 0:
                f.seek(0, 2)
            elif len(offset) == 2:
            # 判断文件是否为新文件
                # 文件没有改变,则从上次读取的位置继续读取
                if int(offset[1]) == int(os.stat(logfile)[1]):
                    logging.info("start_offset: {0}".format(offset[0].strip()))
                    f.seek(int(offset[0].strip()))
                else:
                    # 如果文件改变了,则从头开始去读
                    logging.info("start_offset: 0")
                    f.seek(0)
                for i in f.readlines():
                    # 将查询结果用0和1存入list中
                    if re.search(str(keyword), i.strip()):
                        logging.error("Find {0} the key!!".format(keyword))
                        alter.append(0)
                    else:
                        alter.append(1)
            # 将文件读取位置和inode值写入状态文件
            offwr.write(str(f.tell()))
            offwr.write("
    ")
            offwr.write(str(os.stat(logfile)[1]))
    
    f.close()
    offwr.close()
    
    logging.info("======================================================End======================================================")
    
    # set是去重,如果list中包含1和2,则长度为2,应当报警
    if len(set(alter)) == 1:
        print 100
    else:
        print 200
    
  • 相关阅读:
    mysql-workbench-community报错解决办法
    前端技术交流群
    h5页面在浏览器上好好的,到手机上熄火了又看不到报错信息怎么办?
    【面试篇】金九银十面试季,这些面试题你都会了吗?
    [译]8个惊人的HTML按钮悬停效果,不看后悔一辈子
    'Component' is defined but never used
    DNS协议
    HTTP协议
    套接字Socket
    GYM102219H Are You Safe?(凸包)
  • 原文地址:https://www.cnblogs.com/GXLo/p/9494634.html
Copyright © 2020-2023  润新知