threading和queue监控两个log的python脚本

# coding:utf-8python

__author__ = 'admin'nginx

# --------------------------------redis

# Created by admin  on 2015/5/29.shell

# ---------------------------------函数

#/usr/bin/pythonthis

import redis,re,subprocess,threading,Queuespa

host="192.168.8.137"线程

wiki_log="/home/nginx/logs/wiki.log"调试

other_log="/home/nginx/logs/other.log"code

_popen={}

queue=Queue.Queue()


#获取log的一行数据

def get_one_line(logpath):

    "get one line from log,logpath mast be a str"

    global  _popen,state

    if not _popen.has_key(logpath):

        _popen[logpath]=subprocess.Popen("tail -f %s"%(logpath,),stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)

    a=_popen[logpath].stdout.readline()

    return a


#获取一次访问的IP

def get_guest_ip_info(log):

    "get guest ip,this fun return a string"

    while 1:

        info=get_one_line(log)

        ip=re.match("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",info)

        return ip.group()



def ip_count():

     global  queue

     r = redis.Redis(host=host, port=6379, db=0)

     while 1:

         item=queue.get()

         if not r.exists(item[0]):

             r.zadd(item[0],item[1],1)

         else:

             #直接写也能够,不存在key值的话会自动建立

             r.zincrby(item[0],item[1],1)


def start_thread(target,args):

    "start a theard"

    t=threading.Thread(target=target,args=args)

    #加上setDaemon(True)的话,主线程不等待子线程结束就关闭全部线程,全部在子线程里print调试的内容都不会再前台显示出来

    # t.setDaemon(True)

    t.start()


def put_ip(log_name,log):

    global  queue

    while 1:

        ip=get_guest_ip_info(log)

        queue.put([log_name,ip])


def handle():

    #为避免put_ip陷入死循环(while 1:)没法执行后面的代码,因此每一个函数都用一个线程单独运行。

    #target目标函数不能带括号,args为空时,用()表示,一个参数时用(agrs,)表示

    start_thread(put_ip,("wiki",wiki_log))

    start_thread(put_ip,("other",other_log))

    start_thread(ip_count,())


def main():

    #主线程

    start_thread(handle,())


if __name__ == '__main__':

    main()

  

#放到后台运行ps -ef |grep python 能够看到
#python ip_count.py &
#远程链接到192.168.8.137查看
#redis-cli -h 192.168.8.137
#keys "wiki"
#ZRANGE wiki 0 -1 withscores
相关文章
相关标签/搜索