Skip to content

Commit

Permalink
Reapply "android: forward all logs to adb logs"
Browse files Browse the repository at this point in the history
This reverts commit 01857d7.
  • Loading branch information
uael committed Nov 28, 2023
1 parent 04e51f4 commit 62d6e59
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions avatar/pandora_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@
import avatar.aio
import grpc
import grpc.aio
import logging
import os
import portpicker
import re
import shlex
import threading
import types

Expand Down Expand Up @@ -112,6 +116,8 @@ class AndroidPandoraServer(PandoraServer[AndroidDevice]):

_instrumentation: Optional[threading.Thread] = None
_port: int
_logger: logging.Logger
_handler: logging.Handler

def start(self) -> PandoraClient:
"""Sets up and starts the Pandora server on the Android device."""
Expand All @@ -132,6 +138,31 @@ def start(self) -> PandoraClient:
self._instrumentation.start()
self.device.adb.forward([f'tcp:{self._port}', f'tcp:{ANDROID_SERVER_GRPC_PORT}']) # type: ignore

# Forward all logging to ADB logs
adb = self.device.adb

class AdbLoggingHandler(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
if record.levelno <= logging.DEBUG:
return
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
msg = self.format(record)
msg = ansi_escape.sub('', msg)
level = {
logging.FATAL: 'f',
logging.ERROR: 'e',
logging.WARN: 'w',
logging.INFO: 'i',
logging.DEBUG: 'd',
logging.NOTSET: 'd',
}[record.levelno]
for msg in msg.splitlines():
os.system(f'adb -s {adb.serial} shell "log -t Avatar -p {level} {shlex.quote(msg)}"')

self._logger = logging.getLogger()
self._handler = AdbLoggingHandler()
self._logger.addHandler(self._handler)

return PandoraClient(f'localhost:{self._port}', 'android')

def stop(self) -> None:
Expand All @@ -143,6 +174,9 @@ def stop(self) -> None:
'shell', f'am force-stop {ANDROID_SERVER_PACKAGE}', shell=False, timeout=None, stderr=None
)

# Remove ADB logging handler
self._logger.removeHandler(self._handler)

self.device.adb.forward(['--remove', f'tcp:{self._port}']) # type: ignore
self._instrumentation.join()
self._instrumentation = None

0 comments on commit 62d6e59

Please sign in to comment.