Created
October 26, 2025 12:38
-
-
Save PeterWaIIace/f4c05973bf9e0cbc0fc649b70d46dfc1 to your computer and use it in GitHub Desktop.
Python colorful traces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import inspect | |
| import threading | |
| # Some ANSI color codes | |
| COLORS = [ | |
| "\033[97m", # White | |
| "\033[91m", # Red | |
| "\033[92m", # Green | |
| "\033[93m", # Yellow | |
| "\033[94m", # Blue | |
| "\033[95m", # Magenta | |
| "\033[96m", # Cyan | |
| ] | |
| RESET = "\033[0m" | |
| threads_colors = {} | |
| def trace(func): | |
| def wrapper(*args, **kwargs): | |
| # Get the current thread info | |
| thread = threading.current_thread() | |
| thread_name = thread.name | |
| thread_id = threading.get_ident() | |
| if thread_id not in threads_colors.keys(): | |
| threads_colors[thread_id] = len(threads_colors.keys()) % len(COLORS) | |
| START_COLOR = COLORS[threads_colors[thread_id]] | |
| # Check if called as a method | |
| if args: | |
| possible_self = args[0] | |
| cls = None | |
| # Case 1: instance method | |
| if inspect.isclass(possible_self.__class__): | |
| cls = possible_self.__class__ | |
| # Case 2: class method | |
| elif inspect.isclass(possible_self): | |
| cls = possible_self | |
| if cls: | |
| print(f"{START_COLOR}[thread: {thread_id}] {cls.__name__}.{func.__name__} arguments {args[1:]} {RESET}") | |
| else: | |
| print(f"{START_COLOR}[thread: {thread_id}] {func.__name__} (not a method) {RESET}") | |
| else: | |
| print(f"{START_COLOR}[thread: {thread_id}] {func.__name__} (no args) {RESET}") | |
| return func(*args, **kwargs) | |
| return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment