使用Python实现对日志文件的监控,并进行钉钉告警,通过查询服务器日志文件,找寻日志文件中关键字,向钉钉群聊中发送存在关键字行的日志,并艾特配置的相关人员,从而实现对日志文件的监控并告警,具体实现代码如下: # -*- coding: utf-8 -* import io import os import zipfile import dingtalkchatbot.chatbot as cb import datetime import sys reload(sys) sys.setdefaultencoding('utf8') class LOG(): def haszipfile(self,targetDir): """ 判断文件夹下是否存在zip :param targetDir: :return: """ for file in os.listdir(targetDir): targetFile = os.path.join(targetDir, file) if os.path.isfile(targetFile) and targetFile[-4:].lower == '.zip': return True return False def print_log(self,file,at_mobiles): try: for service in services: yesterday = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d") targetDir=file+service+'/logs' #logs目录 if self.haszipfile(targetDir): os.popen( 'unzip -o ' + file + service + '/logs/'+ service+ yesterday + '.zip -d ' + file + service + '/logs') log_file = file + service + '/logs/' +service+ yesterday else: log_file =file + service + '/logs/' +service+ yesterday+ '.log' f = io.open(log_file, "r", encoding='UTF-8') lines = f.readlines() # 查找关键字 for line in lines: if "exception" in line: secret= 'SECfe866b317f4f760af6071bb32a518b8bfc898394e67970ebd3100cae5c882086' #密签 webhook = 'https://oapi.dingtalk.com/robot/send?access_token=06e13726e305020c65c32c5b530460e2f88503cb573318dfd0c16359d98e36ef' #机器人发送消息url ding = cb.DingtalkChatbot(webhook,secret=secret,) ding.send_text(msg=service+'服务'+log_file+'日志文件存在异常关键词,所在行内容为:'+line,at_mobiles=at_mobiles) # print(log_file+'日志文件存在异常关键词,所在行内容为:'+line) else: pass f.close() except Exception as e: print(str(e)) if __name__ == '__main__': """ 设置每天8点定时执行. 1.在服务器输入命令:crontab -e 2.输入 0 8 * * * python /mnt/app/log.py,然后wq保存退出(py文件路径根据实际填写) """ services=['gateway','uaa-pg','cache-server'] #可配置多个服务日志目录下文件监控 file = '/mnt/app/' #服务根目录 at_mobiles=['12345678911'] #需要艾特人的手机号,支持配置多个 log=LOG()