helpers: logging: get rid of context and args (MR 2252)

Signed-off-by: Caleb Connolly <caleb@postmarketos.org>
This commit is contained in:
Caleb Connolly 2024-06-13 08:04:23 +02:00 committed by Oliver Smith
parent 29eb4e950e
commit 25e41ff3f7
No known key found for this signature in database
GPG key ID: 5AE7F5513E0885CB
2 changed files with 20 additions and 22 deletions

View file

@ -94,7 +94,7 @@ def init(args: PmbArgs) -> PmbArgs:
pmb.core.context.set_context(context) pmb.core.context.set_context(context)
# Initialize logs (we could raise errors below) # Initialize logs (we could raise errors below)
pmb.helpers.logging.init(args) pmb.helpers.logging.init(context.log, args.verbose, context.details_to_stdout)
# Initialization code which may raise errors # Initialization code which may raise errors
if args.action not in ["init", "checksum", "config", "bootimg_analyze", "log", if args.action not in ["init", "checksum", "config", "bootimg_analyze", "log",

View file

@ -2,11 +2,10 @@
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
import logging import logging
import os import os
from pathlib import Path
import sys import sys
from typing import TextIO from typing import TextIO
import pmb.config import pmb.config
from pmb.core.context import Context, get_context
from pmb.types import PmbArgs
logfd: TextIO logfd: TextIO
@ -22,19 +21,19 @@ VERBOSE = 5
class log_handler(logging.StreamHandler): class log_handler(logging.StreamHandler):
"""Write to stdout and to the already opened log file.""" """Write to stdout and to the already opened log file."""
context: Context
def __init__(self): def __init__(self, details_to_stdout: bool=False, quiet: bool=False):
super().__init__() super().__init__()
self.context = get_context() self.details_to_stdout = False
self.quiet = False
def emit(self, record): def emit(self, record):
try: try:
msg = self.format(record) msg = self.format(record)
# INFO or higher: Write to stdout # INFO or higher: Write to stdout
if (not self.context.details_to_stdout and if (not self.details_to_stdout and
not self.context.quiet and not self.quiet and
record.levelno >= logging.INFO): record.levelno >= logging.INFO):
stream = self.stream stream = self.stream
@ -124,27 +123,27 @@ def add_verbose_log_level():
**kwargs)) **kwargs))
def init(args: PmbArgs): def init(logfile: Path, verbose: bool, details_to_stdout: bool=False):
"""Set log format and add the log file descriptor to logfd, add the verbose log level.""" """Set log format and add the log file descriptor to logfd, add the verbose log level."""
global logfd global logfd
context = get_context()
if "logfs" in globals():
warning("Logging already initialized, skipping...")
return
# Set log file descriptor (logfd) # Set log file descriptor (logfd)
if context.details_to_stdout: if details_to_stdout:
logfd = sys.stdout logfd = sys.stdout
else: else:
# Require containing directory to exist (so we don't create the work # Require containing directory to exist (so we don't create the work
# folder and break the folder migration logic, which needs to set the # folder and break the folder migration logic, which needs to set the
# version upon creation) # version upon creation)
dir = os.path.dirname(context.log) dir = os.path.dirname(logfile)
if os.path.exists(dir): if os.path.exists(dir):
logfd = open(context.log, "a+") logfd = open(logfile, "a+")
logfd.write("\n\n") logfd.write("\n\n")
else: else:
logfd = open(os.devnull, "a+") logfd = open(os.devnull, "a+")
# FIXME: what? surely this check shouldn't be needed!
if args.action != "init":
print(f"WARNING: Can't create log file in '{dir}', path"
" does not exist!")
# Set log format # Set log format
root_logger = logging.getLogger() root_logger = logging.getLogger()
@ -155,18 +154,17 @@ def init(args: PmbArgs):
# Set log level # Set log level
add_verbose_log_level() add_verbose_log_level()
root_logger.setLevel(logging.DEBUG) root_logger.setLevel(logging.DEBUG)
if args.verbose: if verbose:
root_logger.setLevel(VERBOSE) root_logger.setLevel(VERBOSE)
# Add a custom log handler # Add a custom log handler
handler = log_handler() handler = log_handler(details_to_stdout=details_to_stdout)
handler.setFormatter(formatter) handler.setFormatter(formatter)
root_logger.addHandler(handler) root_logger.addHandler(handler)
logging.debug(f"Pmbootstrap v{pmb.__version__} (Python {sys.version})") logging.debug(f"Pmbootstrap v{pmb.__version__} (Python {sys.version})")
safe_args = ' '.join(sys.argv[1:]) if "--password" in sys.argv:
if "password" in args: sys.argv[sys.argv.index("--password")+1] = "[REDACTED]"
safe_args = safe_args.replace(args.password, "[REDACTED]")
logging.debug(f"$ pmbootstrap {' '.join(sys.argv)}") logging.debug(f"$ pmbootstrap {' '.join(sys.argv)}")