我处理apache日志实时入库的方法:
#coding:utf-8
#!/usr/bin/Python
import subprocess
import signal
import time
import datetime
import time
from CURD import Field, Model, Database
import os
flag=1
CONFIG = {
}
class dami_case(Model):
id = Field()
case_name = Field()
save_time = Field()
is_current = Field()
class dami_muma(Model):
id = Field()
source = Field()
ip = Field()
apkname = Field()
downtime = Field()
cid = Field()
#
#监控文件的变化,获取文件的内容进行存入库中。
#
#网址分析出对应的域名
#这里用了find方法,未找到返回-1,若使用index方法获取索引,如果没有找到会抛出异常
#需要自己写异常捕捉,否则程序就中断了
def gethostname(data):
if "http://" in data:
data = data[8:]
index = data.find('/')
if index == -1:
return data
else:
return data[:index]
#hostname转换成对应的名字
#在网页模板中转换.
#def hosttoname(host):
## if "baidu" in host:
# return "百度"
# if "91" in host:
# return "91助手"
# if
def monitorLog(logfile):
global flag
print "Strating........................."
popen = subprocess.Popen('tail -n 1 -f ' + logfile, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
while True:
line = popen.stdout.readline().strip()
if line:
if flag == 1:
flag = flag+1
continue
line = line.split(" ")
#测试部分
'''
print "ip:"+line[0]
print "time:"+line[3][1:]
print "apkname:"+os.path.basename(line[6])
print "http code:"+line[8]
print "url:"+gethostname(line[10])
'''
#过滤条件
if line[6] == "456.apk":
continue
#开始存库
#获取案件id号
cid = dami_case.where(is_current=1).getone()
data={
"ip":line[0],
"downtime":line[3][1:],
"apkname":os.path.basename(line[6]),
"source":gethostname[line[10]],
"cid":cid.id
}
dami_muma(**data).save()
if __name__ == '__main__':
#数据库配置部分
CONFIG['db_user'] = '****'
CONFIG['db_passwd'] = '****'
CONFIG['db'] = '****'
logfile="/var/log/apache2/muma.log"
Database.config(user=CONFIG['db_user'],
passwd=CONFIG['db_passwd'],
db=CONFIG['db'])
monitorLog(logfile)
考虑到我的apache日志并不是很多,所以没有考虑用线程加队列了。直接从pipe中读。如果数据多的话,可以考虑一个线程读pipe把数据放到队列中,另外一个线程读队列处理。如果再多的话,就多加几个线程来处理pipe中的数据,这里只有处理好从队列拿数据的原子性就OK了,保证同一时间几个线程从队列拿的是用一份数据。
3.想法
既然web日志可以达到实时入库,那么就可以利用这个思路,实现WEB日志显示。通过python相关web框架/php相关框架和相关图表的库来实现日志web显示。多台服务器的日志可以通过syslog中的-r选项实现日志统一汇总入库。后期有时间我来实现这个功能。觉得还是有点实用价值的。数据量太大就扛不住了,这也是事实。至少可以分析下最近访问的最多的页面确定热点区域。分析访问网站最多的ip,时间段等等信息。
4.总结
一些写程序一直用os里面的popen,后来发现subprocess这个包用处很大,后期认真看下这里面的一些相关函数,还有一个就是线程这个部分的内容。后期重点看看这方面的内容。
Python 的详细介绍:请点这里
Python 的下载地址:请点这里
本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-07/104741.htm
本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-07/1047.htm
