控制台下adb的打印出彩色的log

468 阅读1分钟

本文目的:为了安卓开发者能在控制台中查看彩色的logcat
为了方便调试/查看非as工程的应用的/framework的日志,我用python开发了一个小脚本,在此开源,共享给大家。

运行结果

image.png

常见命令

指定等级

py logcat.py -level=E

指定tag

py logcat.py -tag=TAG

image.png

指定grep内容

py logcat.py -grep=content image.png

使用帮助

py logcat.py -h image.png

源码

import subprocess
import re
import sys
import argparse

# 用于设置颜色的ANSI转义序列
COLOR_RED = '\033[91m'
COLOR_YELLOW = '\033[93m'
COLOR_WHITE = '\033[97m'
COLOR_GREEN = '\033[92m'
COLOR_RESET = '\033[0m'


# 获取&解析命令行参数
parser = argparse.ArgumentParser(description='Logcat Filter',add_help=True)
parser.add_argument('-level', default='D', choices=['E', 'W', 'I', 'D'], help='Log level (E, W, I, D)')
parser.add_argument('-tag', default='', help='Tag to filter')
parser.add_argument('-grep', default='', help='Content to filter with regex')
parser.add_argument('-clear', choices=['y','n','yes','no'],default='n',help='clear logcat')
args = parser.parse_args()
level = args.level
tag = args.tag
grep_content = args.grep
clear = args.clear

if clear == 'yes' or clear == 'y':
    command = 'adb shell logcat -c'
    result = subprocess.run(command, capture_output=True, text=True, shell=True)

# 执行命令
command = 'adb shell logcat'
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)


def getLevelInt(level) -> int:
    if level == 'E':
        return 3
    elif level == 'W':
        return 2
    elif level == 'I':
        return 1
    else:
        return 0

def find_index_using_index(arr, target):
    try:
        index = arr.index(target)
        return index
    except ValueError:
        return None

need_level_int = getLevelInt(level)

for line in process.stdout:
    try:
        the_line = line.decode('utf-8')
        level_match = the_line[31:32]
        level_int = getLevelInt(level_match)
        if level_int < need_level_int :
            continue
        the_tag_and_content = the_line[32:]
        commonIndex = find_index_using_index(the_tag_and_content, ":")
        tag_match = the_tag_and_content[0:commonIndex]
        content_match = ''
        if commonIndex is not None:
            content_match = the_tag_and_content[commonIndex + 1:]
        if tag and not re.search(tag, tag_match):
            continue
        if grep_content and not re.search(grep_content, content_match):
            continue
        # 根据level设置颜色
        if level_match == 'E':
            content_match = COLOR_RED + content_match + COLOR_RESET
        elif level_match == 'W':
            content_match = COLOR_YELLOW + content_match + COLOR_RESET
        elif level_match == 'I':
            content_match = COLOR_WHITE + content_match + COLOR_RESET
        elif level_match == 'D':
            content_match = COLOR_GREEN + content_match + COLOR_RESET
        print(tag_match,':',content_match,end='')
    except UnicodeDecodeError:
        print(line.decode('utf-8', errors='ignore'),end='')

# 等待命令执行完成
process.wait()