利用了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/.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)

mit()

下面是所有源代码nginxlogtomysql.py

[root@localhost ~]# 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)

mit()

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()

[root@localhost ~]#

运行方式如下:

./nginxlogtomysql.py /usr/local/nginx/logs/.access.log

效果如下

python访问数据库日志文件_python利用inotify实现把nginx日志实时写入数据库相关推荐

  1. python写日志文件_Python logging日志模块 配置文件方式

    在一些微服务或web服务中我们难免需要日志功能,用来记录一些用户的登录记录,操作记录,以及一些程序的崩溃定位,执行访问定位等等; Python内置 非常强大的日志模块 ==> logging 今 ...

  2. mysql启动失败 查看日志文件_mysql诊断启动问题、查看日志文件详解

    诊断启动问题 服务器启动问题通常在对MySQL配置或服务器本身进行更改时出现.MySQL在这个问题发生时报告错误,但由于多数MySQL服务器是作为系统进程或服务自动启动的,这些消息可能看不到. 在排除 ...

  3. python输出日志文件_python将print输出的信息保留到日志文件中

    具体代码如下所示: import sys import os import sys import io import datetime def create_detail_day(): ''' :re ...

  4. python解析log文件_python解析基于xml格式的日志文件

    大家中午好,由于过年一直还没回到状态,好久没分享一波小知识了,今天,继续给大家分享一波Python解析日志的小脚本. 首先,同样的先看看日志是个啥样. 都是xml格式的,是不是看着就头晕了??没事,我 ...

  5. python怎么打开h5文件_python中利用h5py模块读取h5文件中的主键方法

    如下所示: import h5py import numpy as np #HDF5的写入: imgData = np.zeros((2,4)) f = h5py.File('HDF5_FILE.h5 ...

  6. python 实时监控日志文件_Python动态监控日志的内容

    日志文件一般是按天产生,则通过在程序中判断文件的产生日期与当前时间,更换监控的日志文件 程序只是简单的示例一下,监控test1.log 10秒,转向监控test2.log 程序监控使用是linux的命 ...

  7. python如何实现下载文件_python实现下载文件的三种方法

    python实现下载文件的三种方法 Python开发中时长遇到要下载文件的情况,最常用的方法就是通过Http利用urllib或者urllib2模块. 当然你也可以利用ftplib从ftp站点下载文件. ...

  8. python数据录入系统数据库处理导出_Python以太坊区块链交互将数据存入数据库

    关于区块链介绍性的研讨会通常以易于理解的点对点网络和银行分类账这类故事开头,然后直接跳到编写智能合约,这显得非常突兀.因此,想象自己走进丛林,想象以太坊区块链是一个你即将研究的奇怪生物.今天我们将观察 ...

  9. python下的所有文件_python批量复制文件夹下所有文件大小

    python复制文件夹下所有文件 Python---进阶---文件操作---获取文件夹下所有文件的数量和大小 一.####编写一个程序,统计当前目录下每个文件类型的文件数 ####思路: - 打开当前 ...

最新文章

  1. Android之对资源图片进行比例缩放
  2. Python读取文件内容为字符串的方法(多种方法详解)
  3. python聊天程序程序代码_python聊天程序实例代码分享
  4. Node — 第九天 (大事件项目接口实现三)
  5. openapi_MicroProfile OpenAPI上的Swagger UI
  6. 设计模式(十一):从文Finder中认识组合模式(Composite Pattern)
  7. pytorch学习笔记(5):vgg实现以及一些tricks
  8. 释放内容化势能 聚划算《划算8点档》给出新思路
  9. openssl pkeyutl执行SM2椭圆曲线数字签名
  10. 赢在微点答案专区英语_自考英语二太难?看了墨盒的单词本,保你信心满满去考试!...
  11. 蜂鸣器驱动电路 自主开发设计
  12. KITTI 3D目标检测离线评估工具包说明
  13. 二倍图三倍图什么意思_什么是二倍图三倍图
  14. c语言窗口贴图,c语言添加图片
  15. Optimal Design of Energy-Efficient Multi-User MIMO Systems: Is Massive MIMO the Answer?笔记
  16. 初出茅庐的小李第114篇博客项目笔记之机智云智能浇花器实战(3)-基础Demo实现
  17. 电路硬件设计——PCB布局和布线
  18. LAPACK的C/C++接口及代码实例
  19. Elasticsearch集群配置
  20. java测评系统_学生综合素质测评系统

热门文章

  1. c 传图片数据给matlab,c++ - 如何通过UDP将数据从C ++应用程序发送到Matlab并进行绘制 - 堆栈内存溢出...
  2. python导入标准库对象的语句_Python项目中如何优雅的import
  3. jquery获取浏览器版本号_前端为什么弃用jQuery?有这六个原因
  4. 何时查询2021高考成绩长春市,2020年吉林长春成人高考成绩查询入口(已开通)...
  5. java mvc 分页查询条件_java分页条件查询-GridManager.js表格插件+Pageable分页对象+mybatis pagehelper分页插件...
  6. CTF-Xortool,windows上的安装与使用
  7. 计算机应用基础任务化教程知识点,计算机应用基础任务化教程
  8. python贪婪与非贪婪_python 贪婪 非贪婪 匹配
  9. python与Excel的完美结合
  10. python PyQt5 QLCDNumber类(用于显示数字或一些符号的容器)