diff --git a/ykman/_cli/__main__.py b/ykman/_cli/__main__.py index 66951d72..d89f40db 100644 --- a/ykman/_cli/__main__.py +++ b/ykman/_cli/__main__.py @@ -272,7 +272,7 @@ def cli(ctx, device, log_level, log_file, reader): ctx.obj = YkmanContextObject() if log_level: - init_logging(log_level, log_file=log_file) + init_logging(log_level, log_file=log_file, replace=log_file is None) logger.info("\n".join(pretty_print({"System info": sys_info()}))) elif log_file: ctx.fail("--log-file requires specifying --log-level.") @@ -435,6 +435,7 @@ def main(): msg = "An unexpected error has occurred" formatter.show_trace = True logger.exception(msg) + logging.shutdown() sys.exit(status) diff --git a/ykman/logging.py b/ykman/logging.py index 481da3e4..81cbeeac 100644 --- a/ykman/logging.py +++ b/ykman/logging.py @@ -64,13 +64,26 @@ def set_log_level(level: LOG_LEVEL): logger.warning(_print_box(*DEBUG_WARNING)) -def init_logging(log_level: LOG_LEVEL, log_file=None): - logging.basicConfig( - force=log_file is None, # Replace the default logger if logging to stderr - datefmt="%H:%M:%S", - filename=log_file, - format="%(levelname)s %(asctime)s.%(msecs)d [%(name)s.%(funcName)s:%(lineno)d] " +def init_logging(log_level: LOG_LEVEL, log_file=None, replace=False): + formatter = logging.Formatter( + "%(levelname)s %(asctime)s.%(msecs)d [%(name)s.%(funcName)s:%(lineno)d] " "%(message)s", + "%H:%M:%S", + "%", ) + if log_file: + handler: logging.Handler = logging.FileHandler(log_file) + else: + handler = logging.StreamHandler() + handler.setFormatter(formatter) + root = logging.getLogger() + if replace: + for h in root.handlers[:]: + root.removeHandler(h) + + root.addHandler(handler) set_log_level(log_level) + + if log_file: + logger.warning(f"Logging to file: {log_file}") diff --git a/ykman/logging_setup.py b/ykman/logging_setup.py index ad01147e..941c9b52 100644 --- a/ykman/logging_setup.py +++ b/ykman/logging_setup.py @@ -32,6 +32,7 @@ from datetime import datetime import platform import logging +import warnings import ctypes import sys import os @@ -55,7 +56,11 @@ def log_sys_info(log): def setup(log_level_name, log_file=None): - log_level = LOG_LEVEL[log_level_name.upper()] - init_logging(log_level, log_file=log_file) + warnings.warn( + "logging_setup.setup is deprecated, use logging.init_loging instead", + DeprecationWarning, + ) + log_level = LOG_LEVEL[log_level_name.upper()] + init_logging(log_level, log_file=log_file, replace=log_file is None) log_sys_info(logger.debug)