前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 分析日志并发上报

python 分析日志并发上报

作者头像
葫芦
发布2019-04-17 16:26:48
8690
发布2019-04-17 16:26:48
举报
文章被收录于专栏:葫芦葫芦

分析日志并发上报

代码语言:javascript
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/11/6 下午4:42
# @Author  : BrownWang
# @Email   : 277215243@qq.com
# @File    : logtotnm2.py
# @Software: PyCharm

import os
import datetime
import threading
import sys
rootpath='/kkk/logs/bigbang_log/'
modules = os.listdir(rootpath)


def getmonitordir(modules):
    retlist = []
    for module in modules:
        path = '/kkk/logs/bigbang_log/'+module+'/monitor/'
        if os.path.isdir(path):
            retlist.append(path)
    return retlist


# 获取本时段内上一分钟的日志
def logfilterforlastminute(path):
    filename = (datetime.datetime.now() - datetime.timedelta(minutes=1)).strftime("%Y%m%d%H")
    try:
       file = open(path + filename + '.log', 'r')
    except Exception,e:
       print '未找到{0}'.format(path + filename + '.log')
       return []
    lines = file.readlines()
    timelag = (datetime.datetime.now() - datetime.timedelta(minutes=1)).strftime("%Y%m%d %H:%M")
    retlist = []
    for line in lines:
        if timelag in line:
            templist = line.split('|')[4:]
            for item in xrange(len(templist)):
                if item % 2 == 0:
                    retlist.append((templist[item], templist[item + 1].strip()))
    file.close()
    return retlist


# 上报tnm2系统
def agenttotnm2(tnm2list):
    return '|'.join([tnm2list[0], tnm2list[1], os.popen(
        "/kkk/kkk/agenttools/agent/agentRepNum " + tnm2list[0] + " " + tnm2list[1]).read().replace('\n', '')])


# 多线程并发上报tnm2系统
def multithreadtotnm2(result=True):
    threads = []
    retlist = []
    for path in getmonitordir(modules):
        if len(logfilterforlastminute(path))!=0:
            for tnm2list in logfilterforlastminute(path):
                thread = MyThread(agenttotnm2, args=(tnm2list,))
                threads.append(thread)
    for t in threads:
        t.start()
    for t in threads:
        t.join()
        if result == True:
            retlist.append(t.get_result())
    if result == True:
        return "\n".join(retlist) + '\nresults_num=' + str(len(retlist))
    return '已上报成功,如需查看返回值,请加参数 1 '

# 使得线程可通过get_result方法得到返回参数
class MyThread(threading.Thread):
    def __init__(self, func, args=()):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result  # 如果子线程不使用join方法,此处可能会报没有self.result的错误
        except Exception:
            return None



if __name__ == '__main__':

    # 关闭结果获取
    if len(sys.argv) == 2:
        switch = sys.argv[1]
        if switch == '1':
            switch = True
        else:
            switch = False
    else:
        switch = False
    results = multithreadtotnm2(result=switch)
    print results
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017/11/06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档