python利用inotify实现把nginx日志实时写入数据库

利用了pyinotify库,我用的是这里的这个,https://github.com/seb-m/pyinotify
其实网上yum上也有pyinotify库可以安装。
写入数据库是pymysql这里做一下记录,
先务pyinotify实现一个tail -f 的功能:

#!/opt/python3/bin/python3
#
import pyinotify
import time
import os
import sys

class ProcessTransientFile(pyinotify.ProcessEvent):
    def process_IN_MODIFY(self,event):
        line = file.readline()
        if line:
            print(line, end=‘‘)

if __name__ == ‘__main__‘:
    filename = sys.argv[1]
    file = open(filename,‘r‘)
    st_results = os.stat(filename)
    st_size = st_results[6]
    file.seek(st_size)

    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm)
    wm.watch_transient_file(filename, pyinotify.IN_MODIFY, ProcessTransientFile)
    notifier.loop()

然后通过pytaif /usr/local/nginx/logs/www.tbbpay.com.access.log就可以进行日志的实时查看。

这个是实时查看,和tail -f 功能一样。只打印一行,

现在就是定义一个nginxloganalyzer函数进行日志分析,是默认的nginx日志,这个没有用正则,用了土办法查找特定字符。

def nginxLogAnalyzer(line):
    #print(line)
    g1 = line.find(‘[‘)
    g2 = line.find(‘]‘)
    h1 = line.find(‘"‘)
    h2 = line.find(‘"‘, h1+1)
    h3 = line.find(‘"‘, h2+1)
    h4 = line.find(‘"‘, h3+1)
    h5 = line.find(‘"‘, h4+1)
    h6 = line.find(‘"‘, h5+1)

    #print("g1:%d"%g1)
    #print("g2:%d"%g2)
    #print("h1:%d"%h1)
    #print("h2:%d"%h2)
    #print("h3:%d"%h3)
    #print("h4:%d"%h4)
    #print("h5:%d"%h5)
    #print("h6:%d"%h6)

    remote_addr = ""
    remote_user = ""
    time=""
    time_local = ""
    time_zone = ""
    request = ""
    status = ""
    body_bytes_sent = ""
    http_referer = ""
    http_user_agent = ""
    http_x_forwarded_for = ""

    time = line[g1+1:g2]
    time_local = time.split()[0]
    time_zone = time.split()[1]

    request = line[h1+1:h2]
    http_referer = line[h3+1:h4]
    http_user_agent = line[h5+1:h6]

    remote_addr = line.split()[0]
    remote_user = line.split()[1]
    status = line.split()[8]
    body_bytes_sent = line.split()[9]

    request = urllib.parse.unquote(request)
    print("time:%s"%(time) )
    print("time_local:%s"%(time_local) )
    print("time_zone:%s"%(time_zone) )
    print("request:%s"%(request) )
    print("http_referer:%s"%(http_referer) )
    print("http_user_agent:%s"%(http_user_agent) )

    print("status:%s"%(status) )
    print("body_bytes_sent:%s"%(body_bytes_sent) )

    print("request--------:%s"%(urllib.parse.unquote(request)) )
    l = []
    l.append(remote_addr)
    l.append(remote_user)
    l.append(time)
    l.append(time_local)
    l.append(time_zone)
    l.append(request)
    l.append(status)
    l.append(body_bytes_sent)
    l.append(http_referer)
    l.append(http_user_agent)
    l.append(http_x_forwarded_for)
    print(l)
    return l

对传一个行日志数据进行分析得到一个列表以备用,然后再写一个intodb函数插入数据库

这里先写数据库

CREATE DATABASE `nginxlog` CHARSET=utf8;
use nginxlog;

CREATE TABLE `nginxlog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `remote_add` varchar(50) DEFAULT NULL,
  `remote_user` varchar(50) DEFAULT NULL,
  `time` varchar(50) DEFAULT NULL,
  `time_local` varchar(50) DEFAULT NULL,
  `time_zone` varchar(10) DEFAULT NULL,
  `request` varchar(1024) DEFAULT NULL,
  `status` varchar(10) DEFAULT NULL,
  `body_bytes_sent` varchar(10) DEFAULT NULL,
  `http_referer` varchar(1024) DEFAULT NULL,
  `http_user_agent` varchar(1024) DEFAULT NULL,
  `http_x_forwarded_for` varchar(1024) DEFAULT NULL,
  PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=1001 DEFAULT CHARSET=utf8;

GRANT ALL PRIVILEGES ON nginxlog.* TO ‘nginxlog‘@‘192.168.1.112‘ IDENTIFIED BY ‘nginxlog‘;

这样就创建了表nginxlog的库和表。并创建了连接用户。

下面是插入数据库所定义的函数

def intodb(line):
    l = nginxLogAnalyzer(line)

    s = "INSERT INTO `nginxlog`.`nginxlog` (`id` ,`remote_add` ,`remote_user` ,`time` ,`time_local` ,`time_zone` ,`request` ,`status` ,`body_bytes_sent` ,`http_referer` ,`http_user_agent` ,`http_x_forwarded_for` )VALUES (‘null‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘);"%(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],l[8],l[9],l[10])
    print(s)
    cur.execute(s)
    conn.commit()

下面是所有源代码nginxlogtomysql.py

[[email protected] ~]# cat nginxLogtoMysql.py
#!/opt/python3/bin/python3
#
import pyinotify
import time
import os
import sys
import urllib
import urllib3
import pymysql

class ProcessTransientFile(pyinotify.ProcessEvent):
    def process_IN_MODIFY(self,event):
        line = file.readline()
        if line:
            #nginxLogAnalyzer(line)
            intodb(line)

def nginxLogAnalyzer(line):
    print(line,end=‘‘)
    g1 = line.find(‘[‘)
    g2 = line.find(‘]‘)
    h1 = line.find(‘"‘)
    h2 = line.find(‘"‘, h1+1)
    h3 = line.find(‘"‘, h2+1)
    h4 = line.find(‘"‘, h3+1)
    h5 = line.find(‘"‘, h4+1)
    h6 = line.find(‘"‘, h5+1)

    remote_addr = ""
    remote_user = ""
    time=""
    time_local = ""
    time_zone = ""
    request = ""
    status = ""
    body_bytes_sent = ""
    http_referer = ""
    http_user_agent = ""
    http_x_forwarded_for = ""

    time = line[g1+1:g2]
    time_local = time.split()[0]
    time_zone = time.split()[1]

    request = line[h1+1:h2]
    http_referer = line[h3+1:h4]
    http_user_agent = line[h5+1:h6]

    remote_addr = line.split()[0]
    remote_user = line.split()[1]
    status = line.split()[8]
    body_bytes_sent = line.split()[9]

    request = urllib.parse.unquote(request)
    #print("time:%s"%(time) )
    #print("time_local:%s"%(time_local) )
    #print("time_zone:%s"%(time_zone) )
    #print("request:%s"%(request) )
    #print("http_referer:%s"%(http_referer) )
    #print("http_user_agent:%s"%(http_user_agent) )
    #print("status:%s"%(status) )
    #print("body_bytes_sent:%s"%(body_bytes_sent) )
    #print("request--------:%s"%(urllib.parse.unquote(request)) )
    l = []
    l.append(remote_addr)
    l.append(remote_user)
    l.append(time)
    l.append(time_local)
    l.append(time_zone)
    l.append(request)
    l.append(status)
    l.append(body_bytes_sent)
    l.append(http_referer)
    l.append(http_user_agent)
    l.append(http_x_forwarded_for)
    #print(l)
    return l

def intodb(line):
    l = nginxLogAnalyzer(line)
    s = "INSERT INTO `nginxlog`.`nginxlog` (`id` ,`remote_add` ,`remote_user` ,`time` ,`time_local` ,`time_zone` ,`request` ,`status` ,`body_bytes_sent` ,`http_referer` ,`http_user_agent` ,`http_x_forwarded_for` )VALUES (‘null‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘, ‘%s‘);"%(l[0],l[1],l[2],l[3],l[4],l[5],l[6],l[7],l[8],l[9],l[10])
    #print(s)
    cur.execute(s)
    conn.commit()

if __name__ == ‘__main__‘:

    conn = pymysql.connect(host=‘192.168.1.112‘, port=3306, user=‘nginxlog‘, passwd=‘nginxlog‘, db=‘nginxlog‘,charset="utf8")
    cur = conn.cursor()
    cur.execute("SET NAMES utf8")

    filename = sys.argv[1]
    file = open(filename,‘r‘)
    st_results = os.stat(filename)
    st_size = st_results[6]
    file.seek(st_size)

    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm)
    wm.watch_transient_file(filename, pyinotify.IN_MODIFY, ProcessTransientFile)
    notifier.loop()

[[email protected] ~]#

运行方式如下:

./nginxlogtomysql.py /usr/local/nginx/logs/www.tbbpay.com.access.log

效果如下

时间: 2024-08-30 04:12:48

python利用inotify实现把nginx日志实时写入数据库的相关文章

利用ngxtop工具对nginx日志实时分析

参考:通过ngxtop实时监控webserver的访问情况 一.部署 准备:python2.7.3+.SQLite(否则会报错) 编译安装SQLite cd /usr/local/src && wget    #下载安装包,最新安装包请参考 tar xf sqlite-autoconf-3230100.tar.gz && cd sqlite-autoconf-3230100  #解压安装包 ./configure --prefix=/usr/local/sqlite &am

ngxtop nginx 日志实时峰分析

安装ngxtop wget http://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz tar zxvf setuptools-0.6c11.tar.gz cd setuptools-0.6c11 python setup.py build python setup.py install wget https://pypi.python.org/packages/source/p/pip/pip-7.1

Python获取Nginx访问日志,写入数据库

#!/usr/bin/env python # coding: utf-8 # Auther:liangkai # Date:2018/6/26 11:26 # License: (C) Copyright 2013-2018, Node Supply Chain Manager Corporation Limited. # Describe: import pymysql import re import datetime import sys import time # DB variabl

使用Log4j将程序日志实时写入Kafka

第一部分 搭建Kafka环境 安装Kafka 下载:http://kafka.apache.org/downloads.html tar zxf kafka-<VERSION>.tgz cd kafka-<VERSION> 启动Zookeeper 启动Zookeeper前需要配置一下config/zookeeper.properties: 接下来启动Zookeeper bin/zookeeper-server-start.sh config/zookeeper.properties

filebeat读取nginx日志并写入kafka

filebeat写入kafka的配置: filebeat.inputs: - type: log paths: - /tmp/access.log tags: ["nginx-test"] fields: type: "nginx-test" log_topic: "nginxmessages" fields_under_root: true processors: - drop_fields: fields: ["beat"

Syslog-ng+Rsyslog收集日志:写入数据库MySQ, MS-SQL,SQLite, mSQL(六)

为了统计方便,我们要从日志中选择一些消息放到数据库.对数据库读写支持要在编译时就要加上参数,还要在配置文件中开启对应的模块.模块如果很多监控都需要到数据库模块,可以放到/etc/rsyslog.conf全局配置文件里,如果只是某个监控收集用到那就放到/etc/rsyslog.d/的对应局部配置文件里. 1.编译. ./configure --enable-mysql 2.模块.生成的模板. ommysql # mysql输出模块 ompgsql # PostgreSQL的输出模块 omlibdb

Nginx 日志分析及性能排查

最近一直在做性能排查,思路就是根据分析Nginx日志,得到响应耗时的url.以及请求时间,再得到这段时间的请求量,并发量,分析是并发的原因,还是本身就比较慢,如果是应用本身的原因,只需要找到对应的代码,然后进行优化就好了 找到的几个原因,基本就是后端sql运行的比较多,单次访问看不出来,但是人比较多的时候就比较慢了,人少的时候20-200毫秒,人多的时候,200-6000毫秒,优化之后基本保持在几十毫秒,优化策略就是减少不必要的sql,加上缓存,基本解决了卡顿的问题,顺便把这次用的一系列命令记录

切分Nginx日志,完成网站访问量的自动统计

如果你的网站通过 Nginx 代理,那么本文将为你提供一个自动统计网站访问量的方案. 方案在实现步骤上,一个分为三步: 1. 运行 shell 脚本,移动 Nginx 日志到指定文件夹,并运行 Python 脚本: 2. 执行 Python 脚本,统计有效的 IP 访问量 3. 设置 crontab 定时任务. 一.shell 脚本 通过 Nginx 配置文件,查看监听端口的日志文件,并移动到指定的路径. 然后运行 Python 脚本,执行处理 Nginx 日志文件的 Python 脚本. sh

如何借助log4j把日志写入数据库中

log4j是一个优秀的开源日志记录项目,我们不仅可以对输出的日志的格式自定义,还可以自己定义日志输出的目的地,比如:屏幕,文本文件,数据 库,甚至能通过socket输出.本节使用MySQL数据库主要讲述如何将日志信息输入到数据库中. 用log4j将日志写入数据库主要用到是log4j包下的JDBCAppender类,它提供了将日志信息异步写入数据的功能,我们可以直接使用这个类将我 们的日志信息写入数据库:也可以扩展JDBCAppender类,就是将JDBCAppender类作为基类进行二次开发获得