DASP trace: sent lines yellow, received green on a console
Plain text when stdout is a pipe or file. Also remembers localhost as the last device. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -98,7 +98,43 @@ def _trace(direction, msg, datagram=None):
|
||||
hexdump = ""
|
||||
if datagram:
|
||||
hexdump = " [" + datagram.hex(" ") + "]"
|
||||
_trace_out(f"[DASP] {ts} {direction} {name}{seq}{ack} payload={plen}{hexdump}")
|
||||
line = f"[DASP] {ts} {direction} {name}{seq}{ack} payload={plen}{hexdump}"
|
||||
color = _TRACE_COLORS.get(direction)
|
||||
if color and _console_colors():
|
||||
line = f"{color}{line}\033[0m"
|
||||
_trace_out(line)
|
||||
|
||||
|
||||
# Sent lines yellow, received lines green, so the two directions read apart at a glance.
|
||||
_TRACE_COLORS = {"S": "\033[93m", "R": "\033[92m"}
|
||||
_colors_ok = None
|
||||
|
||||
|
||||
def _console_colors():
|
||||
"""True when stdout is a console that understands ANSI colour codes.
|
||||
|
||||
Windows consoles need virtual-terminal processing switched on first; a pipe or
|
||||
file gets plain text so captured logs stay free of escape codes.
|
||||
"""
|
||||
global _colors_ok
|
||||
if _colors_ok is None:
|
||||
import sys
|
||||
stream = sys.__stdout__
|
||||
try:
|
||||
_colors_ok = stream is not None and stream.isatty()
|
||||
except (OSError, ValueError):
|
||||
_colors_ok = False
|
||||
if _colors_ok and os.name == "nt":
|
||||
try:
|
||||
import ctypes
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
|
||||
mode = ctypes.c_uint32()
|
||||
_colors_ok = bool(kernel32.GetConsoleMode(handle, ctypes.byref(mode))
|
||||
and kernel32.SetConsoleMode(handle, mode.value | 0x0004))
|
||||
except (OSError, AttributeError):
|
||||
_colors_ok = False
|
||||
return _colors_ok
|
||||
|
||||
|
||||
# Trace lines are printed by a thread of their own. The send and receive threads must
|
||||
|
||||
Reference in New Issue
Block a user