Home  >  Article  >  Backend Development  >  Monitor python logcat keywords

Monitor python logcat keywords

coldplay.xixi
coldplay.xixiforward
2020-09-04 17:05:453161browse

Monitor python logcat keywords

Related learning recommendations: python tutorial

This article mainly introduces the use of Python to call ADB commands to implement real-time monitoring of logcat keywords The function

adopts multi-process, which can monitor multiple devices and multiple keywords at the same time.

You need to configure the ADB environment. I won’t introduce the specific configuration. Just search a lot and go directly to the code.

Control the monitoring function on and off through a global variable. INSTRUCTION is used to follow the instructions. Get the corresponding method name

import os, threading, datetime

# 获取当前文件所在目录,拼接出LOG路径
LOG_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "log")

# 配置需要监控的关键字
KEYWORDS = ["ANR ", "NullPointerException", "CRASH", "Force Closed"]

# 控制开启和关闭
STOP_LOGCAT = True

# 指令对应具体操作
INSTRUCTION = {
               "1": "filter_keywords",
               "2": "stop_filter_keywords",
               "3": "exit"
               }


def filter_keywords():
    global STOP_LOGCAT
    STOP_LOGCAT = False
    devices = get_devices()  # 先获取所有连接的设备
    print("开始监控关键字")
    for device in devices:
        t = threading.Thread(target=filter_keyword, args=(device,))
        t.start()


def stop_filter_keywords():
    global STOP_LOGCAT
    if STOP_LOGCAT:
        print("没有正在执行的任务\n")
    else:
        STOP_LOGCAT = True
        print("正在停止关键字监控\n")

Monitor keyword main function,

def filter_keyword(device):
    print("设备%s关键字监控已开启" % str(device))
    sub = logcat(device)
    with sub:
        for line in sub.stdout: # 子进程会持续输出日志,对子进程对象.stdout进行循环读取
            for key in KEYWORDS:
                if line.decode("utf-8").find(key) != -1: # stdout输出为字节类型,需要转码
                    message = "设备:%s 检测到:%s\n" % (device, key)# 设备:192.168.56.104:5555 检测到:ANR
                    path = get_log_path("bugreport") # 根据时间创建文件夹
                    bugreport(device, path)# 拉取完整日志压缩包到创建的文件夹内
                    send_message(message) # 这里可以换成自己要做的事情,比如发送邮件或钉钉通知
            if STOP_LOGCAT:
                break
        print("设备%s关键字监控已停止" % str(device))
        sub.kill()

Create a process through subprocess.Popen to execute the command, and continuously output the log to stdout

# logcat持续输出日志
def logcat(device):
    command = "adb -s " + str(device) + " logcat -v time"
    sub = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return sub

Get all connected The device method, after executing "adb devices", the output is as follows. By cutting the string obtained by executing the command, all device numbers are obtained and stored in list format

# 获取所有device
def get_devices():
    command = "adb devices"
    res = os.popen(command).read()
    devices = []
    res = res.split("\n")
    for i in res:
        if i.endswith("device"):
            devices.append(i.split('\t')[0])
    return devices
# 打包下载所有日志到当前目录
def bugreport(device, path):
    os.chdir(path)# bugreport会下载日志到当前文件夹,所以需要先切换到已经创建的目录
    command = "adb -s " + str(device) + " bugreport"
    subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1)
    print("设备:%s 日志路径:%s" % (str(device), path))

to the current file Get the log path in the directory/year/month/day format. If it does not exist, it will automatically create the

# 获取日志存放路径,如果不存在则按日期创建
def get_log_path(tag):
    year = datetime.datetime.now().strftime('%Y')
    month = datetime.datetime.now().strftime('%m')
    day = datetime.datetime.now().strftime('%d')
    path = os.path.join(LOG_PATH, tag, year, month, day)
    if not os.path.exists(path):
        os.makedirs(path)
    return path

main function, receive instructions in a loop, get the method name according to the received instructions, and execute it through the eval() method.

def main():
    while True:
        print("-" * 100)
        print("1:开启关键字监控\n2:停止关键字监控\n3:退出")
        print("-" * 100)
        instruction = str(input("\n\n请输入要进行的操作号:\n"))
        print("-" * 100)
        while instruction not in INSTRUCTION.keys():
            instruction = str(input("\n\n输入无效,请重新输入:"))
        if int(instruction) == 9:
            exit()  # TODO 退出前需要判断是否有正在执行的monkey任务和关键字监控任务
        eval(INSTRUCTION[str(instruction)] + "()")


if __name__ == '__main__':
    main()

The code is a bit messy after segmentation. If you don’t understand it, you can copy the code to a file and you will understand it

If you want to learn more about programming, please pay attentionphptrainingcolumn!

The above is the detailed content of Monitor python logcat keywords. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete