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("\n")
        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
相關文章
相關標籤/搜索