Skip to content

Commit 6ae6c0b

Browse files
committed
add: adding excepthooks to instrumented program when --debug-mode is set
1 parent fda3aca commit 6ae6c0b

3 files changed

Lines changed: 24 additions & 3 deletions

File tree

mldaikon/collect_trace.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ def is_path_md_output_dir(output_dir: str) -> bool:
306306
"-d",
307307
"--debug-mode",
308308
action="store_true",
309-
help="Enable debug mode for the program",
309+
help="Enable debug mode for the program, insert an exception hook into the program to log the entire stack trace",
310310
)
311311

312312
## instrumentor configs

mldaikon/instrumentor/source_file.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,13 @@ def instrument_file(
442442
os.environ['ML_DAIKON_OUTPUT_DIR'] = "{output_dir}"
443443
"""
444444

445+
debug_hook_code = """
446+
from mldaikon.utils import register_custom_excepthook
447+
if os.environ.get("ML_DAIKON_DEBUG") == "1":
448+
print("ML_DAIKON_DEBUG is set to 1, registering custom excepthook")
449+
register_custom_excepthook(True)
450+
"""
451+
445452
# general config update
446453
general_config_update = f"""
447454
import mldaikon.config.config as general_config
@@ -469,7 +476,11 @@ def instrument_file(
469476
# HACK: this is a hack to attach the logging code to the instrumented source after the __future__ imports
470477
code_head, code_tail = get_code_head_and_tail(instrumented_source)
471478
instrumented_source = (
472-
code_head + logging_start_code + general_config_update + code_tail
479+
code_head
480+
+ logging_start_code
481+
+ debug_hook_code
482+
+ general_config_update
483+
+ code_tail
473484
)
474485

475486
return instrumented_source

mldaikon/utils.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,17 @@ def thread_excepthook(args):
103103
raise exc_type(exc_value) from None
104104

105105

106-
def register_custom_excepthook():
106+
def register_custom_excepthook(add_file_handler=False):
107+
if add_file_handler:
108+
file_handler = logging.FileHandler("debug.log")
109+
file_handler.setLevel(logging.DEBUG)
110+
formatter = logging.Formatter(
111+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
112+
)
113+
file_handler.setFormatter(formatter)
114+
# add to the "mldaikon" logger and the "threading" logger
115+
logging.getLogger("mldaikon").addHandler(file_handler)
116+
logging.getLogger("threading").addHandler(file_handler)
107117
sys.excepthook = handle_excepthook
108118
threading.excepthook = thread_excepthook
109119

0 commit comments

Comments
 (0)