python实时监控滚动日志,推送企业微信消息

在运维岗位中经常巡检系统指标或者查看程序的日志,对实时生成的log文件,进行实时滚动监控
例如:需要对程序的日志进行提取关键字,并且发送到企业微信

在这里插入图片描述

代码示例:
#!/usr/bin/python3
# encoding=utf-8
import os
import subprocess
import time
import requests, json


# 发送文字
def send_wechat_msg(content,
                    webhook_url="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bedfjb79-49ca-42c2-598a-a29098bpe367"):
    data = {"msgtype": "markdown", "markdown": {"content": content}}
    r = requests.post(url=webhook_url, data=json.dumps(data, ensure_ascii=False).encode('utf-8'), verify=False)
    return r.text, r.status_code

#获取目录下的文件log
file = os.popen("ls -l /home/up/log/up*.log|awk -F' ' '{print $9}'").read()
item = file.split('\n')[0]


# 持续监控日志
def monitorLog(logFile):
    print('监控的日志文件是{}'.format(logFile))
    popen = subprocess.Popen('tail -10f ' + item, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    while True:
        line = popen.stdout.readline().strip()  # 读取行
        # 判断iupp是否在行中
        if 'iupp' in str(line):
            eeg_id = str(line).split('eeg_id:')[-1].split(',')[0]  # 进行提取想要的值
            eeg_type = str(line).split('eeg_type:')[-1].split(',')[0]  # 进行提取想要的值
            thistime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 系统时间
            print('eeg_type: ' + eeg_type, ' | ', 'eeg_id: ', eeg_id)  # 打印确认值
            #我这边需要拿到值去程序跑一下,再取结果输出,如果其他日志的话,可以调取机器人输出内容了
            time.sleep(5)  # 睡眠一下,不然读不到
            file = os.popen("iupp rds show rd du {} {}".format(eeg_id,
                                                                    eeg_type)).read()
            file2 = file + '}'  # 经过测试程序输出的内容末尾少},进行添加,方便序列化
            print(file2)  # 显示想要的内容
            try:
                if json.loads(file2)['id'] == 1:  # 变为字典,取主要的值进行匹配
                    send_wechat_msg(file2)  # 调用企业微信发送模块,将内容发送至企业微信
                    print('已发送到企业微信中', thistime)
                else:
                    print('没有id: 1')
                    continue
            except Exception:
                print('有异常')
                continue
        else:
            print('本行没有匹配匹配到iupp字符')
            continue
        # if thistime >= stoptime:
        # 终止子进程
        # popen.kill()
        # print ('杀死subprocess')
        # break


#    time.sleep(2)

if __name__ == '__main__':
    monitorLog(item)
代码执行

后台运行,或者添加定时任务,都可以
nohup python3 -u jk_iupp_log_.py > test_out.out 2>&1 &

执行结果

在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值