diff --git a/codebasin/__main__.py b/codebasin/__main__.py index 8f8e324..7cb04b5 100755 --- a/codebasin/__main__.py +++ b/codebasin/__main__.py @@ -16,6 +16,8 @@ log = logging.getLogger("codebasin") version = "1.2.0" +_traceback = False + def _help_string(*lines: str, is_long=False, is_last=False): """ @@ -89,6 +91,14 @@ def _main(): default=0, help=_help_string("Decrease verbosity level."), ) + parser.add_argument( + "--debug", + dest="debug", + action="store_const", + default=False, + const=True, + help=_help_string("Enable debug output."), + ) parser.add_argument( "-R", "--report", @@ -152,23 +162,35 @@ def _main(): # Configure logging such that: # - All messages are written to a log file # - Only errors are written to the terminal by default - # - Messages written to terminal are based on -q and -v flags + # - Messages written to terminal are based on -q, -v and --debug flags # - Meta-warnings and statistics are generated by a WarningAggregator aggregator = WarningAggregator() log.setLevel(logging.DEBUG) + if args.debug: + min_log_level = logging.DEBUG + global _traceback + _traceback = True + else: + min_log_level = logging.INFO file_handler = logging.FileHandler("cbi.log", mode="w") - file_handler.setLevel(logging.INFO) + file_handler.setLevel(min_log_level) file_handler.setFormatter(Formatter()) file_handler.addFilter(aggregator) log.addHandler(file_handler) + if args.debug: + log.debug(f"Code Base Investigator {version}; Python {sys.version}") + # Inform the user that a log file has been created. # 'print' instead of 'log' to ensure the message is visible in the output. log_path = os.path.abspath("cbi.log") print(f"Log file created at {log_path}") - log_level = max(1, logging.ERROR - 10 * (args.verbose - args.quiet)) + log_level = max( + min_log_level, + logging.ERROR - 10 * (args.verbose - args.quiet), + ) stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(log_level) stdout_handler.setFormatter(Formatter(colors=sys.stdout.isatty())) @@ -270,7 +292,7 @@ def main(): try: _main() except Exception as e: - log.error(str(e)) + log.error(str(e), exc_info=_traceback) sys.exit(1) diff --git a/codebasin/_detail/logging.py b/codebasin/_detail/logging.py index 9500f86..9559180 100644 --- a/codebasin/_detail/logging.py +++ b/codebasin/_detail/logging.py @@ -61,6 +61,11 @@ def format(self, record: logging.LogRecord) -> str: color = RED else: color = DEFAULT + + # Print a stack trace if explicitly requested. + if record.exc_info: + return self.formatException(record.exc_info) + return f"{BOLD}{color}{level}{RESET}: {msg}"