Skip to content

Commit 0fdc694

Browse files
committed
Make it easy to monkey-patch length of frames repr.
Fix #1451.
1 parent 2774fab commit 0fdc694

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

src/websockets/frames.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,9 @@ class Frame:
146146
rsv2: bool = False
147147
rsv3: bool = False
148148

149+
# Monkey-patch if you want to see more in logs. Should be a multiple of 3.
150+
MAX_LOG = 75
151+
149152
def __str__(self) -> str:
150153
"""
151154
Return a human-readable representation of a frame.
@@ -163,8 +166,9 @@ def __str__(self) -> str:
163166
# We'll show at most the first 16 bytes and the last 8 bytes.
164167
# Encode just what we need, plus two dummy bytes to elide later.
165168
binary = self.data
166-
if len(binary) > 25:
167-
binary = b"".join([binary[:16], b"\x00\x00", binary[-8:]])
169+
if len(binary) > self.MAX_LOG // 3:
170+
cut = (self.MAX_LOG // 3 - 1) // 3 # by default cut = 8
171+
binary = b"".join([binary[: 2 * cut], b"\x00\x00", binary[-cut:]])
168172
data = " ".join(f"{byte:02x}" for byte in binary)
169173
elif self.opcode is OP_CLOSE:
170174
data = str(Close.parse(self.data))
@@ -179,15 +183,17 @@ def __str__(self) -> str:
179183
coding = "text"
180184
except (UnicodeDecodeError, AttributeError):
181185
binary = self.data
182-
if len(binary) > 25:
183-
binary = b"".join([binary[:16], b"\x00\x00", binary[-8:]])
186+
if len(binary) > self.MAX_LOG // 3:
187+
cut = (self.MAX_LOG // 3 - 1) // 3 # by default cut = 8
188+
binary = b"".join([binary[: 2 * cut], b"\x00\x00", binary[-cut:]])
184189
data = " ".join(f"{byte:02x}" for byte in binary)
185190
coding = "binary"
186191
else:
187192
data = "''"
188193

189-
if len(data) > 75:
190-
data = data[:48] + "..." + data[-24:]
194+
if len(data) > self.MAX_LOG:
195+
cut = self.MAX_LOG // 3 - 1 # by default cut = 24
196+
data = data[: 2 * cut] + "..." + data[-cut:]
191197

192198
metadata = ", ".join(filter(None, [coding, length, non_final]))
193199

0 commit comments

Comments
 (0)