• python 多线程日志切割+日志分析


    python 多线程日志切割+日志分析

    楼主最近刚刚接触python,还是个小菜鸟,没有学习python之前可以说楼主的shell已经算是可以了,但用shell很多东西实现起来还是不可能的事情,例如最明显的一点大日志分析,由于楼主的公司,每天的日志量很大,用shell分析的会非常非常的慢。

    通过学习python,楼主有了一种想法,想法如下

    可不可以分割日志,把日志分割成很多的小块,利用多线程去分析日志,这个难点在哪,难点就在如何去分割日志,前几篇文件楼主写过日志分割的python版,但是存在很大的弊端,只能够针对小日志进行分割,因为上一篇是把日志先写到列表中,大家都知道列表时要站内存的,那如果说日志很大,岂不一下就把内存吃满了。废话就不多说了,楼主来阐明下如何解决此问题

    首先创建一个文本,文本内容如下

    1

    2

    3

    1000

    1.计算出文本一行的大小比如说是4B

    2.用服务器的总内存数除以4B 计算出我的服务器可以一次性分析多大的文件,这个数就是我一个文本应该为多少行,也就是说我切割的日志,一个文件是多少行

    下面奉献出日志切割的脚本

    #!/usr/bin/python
    from time import ctime
    def splitFile(fileLocation, targetFoler):
    file_handler = open(fileLocation, ‘r’)
    block_size = 100   (为我每个文件的行数)
    line = file_handler.readline()
    temp = []
    countFile = 1
    while line:
    for i in range(block_size):
    if i == (block_size-1):
    # write block to small files
    file_writer = open(targetFoler + “file_”+str(countFile)+”.txt”, ‘a+’)
    file_writer.writelines(temp)
    file_writer.close()
    temp = []
    print ”  file ” + str(countFile) + ” generated at: ” + str(ctime())
    countFile = countFile + 1
    else:
    temp.append(file_handler.readline())
    if countFile == 11:
    break;

    file_handler.close()

    if __name__ == ‘__main__’:
    print “Start At: ” + str(ctime())
    splitFile(“/home/python/test.txt”, “/tmp/”)

    分割完日志后,下面就该进行日志分析了

    脚本如下

    #!/usr/bin/python
    import os
    import re
    import threading
    def chaFile(path):
    a=os.listdir(path)
    for i in range(len(a)):
    b=a[i]
    c=open(“/home/python/rizhifenge.txt”,”a+”)
    kk=” ”+b
    c.writelines(kk)
    c.close()
    d=open(“/home/python/rizhifenge.txt”,”r”)
    f=d.read()
    e=re.findall(“file.*”,f)
    return e
    d.close()

    def chaZhao(path):
    aa=open(path,”r+”)
    bb=aa.read()
    cc=re.search(“d.”,bb)
    if cc:
    print cc.group()
    aa.close()

    if __name__ == “__main__”:
    ff=”/tmp/”
    for i in chaFile(ff):
    gg=ff+i
    a=threading.Thread(target=chaZhao,args=(gg,))
    a.start()

  • 相关阅读:
    柔性的沟通
    as3简单的文字提示队列
    恢复低版本的FlashPlayer
    AIR切换SDK版本时遇到的问题
    文字闪烁提示
    as3 ISOLIB学习资料整理
    xml文件转二进制文件的AIR
    Photoshop CS5的序列号
    MySQL导出、导出数据
    as3 shake动画
  • 原文地址:https://www.cnblogs.com/timssd/p/10299188.html
Copyright © 2020-2023  润新知