python实时监控logstash日志代码


Posted in Python onApril 27, 2020

实时读取logstash日志,有异常错误keywork即触发报警。

# /usr/bin/env python3
# -*- coding: utf-8 -*-
# __author__ = caozhi
# create_time 2018-11-12,update_time 2018-11-15
# version = 1.0
# 录像高可用报警
# 1 读取日志 使用游标移动
# 2 线上业务日志文件会切割,切割后,读取上一个切割的日志

import os
import sys
import json
import requests
import time
import re

cini = conf.ini'
log_file = logstash.log'

def readconf():
 try:
 with open(cini, 'r+') as f:
  CONF = json.load(f)
 except:
 CONF = {"seek": 0, "inode": 922817, "last_file": logstash.log"}
 writeconf(CONF=CONF)
 print('conf.ini 配置文件缺失,自动创建一个新的配置文件')
 return CONF

def writeconf(CONF):
 with open(cini, 'w+') as e:
 json.dump(CONF, e)

def read_log(log_file, seek):
 try:
 f = open(log_file, 'r')
 except FileNotFoundError:
 f = open(logstash.log', 'r')
 seek = 0
 print('上一个文件读取失败了,请检查切割的日志文件')
 except:
 print('日志文件打开错误,退出程序')
 sys.exit()

f.seek(seek)
line = f.readline()
new_seek = f.tell()
if new_seek == seek:
 print('没有追加日志,退出程序')
 sys.exit()

while line:
 try:
 logstash = json.loads(line)
 except:
 CONF = {"seek": 0, "inode": 922817, "last_file": "/data/logs/lmrs/logstash.log"}
 writeconf(CONF=CONF)
 print('json数据加载错误,重新创建一个新的配置文件')
 sys.exit()

 #if '''re.search(time.strftime("%Y:%H:%M", time.localtime()), logstash.get('log_time')) and '''logstash.get('rtype') == 6 and logstash.get('uri') == '/publish' and logstash.get('event') == 0:
 if logstash.get('rtype') == 6 and logstash.get('uri') == '/publish' and logstash.get('event') == 0:
 value = 1
 stream = logstash.get('name')
 print('{} {}'.format(value, stream))
 record(value=value, stream=stream)
 else:
 value = 0
 stream = 0
 line = f.readline()
seek = f.tell()
f.close
return value, stream, seek

def record(value, stream):
 data = []
 record = {}
 record['metric'] = 'recording_high_availability_monitor'
 record['endpoint'] = os.uname()[1]
 record['timestamp'] = int(time.time())
 record['step'] = 60
 record['value'] = value
 record['counterType'] = 'GAUGE'
 record['Tags'] = '{}={}'.format(int(time.time()), stream)
 data.append(record)

if data:
 print('这是data的json数据')
 print(data)
 falcon_request = requests.post("http://127.0.0.1:1988/v1/push", data=json.dumps(data))
 #falcon_request = requests.post("http://127.0.0.1:1988/v1/push", json=data)
 print('json参数请求返回状态码为:' + str(falcon_request.status_code))
 print('json参数请求返回为:' + str(falcon_request.text))

if __name__ == '__main__':
 print()
 print('***************************************')
 print('本次执行脚本时间:{}'.format(time.strftime("%Y%m%d_%H%M", time.localtime())))
 CONF = readconf()
 print('first_CONF :{}'.format(CONF))
 print('NO1.log_file',log_file)
 last_inode = CONF['inode']
 inode = os.stat(log_file).st_ino
 print('last_inode: {} inode: {}'.format(last_inode, inode))

if inode == last_inode:
 seek = CONF['seek']
 next_file = 0
else:
 log_file = CONF['last_file'] + time.strftime("-%Y%m%d_", time.localtime()) + str(time.strftime("%H%M", time.localtime()))[:-1] + '0'
 next_file = 1
 seek = CONF['seek']

print('NO2.log_file',log_file)
value, stream, seek = read_log(log_file=log_file,seek=seek)

if next_file:
 CONF['seek'] = 0
else:
 CONF['seek'] = seek

CONF['inode'] = os.stat(logstash.log').st_ino
writeconf(CONF=CONF)
print('last_CONF :{}'.format(CONF))

补充知识:logstash 调用exec

我就废话不多说了,还是直接看代码吧!

[elk@Vsftp logstash]$ cat t3.conf 
input {
 stdin {
 } 
} 
filter {
 grok {
 match => [ "message","(?m)\s*%{TIMESTAMP_ISO8601:time}\s*(?<Level>(\S+)).*"]
 }
 date {
 match => ["time", "yyyy-MM-dd HH:mm:ss,SSS"]
 }
 mutate {
   add_field =>["type","tailong"]
   add_field =>["messager","%{type}-%{message}"]
   remove_field =>["message"]
  }
} 
output { 
 if ([Level] == "ERROR" or [messager] =~ "Exception" ) and [messager] !~ "温金服务未连接" and [messager] !~ "调用温金代理系统接口错误" and [messager] !~ "BusinessException" {
 exec {
  command => "/bin/smail.pl \"%{messager}\" \"%{type}\" "
 }
 }
 stdout { 
 codec =>rubydebug 
 } 
}
 
Vsftp:/root# cat /bin/smail.pl 
#!/usr/bin/perl 
use Net::SMTP;
use HTTP::Date qw(time2iso str2time time2iso time2isoz); 
use Data::Dumper;
use Getopt::Std;
use vars qw($opt_d );
getopts('d:');
# mail_user should be your_mail@163.com
 $message= "@ARGV";
 $env="$opt_d";
 sub send_mail{
 my $CurrTime = time2iso(time());
 my $to_address = shift;
 my $mail_user = 'zhao.yangjian@163.com';
 my $mail_pwd = 'xx';
 my $mail_server = 'smtp.163.com';
 
 my $from = "From: $mail_user\n";
 my $subject = "Subject: zjcap info\n";
 my $info = "$CurrTime--$message";
 my $message = <<CONTENT; 
 $info
CONTENT
 my $smtp = Net::SMTP->new($mail_server);
 
 $smtp->auth($mail_user, $mail_pwd) || die "Auth Error! $!";
 $smtp->mail($mail_user);
 $smtp->to($to_address);
 
 $smtp->data();  # begin the data
 $smtp->datasend($from); # set user
 $smtp->datasend($subject); # set subject
 $smtp->datasend("\n\n");
 $smtp->datasend("$message\n"); # set content
 $smtp->dataend();
 $smtp->quit();
};
 
send_mail ('zhao.yangjian@163.com'); 
 
2017-01-12 10:19:19,888 jjjjj Exception
{
 "@version" => "1",
 "@timestamp" => "2017-01-12T02:19:19.888Z",
  "host" => "Vsftp",
  "time" => "2017-01-12 10:19:19,888",
  "Level" => "jjjjj",
  "type" => "tailong",
 "messager" => "tailong-2017-01-12 10:19:19,888 jjjjj Exception"
}

以上这篇python实时监控logstash日志代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python列表(list)、字典(dict)、字符串(string)基本操作小结
Nov 28 Python
Python内置函数之filter map reduce介绍
Nov 30 Python
Python验证码识别的方法
Jul 10 Python
深入理解python中函数传递参数是值传递还是引用传递
Nov 07 Python
python SSH模块登录,远程机执行shell命令实例解析
Jan 12 Python
浅谈Tensorflow由于版本问题出现的几种错误及解决方法
Jun 13 Python
Python3+Pycharm+PyQt5环境搭建步骤图文详解
May 29 Python
Python计算一个点到所有点的欧式距离实现方法
Jul 04 Python
Django Rest framework三种分页方式详解
Jul 26 Python
pycharm编写spark程序,导入pyspark包的3中实现方法
Aug 02 Python
学习Django知识点分享
Sep 11 Python
解决paramiko执行命令超时的问题
Apr 16 Python
python实现秒杀商品的微信自动提醒功能(代码详解)
Apr 27 #Python
浅析python 定时拆分备份 nginx 日志的方法
Apr 27 #Python
python异步Web框架sanic的实现
Apr 27 #Python
python库skimage给灰度图像染色的方法示例
Apr 27 #Python
python实现密度聚类(模板代码+sklearn代码)
Apr 27 #Python
Django中文件上传和文件访问微项目的方法
Apr 27 #Python
详解Python中namedtuple的使用
Apr 27 #Python
You might like
PHP中=赋值操作符对不同数据类型的不同行为
2011/01/02 PHP
PHP对表单提交特殊字符的过滤和处理方法汇总
2014/02/18 PHP
php将文件夹打包成zip文件的简单实现方法
2016/10/04 PHP
php 魔术常量详解及实例代码
2016/12/04 PHP
Zend Framework实现自定义过滤器的方法
2016/12/09 PHP
Laravel 5.5基于内置的Auth模块实现前后台登陆详解
2017/12/21 PHP
js处理php输出时间戳对不上号的解决方法
2014/06/20 Javascript
深入浅出理解javaScript原型链
2015/05/09 Javascript
js实现大转盘抽奖游戏实例
2015/06/24 Javascript
js智能获取浏览器版本UA信息的方法
2016/08/08 Javascript
Angular路由简单学习
2016/12/26 Javascript
求js数组的最大值和最小值的四种方法
2017/03/03 Javascript
详解Vue整合axios的实例代码
2017/06/21 Javascript
深入理解Vue 的条件渲染和列表渲染
2017/09/01 Javascript
js中对象和面向对象与Json介绍
2019/01/21 Javascript
使用apifm-wxapi快速开发小程序过程详解
2019/08/05 Javascript
微信小程序自定义navigationBar顶部导航栏适配所有机型(附完整案例)
2020/04/26 Javascript
JS访问对象两种方式区别解析
2020/08/29 Javascript
python处理cookie详解
2014/02/07 Python
Python中exit、return、sys.exit()等使用实例和区别
2015/05/28 Python
浅析python打包工具distutils、setuptools
2018/04/20 Python
python实现电脑自动关机
2018/06/20 Python
python得到电脑的开机时间方法
2018/10/15 Python
python 文本单词提取和词频统计的实例
2018/12/22 Python
python实现合并两个排序的链表
2019/03/03 Python
Ubuntu+python将nii图像保存成png格式
2019/07/18 Python
python3字符串操作总结
2019/07/24 Python
Python实现ElGamal加密算法的示例代码
2020/06/19 Python
如何用Matplotlib 画三维图的示例代码
2020/07/28 Python
python语音识别指南终极版(有这一篇足矣)
2020/09/09 Python
学生个人求职自荐信格式
2013/09/23 职场文书
大学生军训自我鉴定
2014/02/12 职场文书
2015年农村党员公开承诺事项
2015/04/28 职场文书
spring cloud 配置中心native配置方式
2021/09/25 Java/Android
JavaScript 对象创建的3种方法
2021/11/17 Javascript
python实现一个简单的贪吃蛇游戏附代码
2022/06/28 Python