在运维岗位中经常巡检系统指标或者查看程序的日志,对实时生成的log文件,进行实时滚动监控
例如:需要对程序的日志进行提取关键字,并且发送到企业微信
![在这里插入图片描述](https://img-blog.csdnimg.cn/a7b0875ff62442e4bd39982fb7098e27.png)
代码示例:
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
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()
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 __name__ == '__main__':
monitorLog(item)
代码执行
后台运行,或者添加定时任务,都可以
nohup python3 -u jk_iupp_log_.py > test_out.out 2>&1 &
执行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/d67ded347cba4c7c961af052991e3cc0.png)