Skip to content

Commit

Permalink
Merge PR #610
Browse files Browse the repository at this point in the history
  • Loading branch information
dainnilsson committed Apr 24, 2024
2 parents f761197 + e5eccc2 commit cfef084
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
3 changes: 2 additions & 1 deletion ykman/_cli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down Expand Up @@ -435,6 +435,7 @@ def main():
msg = "An unexpected error has occurred"
formatter.show_trace = True
logger.exception(msg)
logging.shutdown()
sys.exit(status)


Expand Down
25 changes: 19 additions & 6 deletions ykman/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
9 changes: 7 additions & 2 deletions ykman/logging_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from datetime import datetime
import platform
import logging
import warnings
import ctypes
import sys
import os
Expand All @@ -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)

0 comments on commit cfef084

Please sign in to comment.