zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    用指针方法排序数组
    struct和typedef struct
    结构体类型定义的一般式
    HDOJ1020 Encoding
    malloc函数详解
    新手入门 acm 输入输出练习
    【算法入门】广度/宽度优先搜索(BFS)
    C++栈和队列
    hdu畅通工程
    codevs 2639 约会计划
  • 原文地址:https://www.cnblogs.com/GXLo/p/9494634.html
Copyright © 2011-2022 走看看