threading和queue監控兩個log的python指令碼

來源:互聯網
上載者:User

標籤:

# coding:utf-8

__author__ = ‘admin‘

# --------------------------------

# Created by admin  on 2015/5/29.

# ---------------------------------

#/usr/bin/python

import redis,re,subprocess,threading,Queue

host="192.168.8.137"

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

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

_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


threading和queue監控兩個log的python指令碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.