|
| 1 | +import io |
| 2 | +import sys |
| 3 | + |
| 4 | + |
| 5 | +# The maximum length of a log message in bytes, including the level marker and |
| 6 | +# tag, is defined as LOGGER_ENTRY_MAX_PAYLOAD in |
| 7 | +# platform/system/logging/liblog/include/log/log.h. As of API level 30, messages |
| 8 | +# longer than this will be be truncated by logcat. This limit has already been |
| 9 | +# reduced at least once in the history of Android (from 4076 to 4068 between API |
| 10 | +# level 23 and 26), so leave some headroom. |
| 11 | +MAX_BYTES_PER_WRITE = 4000 |
| 12 | + |
| 13 | +# UTF-8 uses a maximum of 4 bytes per character, so limiting text writes to this |
| 14 | +# size ensures that TextIOWrapper can always avoid exceeding MAX_BYTES_PER_WRITE. |
| 15 | +# However, if the actual number of bytes per character is smaller than that, |
| 16 | +# then TextIOWrapper may still join multiple consecutive text writes into binary |
| 17 | +# writes containing a larger number of characters. |
| 18 | +MAX_CHARS_PER_WRITE = MAX_BYTES_PER_WRITE // 4 |
| 19 | + |
| 20 | + |
| 21 | +# When embedded in an app on current versions of Android, there's no easy way to |
| 22 | +# monitor the C-level stdout and stderr. The testbed comes with a .c file to |
| 23 | +# redirect them to the system log using a pipe, but that wouldn't be convenient |
| 24 | +# or appropriate for all apps. So we redirect at the Python level instead. |
| 25 | +def init_streams(android_log_write, stdout_prio, stderr_prio): |
| 26 | + if sys.executable: |
| 27 | + return # Not embedded in an app. |
| 28 | + |
| 29 | + sys.stdout = TextLogStream( |
| 30 | + android_log_write, stdout_prio, "python.stdout", errors=sys.stdout.errors) |
| 31 | + sys.stderr = TextLogStream( |
| 32 | + android_log_write, stderr_prio, "python.stderr", errors=sys.stderr.errors) |
| 33 | + |
| 34 | + |
| 35 | +class TextLogStream(io.TextIOWrapper): |
| 36 | + def __init__(self, android_log_write, prio, tag, **kwargs): |
| 37 | + kwargs.setdefault("encoding", "UTF-8") |
| 38 | + kwargs.setdefault("line_buffering", True) |
| 39 | + super().__init__(BinaryLogStream(android_log_write, prio, tag), **kwargs) |
| 40 | + self._CHUNK_SIZE = MAX_BYTES_PER_WRITE |
| 41 | + |
| 42 | + def __repr__(self): |
| 43 | + return f"<TextLogStream {self.buffer.tag!r}>" |
| 44 | + |
| 45 | + def write(self, s): |
| 46 | + if not isinstance(s, str): |
| 47 | + raise TypeError( |
| 48 | + f"write() argument must be str, not {type(s).__name__}") |
| 49 | + |
| 50 | + # In case `s` is a str subclass that writes itself to stdout or stderr |
| 51 | + # when we call its methods, convert it to an actual str. |
| 52 | + s = str.__str__(s) |
| 53 | + |
| 54 | + # We want to emit one log message per line wherever possible, so split |
| 55 | + # the string before sending it to the superclass. Note that |
| 56 | + # "".splitlines() == [], so nothing will be logged for an empty string. |
| 57 | + for line in s.splitlines(keepends=True): |
| 58 | + while line: |
| 59 | + super().write(line[:MAX_CHARS_PER_WRITE]) |
| 60 | + line = line[MAX_CHARS_PER_WRITE:] |
| 61 | + |
| 62 | + return len(s) |
| 63 | + |
| 64 | + |
| 65 | +class BinaryLogStream(io.RawIOBase): |
| 66 | + def __init__(self, android_log_write, prio, tag): |
| 67 | + self.android_log_write = android_log_write |
| 68 | + self.prio = prio |
| 69 | + self.tag = tag |
| 70 | + |
| 71 | + def __repr__(self): |
| 72 | + return f"<BinaryLogStream {self.tag!r}>" |
| 73 | + |
| 74 | + def writable(self): |
| 75 | + return True |
| 76 | + |
| 77 | + def write(self, b): |
| 78 | + if type(b) is not bytes: |
| 79 | + try: |
| 80 | + b = bytes(memoryview(b)) |
| 81 | + except TypeError: |
| 82 | + raise TypeError( |
| 83 | + f"write() argument must be bytes-like, not {type(b).__name__}" |
| 84 | + ) from None |
| 85 | + |
| 86 | + # Writing an empty string to the stream should have no effect. |
| 87 | + if b: |
| 88 | + # Encode null bytes using "modified UTF-8" to avoid truncating the |
| 89 | + # message. This should not affect the return value, as the caller |
| 90 | + # may be expecting it to match the length of the input. |
| 91 | + self.android_log_write(self.prio, self.tag, |
| 92 | + b.replace(b"\x00", b"\xc0\x80")) |
| 93 | + |
| 94 | + return len(b) |
0 commit comments