安卓 logcat 通过一个 websocket 来进行传输;
websocket 基于 socketio 实现
@socketio.on('connect', namespace='/logcat') | |
def connect(): | |
socketio.emit('start connect', {'data': 'Connected'}, namespace='/logcat') | |
logDir = os.path.join(os.getcwd(),'adblog') | |
if not os.path.exists(logDir): | |
os.mkdir(logDir) | |
global thread | |
thread = True | |
with thread_lock: | |
if thread: | |
thread = socketio.start_background_task(target=backgroundThread) |
通过 adb 命令拿到 logcat 日志,输出到本地文件中,然后再从文件中读取日志,通过 websocket 传输
def backgroundThread(): | |
global thread | |
try: | |
# logger.info('Initializing adb environment ...') | |
# os.system('adb kill-server') | |
# os.system('adb start-server') | |
current_time = time.strftime("%Y%m%d%H", time.localtime()) | |
logPath = os.path.join(os.getcwd(),'adblog',f'{current_time}.log') | |
logcat = subprocess.Popen(f'adb logcat *:E > {logPath}', stdout=subprocess.PIPE, | |
shell=True) | |
with open(logPath, "r") as f: | |
while thread: | |
socketio.sleep(1) | |
for line in f.readlines(): | |
socketio.emit('message', {'data': line}, namespace='/logcat') | |
if logcat.poll() == 0: | |
thread = False | |
except Exception: | |
pass |