diff --git a/lib/apt_news.py b/lib/apt_news.py index a61e0336d8..b043dbb88c 100644 --- a/lib/apt_news.py +++ b/lib/apt_news.py @@ -8,7 +8,7 @@ from uaclient.config import UAConfig from uaclient.daemon import setup_logging -uaclient_logger = logging.getLogger("uaclient") +upro_logger = logging.getLogger("ubuntu_pro") def main(cfg: UAConfig): @@ -28,13 +28,13 @@ def main(cfg: UAConfig): logging.INFO, logging.DEBUG, defaults.CONFIG_DEFAULTS["log_file"], - logger=uaclient_logger, + logger=upro_logger, ) cfg = UAConfig() setup_logging( logging.INFO, logging.DEBUG, log_file=cfg.log_file, - logger=uaclient_logger, + logger=upro_logger, ) main(cfg) diff --git a/lib/auto_attach.py b/lib/auto_attach.py index d8405d8e51..7e57a6ab80 100644 --- a/lib/auto_attach.py +++ b/lib/auto_attach.py @@ -31,8 +31,8 @@ ) from uaclient.files import state_files -uaclient_logger = logging.getLogger("uaclient") -LOG = logging.getLogger("uaclient.lib.auto_attach") +upro_logger = logging.getLogger("ubuntu_pro") +LOG = logging.getLogger("ubuntu_pro.lib.auto_attach") try: import cloudinit.stages as ci_stages # type: ignore @@ -108,13 +108,13 @@ def main(cfg: UAConfig): logging.INFO, logging.DEBUG, defaults.CONFIG_DEFAULTS["log_file"], - logger=uaclient_logger, + logger=upro_logger, ) cfg = UAConfig() setup_logging( logging.INFO, logging.DEBUG, log_file=cfg.log_file, - logger=uaclient_logger, + logger=upro_logger, ) sys.exit(main(cfg)) diff --git a/lib/daemon.py b/lib/daemon.py index fd181395ce..ecbacf9c5b 100644 --- a/lib/daemon.py +++ b/lib/daemon.py @@ -12,8 +12,8 @@ setup_logging, ) -LOG = logging.getLogger("uaclient.lib.daemon") -uaclient_logger = logging.getLogger("uaclient") +LOG = logging.getLogger("ubuntu_pro.lib.daemon") +upro_logger = logging.getLogger("ubuntu_pro") def main() -> int: @@ -36,7 +36,7 @@ def main() -> int: logging.CRITICAL, logging.ERROR, log_file=cfg.daemon_log_file, - logger=uaclient_logger, + logger=upro_logger, ) LOG.debug("daemon starting") diff --git a/lib/esm_cache.py b/lib/esm_cache.py index 62f3e16e52..5d770ef497 100755 --- a/lib/esm_cache.py +++ b/lib/esm_cache.py @@ -7,8 +7,8 @@ from uaclient.config import UAConfig from uaclient.daemon import setup_logging -LOG = logging.getLogger("uaclient.lib.esm_cache") -uaclient_logger = logging.getLogger("uaclient") +LOG = logging.getLogger("ubuntu_pro.lib.esm_cache") +upro_logger = logging.getLogger("ubuntu_pro") def main(cfg: UAConfig) -> None: @@ -24,13 +24,13 @@ def main(cfg: UAConfig) -> None: logging.INFO, logging.DEBUG, defaults.CONFIG_DEFAULTS["log_file"], - logger=uaclient_logger, + logger=upro_logger, ) cfg = UAConfig() setup_logging( logging.INFO, logging.DEBUG, log_file=cfg.log_file, - logger=uaclient_logger, + logger=upro_logger, ) main(cfg) diff --git a/lib/patch_status_json.py b/lib/patch_status_json.py index fc33100d61..96f6047916 100755 --- a/lib/patch_status_json.py +++ b/lib/patch_status_json.py @@ -21,7 +21,7 @@ from uaclient import system, util from uaclient.cli import setup_logging -LOG = logging.getLogger("uaclient.lib.patch_status_json") +LOG = logging.getLogger("ubuntu_pro.lib.patch_status_json") def patch_status_json_schema_0_1(status_file: str): diff --git a/lib/reboot_cmds.py b/lib/reboot_cmds.py index 3f582c3f35..505ff17231 100644 --- a/lib/reboot_cmds.py +++ b/lib/reboot_cmds.py @@ -31,7 +31,7 @@ from uaclient.entitlements.fips import FIPSEntitlement from uaclient.files import notices, state_files -LOG = logging.getLogger("uaclient.lib.reboot_cmds") +LOG = logging.getLogger("ubuntu_pro.lib.reboot_cmds") def fix_pro_pkg_holds(cfg: config.UAConfig): diff --git a/lib/timer.py b/lib/timer.py index 27163a4b69..a5246018bc 100644 --- a/lib/timer.py +++ b/lib/timer.py @@ -19,7 +19,7 @@ from uaclient.timer.update_contract_info import update_contract_info from uaclient.timer.update_messaging import update_motd_messages -LOG = logging.getLogger("uaclient.lib.timer") +LOG = logging.getLogger("ubuntu_pro.lib.timer") UPDATE_MESSAGING_INTERVAL = 21600 # 6 hours METERING_INTERVAL = 14400 # 4 hours UPDATE_CONTRACT_INFO_INTERVAL = 86400 # 24 hours diff --git a/uaclient/actions.py b/uaclient/actions.py index dad69b5b1d..e25a1c8633 100644 --- a/uaclient/actions.py +++ b/uaclient/actions.py @@ -24,7 +24,7 @@ ) from uaclient.files.state_files import timer_jobs_state_file -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(pro_log.replace_top_level_logger_name(__name__)) UA_SERVICES = ( @@ -231,7 +231,7 @@ def collect_logs(cfg: config.UAConfig, output_dir: str): content, ) except Exception as e: - logging.warning( + LOG.warning( "Failed to collect user log file: %s\n%s", log_file, str(e) ) diff --git a/uaclient/api/__init__.py b/uaclient/api/__init__.py index 108e48add1..9f5b4536db 100644 --- a/uaclient/api/__init__.py +++ b/uaclient/api/__init__.py @@ -1,4 +1,4 @@ import logging # setup null handler for all API endpoints -logging.getLogger("uaclient").addHandler(logging.NullHandler()) +logging.getLogger("ubuntu_pro").addHandler(logging.NullHandler()) diff --git a/uaclient/apt.py b/uaclient/apt.py index f7aa3e0360..ed89630952 100644 --- a/uaclient/apt.py +++ b/uaclient/apt.py @@ -14,7 +14,7 @@ import apt # type: ignore import apt_pkg # type: ignore -from uaclient import event_logger, exceptions, gpg, messages, system +from uaclient import event_logger, exceptions, gpg, log, messages, system from uaclient.defaults import ESM_APT_ROOTDIR APT_HELPER_TIMEOUT = 60.0 # 60 second timeout used for apt-helper call @@ -56,7 +56,7 @@ APT_RETRIES = [1.0, 5.0, 10.0] event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) @enum.unique diff --git a/uaclient/apt_news.py b/uaclient/apt_news.py index 052d2cf924..d2bf9d3f87 100644 --- a/uaclient/apt_news.py +++ b/uaclient/apt_news.py @@ -7,7 +7,7 @@ import apt_pkg -from uaclient import defaults, messages, system, util +from uaclient import defaults, log, messages, system, util from uaclient.api.u.pro.status.is_attached.v1 import _is_attached from uaclient.clouds.identity import get_cloud_type from uaclient.config import UAConfig @@ -25,7 +25,7 @@ get_contract_expiry_status, ) -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) class AptNewsMessageSelectors(DataObject): diff --git a/uaclient/cli.py b/uaclient/cli.py index ac98f61d17..05f9f6b019 100644 --- a/uaclient/cli.py +++ b/uaclient/cli.py @@ -100,8 +100,8 @@ ) event = event_logger.get_event_logger() -uaclient_logger = logging.getLogger("uaclient") -LOG = logging.getLogger(__name__) +upro_logger = logging.getLogger("ubuntu_pro") +LOG = logging.getLogger(pro_log.replace_top_level_logger_name(__name__)) class UAArgumentParser(argparse.ArgumentParser): @@ -1876,7 +1876,7 @@ def _warn_about_output_redirection(cmd_args) -> None: ): if hasattr(cmd_args, "format") and cmd_args.format in ("json", "yaml"): return - logging.warning( + LOG.warning( messages.WARNING_HUMAN_READABLE_OUTPUT.format( command=cmd_args.command ) @@ -1901,18 +1901,18 @@ def setup_logging(console_level, log_level, log_file=None, logger=None): log_level = log_level.upper() console_formatter = util.LogFormatter() - uaclient_logger.setLevel(log_level) - uaclient_logger.addFilter(pro_log.RedactionFilter()) + upro_logger.setLevel(log_level) + upro_logger.addFilter(pro_log.RedactionFilter()) # Clear all handlers, so they are replaced for this logger - uaclient_logger.handlers = [] + upro_logger.handlers = [] # Setup console logging console_handler = logging.StreamHandler(sys.stderr) console_handler.setFormatter(console_formatter) console_handler.setLevel(console_level) - console_handler.set_name("ua-console") # Used to disable console logging - uaclient_logger.addHandler(console_handler) + console_handler.set_name("upro-console") # Used to disable console logging + upro_logger.addHandler(console_handler) log_file_path = pathlib.Path(log_file) @@ -1924,8 +1924,8 @@ def setup_logging(console_level, log_level, log_file=None, logger=None): file_handler = logging.FileHandler(log_file) file_handler.setFormatter(JsonArrayFormatter()) file_handler.setLevel(log_level) - file_handler.set_name("ua-file") - uaclient_logger.addHandler(file_handler) + file_handler.set_name("upro-file") + upro_logger.addHandler(file_handler) def set_event_mode(cmd_args): diff --git a/uaclient/clouds/aws.py b/uaclient/clouds/aws.py index b1c6682c8f..6dba586359 100644 --- a/uaclient/clouds/aws.py +++ b/uaclient/clouds/aws.py @@ -1,7 +1,7 @@ import logging from typing import Any, Dict -from uaclient import exceptions, http, system, util +from uaclient import exceptions, http, log, system, util from uaclient.clouds import AutoAttachCloudInstance IMDS_IPV4_ADDRESS = "169.254.169.254" @@ -19,7 +19,7 @@ AWS_TOKEN_PUT_HEADER = "X-aws-ec2-metadata-token" AWS_TOKEN_REQ_HEADER = AWS_TOKEN_PUT_HEADER + "-ttl-seconds" -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) class UAAutoAttachAWSInstance(AutoAttachCloudInstance): diff --git a/uaclient/clouds/identity.py b/uaclient/clouds/identity.py index 3f6bdc5ac8..ada07da69c 100644 --- a/uaclient/clouds/identity.py +++ b/uaclient/clouds/identity.py @@ -3,10 +3,10 @@ from functools import lru_cache from typing import Dict, Optional, Tuple, Type # noqa: F401 -from uaclient import clouds, exceptions, system +from uaclient import clouds, exceptions, log, system from uaclient.config import apply_config_settings_override -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) CLOUD_TYPE_TO_TITLE = { "aws": "AWS", diff --git a/uaclient/config.py b/uaclient/config.py index 51e36b28a9..97f04e1d90 100644 --- a/uaclient/config.py +++ b/uaclient/config.py @@ -12,6 +12,7 @@ exceptions, files, http, + log, messages, snap, system, @@ -31,7 +32,7 @@ from uaclient.files.notices import Notice from uaclient.yaml import safe_load -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) PRIVATE_SUBDIR = "private" MERGE_ID_KEY_MAP = { diff --git a/uaclient/conftest.py b/uaclient/conftest.py index ab41611a63..52377fab4b 100644 --- a/uaclient/conftest.py +++ b/uaclient/conftest.py @@ -108,7 +108,7 @@ def _func(): except LookupError: # If the caplog fixture isn't available, shim something in ourselves - root = logging.getLogger("uaclient") + root = logging.getLogger("ubuntu_pro") root.propagate = False root.setLevel(log_level) handler = logging.StreamHandler(io.StringIO()) @@ -135,13 +135,13 @@ def clear_handlers(): def logging_sandbox(): # Monkeypatch a replacement root logger, so that our changes to logging # configuration don't persist outside of the test - uaclient_logger = logging.getLogger("uaclient") - uaclient_logger.setLevel(logging.WARNING) + upro_logger = logging.getLogger("ubuntu_pro") + upro_logger.setLevel(logging.WARNING) - with mock.patch.object(logging, "root", uaclient_logger): - with mock.patch.object(logging.Logger, "root", uaclient_logger): + with mock.patch.object(logging, "root", upro_logger): + with mock.patch.object(logging.Logger, "root", upro_logger): with mock.patch.object( - logging.Logger, "manager", logging.Manager(uaclient_logger) + logging.Logger, "manager", logging.Manager(upro_logger) ): yield diff --git a/uaclient/contract.py b/uaclient/contract.py index ba6a19263b..766fcde99d 100644 --- a/uaclient/contract.py +++ b/uaclient/contract.py @@ -8,6 +8,7 @@ event_logger, exceptions, http, + log, messages, system, util, @@ -48,7 +49,7 @@ } event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) class UAContractClient(serviceclient.UAServiceClient): diff --git a/uaclient/daemon/__init__.py b/uaclient/daemon/__init__.py index a8b4868b60..7652e9b0e6 100644 --- a/uaclient/daemon/__init__.py +++ b/uaclient/daemon/__init__.py @@ -10,7 +10,7 @@ from uaclient.defaults import DEFAULT_DATA_DIR from uaclient.log import JsonArrayFormatter -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(pro_log.replace_top_level_logger_name(__name__)) AUTO_ATTACH_STATUS_MOTD_FILE = os.path.join( DEFAULT_DATA_DIR, "messages", "motd-auto-attach-status" @@ -50,11 +50,11 @@ def setup_logging(console_level, log_level, log_file, logger): console_handler = logging.StreamHandler(sys.stderr) console_handler.setFormatter(logging.Formatter("%(message)s")) console_handler.setLevel(console_level) - console_handler.set_name("ua-console") + console_handler.set_name("upro-console") logger.addHandler(console_handler) file_handler = logging.FileHandler(log_file) file_handler.setFormatter(JsonArrayFormatter()) file_handler.setLevel(log_level) - file_handler.set_name("ua-file") + file_handler.set_name("upro-file") logger.addHandler(file_handler) diff --git a/uaclient/data_types.py b/uaclient/data_types.py index ee9c56aa03..59f4b6ff23 100644 --- a/uaclient/data_types.py +++ b/uaclient/data_types.py @@ -4,9 +4,9 @@ from enum import Enum from typing import Any, List, Optional, Type, TypeVar, Union -from uaclient import exceptions, messages, util +from uaclient import exceptions, log, messages, util -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) class IncorrectTypeError(exceptions.UserFacingError): diff --git a/uaclient/entitlements/base.py b/uaclient/entitlements/base.py index 28050678f0..2c70ad6bca 100644 --- a/uaclient/entitlements/base.py +++ b/uaclient/entitlements/base.py @@ -6,7 +6,15 @@ from datetime import datetime from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union -from uaclient import config, contract, event_logger, messages, system, util +from uaclient import ( + config, + contract, + event_logger, + log, + messages, + system, + util, +) from uaclient.api.u.pro.status.is_attached.v1 import _is_attached from uaclient.defaults import DEFAULT_HELP_FILE from uaclient.entitlements.entitlement_status import ( @@ -24,7 +32,7 @@ from uaclient.yaml import safe_load event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) class IncompatibleService: diff --git a/uaclient/entitlements/fips.py b/uaclient/entitlements/fips.py index 6d8f591f76..3eaa19837c 100644 --- a/uaclient/entitlements/fips.py +++ b/uaclient/entitlements/fips.py @@ -3,7 +3,7 @@ from itertools import groupby from typing import List, Optional, Tuple # noqa: F401 -from uaclient import apt, event_logger, exceptions, messages, system, util +from uaclient import apt, event_logger, exceptions, log, messages, system, util from uaclient.clouds.identity import NoCloudTypeReason, get_cloud_type from uaclient.entitlements import repo from uaclient.entitlements.base import IncompatibleService @@ -21,7 +21,7 @@ ) event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) CONDITIONAL_PACKAGES_EVERYWHERE = [ "strongswan", diff --git a/uaclient/entitlements/livepatch.py b/uaclient/entitlements/livepatch.py index 5ce70c52b0..67348ef88b 100644 --- a/uaclient/entitlements/livepatch.py +++ b/uaclient/entitlements/livepatch.py @@ -8,6 +8,7 @@ exceptions, http, livepatch, + log, messages, snap, system, @@ -24,7 +25,7 @@ } event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) class LivepatchEntitlement(UAEntitlement): diff --git a/uaclient/entitlements/repo.py b/uaclient/entitlements/repo.py index fecee843b8..14cc6f2021 100644 --- a/uaclient/entitlements/repo.py +++ b/uaclient/entitlements/repo.py @@ -11,6 +11,7 @@ event_logger, exceptions, http, + log, messages, system, util, @@ -19,7 +20,7 @@ from uaclient.entitlements.entitlement_status import ApplicationStatus event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) class RepoEntitlement(base.UAEntitlement): diff --git a/uaclient/entitlements/tests/test_cc.py b/uaclient/entitlements/tests/test_cc.py index aedd44b109..c8e407c629 100644 --- a/uaclient/entitlements/tests/test_cc.py +++ b/uaclient/entitlements/tests/test_cc.py @@ -75,37 +75,13 @@ def test_inapplicable_on_invalid_affordances( assert details == uf_status_details.msg -class TestCommonCriteriaEntitlementCanEnable: - @mock.patch("uaclient.system.subp", return_value=("", "")) - @mock.patch("uaclient.system.get_dpkg_arch") - @mock.patch("uaclient.system.get_release_info") - def test_can_enable_true_on_entitlement_inactive( - self, m_release_info, m_dpkg_arch, _m_subp, capsys, FakeConfig - ): - """When entitlement is INACTIVE, can_enable returns True.""" - m_release_info.return_value = system.ReleaseInfo( - distribution="", release="", series="xenial", pretty_version="" - ) - m_dpkg_arch.return_value = "s390x" - cfg = FakeConfig().for_attached_machine( - machine_token=CC_MACHINE_TOKEN, - ) - entitlement = CommonCriteriaEntitlement(cfg, allow_beta=True) - uf_status, uf_status_details = entitlement.user_facing_status() - assert status.UserFacingStatus.INACTIVE == uf_status - details = "{} is not configured".format(entitlement.title) - assert details == uf_status_details.msg - assert (True, None) == entitlement.can_enable() - assert ("", "") == capsys.readouterr() - - class TestCommonCriteriaEntitlementEnable: - # Paramterize True/False for apt_transport_https and ca_certificates @pytest.mark.parametrize( "apt_transport_https,ca_certificates", itertools.product([False, True], repeat=2), ) + @mock.patch("uaclient.system.get_kernel_info") @mock.patch("uaclient.apt.setup_apt_proxy") @mock.patch("uaclient.system.should_reboot") @mock.patch("uaclient.system.subp") @@ -122,6 +98,7 @@ def test_enable_configures_apt_sources_and_auth_files( m_subp, m_should_reboot, m_setup_apt_proxy, + m_get_kernel_info, capsys, event, apt_transport_https, diff --git a/uaclient/entitlements/tests/test_cis.py b/uaclient/entitlements/tests/test_cis.py index 9c6d59fb90..cbef758c50 100644 --- a/uaclient/entitlements/tests/test_cis.py +++ b/uaclient/entitlements/tests/test_cis.py @@ -5,7 +5,6 @@ from uaclient import apt, messages, system from uaclient.entitlements.cis import CIS_DOCS_URL, CISEntitlement -from uaclient.entitlements.entitlement_status import ApplicationStatus M_REPOPATH = "uaclient.entitlements.repo." @@ -20,21 +19,6 @@ def entitlement(entitlement_factory): ) -class TestCISEntitlementCanEnable: - def test_can_enable_true_on_entitlement_inactive( - self, capsys, entitlement - ): - """When entitlement is INACTIVE, can_enable returns True.""" - # Unset static affordance container check - with mock.patch.object( - entitlement, - "application_status", - return_value=(ApplicationStatus.DISABLED, ""), - ): - assert entitlement.can_enable() - assert ("", "") == capsys.readouterr() - - class TestCISEntitlementEnable: @mock.patch("uaclient.apt.get_apt_cache_policy") @mock.patch("uaclient.apt.setup_apt_proxy") diff --git a/uaclient/files/files.py b/uaclient/files/files.py index 23e2307aaf..ebb1f977e9 100644 --- a/uaclient/files/files.py +++ b/uaclient/files/files.py @@ -4,11 +4,19 @@ from datetime import datetime from typing import Any, Dict, Optional # noqa: F401 -from uaclient import defaults, event_logger, exceptions, messages, system, util +from uaclient import ( + defaults, + event_logger, + exceptions, + log, + messages, + system, + util, +) from uaclient.contract_data_types import PublicMachineTokenData event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) class UAFile: diff --git a/uaclient/files/notices.py b/uaclient/files/notices.py index acf263da8e..9d9a96f0ca 100644 --- a/uaclient/files/notices.py +++ b/uaclient/files/notices.py @@ -4,9 +4,9 @@ from enum import Enum from typing import List -from uaclient import defaults, event_logger, messages, system, util +from uaclient import defaults, event_logger, log, messages, system, util -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) event = event_logger.get_event_logger() NoticeFileDetails = namedtuple( "NoticeFileDetails", ["order_id", "label", "is_permanent", "message"] diff --git a/uaclient/gpg.py b/uaclient/gpg.py index c9610c82de..e492b326fc 100644 --- a/uaclient/gpg.py +++ b/uaclient/gpg.py @@ -2,9 +2,9 @@ import os import shutil -from uaclient import exceptions +from uaclient import exceptions, log -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) def export_gpg_key(source_keyfile: str, destination_keyfile: str) -> None: diff --git a/uaclient/http/__init__.py b/uaclient/http/__init__.py index 35d99883c0..270cabcba6 100644 --- a/uaclient/http/__init__.py +++ b/uaclient/http/__init__.py @@ -6,7 +6,7 @@ from urllib import error, request from urllib.parse import urlparse -from uaclient import exceptions, messages, util +from uaclient import exceptions, log, messages, util UA_NO_PROXY_URLS = ("169.254.169.254", "metadata", "[fd00:ec2::254]") PROXY_VALIDATION_APT_HTTP_URL = "http://archive.ubuntu.com" @@ -14,6 +14,8 @@ PROXY_VALIDATION_SNAP_HTTP_URL = "http://api.snapcraft.io" PROXY_VALIDATION_SNAP_HTTPS_URL = "https://api.snapcraft.io" +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) + UnparsedHTTPResponse = NamedTuple( "UnparsedHTTPResponse", [ @@ -70,7 +72,7 @@ def validate_proxy( except (socket.timeout, error.URLError) as e: with util.disable_log_to_console(): msg = getattr(e, "reason", str(e)) - logging.error( + LOG.error( messages.ERROR_USING_PROXY.format( proxy=proxy, test_url=test_url, error=msg ) @@ -108,7 +110,7 @@ def configure_web_proxy( set(proxy_value.split(",")).union(set(UA_NO_PROXY_URLS)) ) ) - logging.debug("Setting no_proxy: %s", no_proxy) + LOG.debug("Setting no_proxy: %s", no_proxy) os.environ["no_proxy"] = no_proxy os.environ["NO_PROXY"] = no_proxy if proxy_dict: @@ -154,7 +156,7 @@ def readurl( sorted_header_str = ", ".join( ["'{}': '{}'".format(k, headers[k]) for k in sorted(headers)] ) - logging.debug( + LOG.debug( "URL [{}]: {}, headers: {{{}}}, data: {}".format( method or "GET", url, @@ -188,7 +190,7 @@ def readurl( elif json_list: body_to_log = json_list debug_msg += ", data: {}".format(body_to_log) - logging.debug(debug_msg) + LOG.debug(debug_msg) return HTTPResponse( code=resp.code, diff --git a/uaclient/livepatch.py b/uaclient/livepatch.py index d5f00d6542..bc6ed6f5b1 100644 --- a/uaclient/livepatch.py +++ b/uaclient/livepatch.py @@ -6,7 +6,7 @@ from functools import lru_cache from typing import List, Optional, Tuple -from uaclient import event_logger, exceptions, messages, system, util +from uaclient import event_logger, exceptions, log, messages, system, util from uaclient.data_types import ( BoolDataValue, DataObject, @@ -26,7 +26,7 @@ LIVEPATCH_API_V1_KERNELS_SUPPORTED = "/v1/api/kernels/supported" event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) @enum.unique @@ -218,10 +218,8 @@ def is_kernel_supported( if response.code != 200: with util.disable_log_to_console(): - logging.warning( - "livepatch supported kernels API was unsuccessful" - ) - logging.warning(response.body) + LOG.warning("livepatch supported kernels API was unsuccessful") + LOG.warning(response.body) return None api_supported_val = response.json_dict.get("Supported") diff --git a/uaclient/lock.py b/uaclient/lock.py index 423b814fa8..e9e49a79fe 100644 --- a/uaclient/lock.py +++ b/uaclient/lock.py @@ -3,11 +3,11 @@ import os import time -from uaclient import config, exceptions +from uaclient import config, exceptions, log from uaclient.files import notices from uaclient.files.notices import Notice -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) # Set a module-level callable here so we don't have to reinstantiate # UAConfig in order to determine dynamic data_path exception handling of diff --git a/uaclient/log.py b/uaclient/log.py index 0174f29472..ce4db09569 100644 --- a/uaclient/log.py +++ b/uaclient/log.py @@ -84,3 +84,9 @@ def get_all_user_log_files() -> List[str]: if os.path.isfile(user_path): log_files.append(user_path) return log_files + + +def replace_top_level_logger_name(name: str) -> str: + names = name.split(".") + names[0] = "ubuntu_pro" + return ".".join(names) diff --git a/uaclient/snap.py b/uaclient/snap.py index 7b979e4123..20021beae5 100644 --- a/uaclient/snap.py +++ b/uaclient/snap.py @@ -2,7 +2,7 @@ import re from typing import List, Optional -from uaclient import apt, event_logger, exceptions, messages, system +from uaclient import apt, event_logger, exceptions, log, messages, system SNAP_CMD = "/usr/bin/snap" SNAP_INSTALL_RETRIES = [0.5, 1.0, 5.0] @@ -11,7 +11,7 @@ SNAP_CHANNEL_SHORTEN_VALUE = "…" event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) def is_installed() -> bool: diff --git a/uaclient/status.py b/uaclient/status.py index aecd69fc5d..6ec45a1e0e 100644 --- a/uaclient/status.py +++ b/uaclient/status.py @@ -10,6 +10,7 @@ event_logger, exceptions, livepatch, + log, messages, util, version, @@ -30,7 +31,7 @@ from uaclient.messages import TxtColor event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) ESSENTIAL = "essential" diff --git a/uaclient/system.py b/uaclient/system.py index aecc158e3f..3f44b206cf 100644 --- a/uaclient/system.py +++ b/uaclient/system.py @@ -21,7 +21,9 @@ DISTRO_INFO_CSV = "/usr/share/distro-info/ubuntu.csv" CPU_VENDOR_MAP = {"GenuineIntel": "intel"} -LOG = logging.getLogger(__name__) +log_names = __name__.split(".") +log_names[0] = "ubuntu_pro" +LOG = logging.getLogger(".".join(log_names)) # N.B. this relies on the version normalisation we perform in get_release_info REGEX_OS_RELEASE_VERSION = ( @@ -88,13 +90,13 @@ def _get_kernel_changelog_timestamp( ) -> Optional[datetime.datetime]: if is_container(): with util.disable_log_to_console(): - logging.warning( + LOG.warning( "Not attempting to use timestamp of kernel changelog because we're in a container" # noqa: E501 ) return None with util.disable_log_to_console(): - logging.warning("Falling back to using timestamp of kernel changelog") + LOG.warning("Falling back to using timestamp of kernel changelog") try: stat_result = os.stat( @@ -107,7 +109,7 @@ def _get_kernel_changelog_timestamp( ) except Exception: with util.disable_log_to_console(): - logging.warning("Unable to stat kernel changelog") + LOG.warning("Unable to stat kernel changelog") return None @@ -117,14 +119,14 @@ def _get_kernel_build_date( date_match = re.search(RE_KERNEL_EXTRACT_BUILD_DATE, uname.version) if date_match is None: with util.disable_log_to_console(): - logging.warning("Unable to find build date in uname version") + LOG.warning("Unable to find build date in uname version") return _get_kernel_changelog_timestamp(uname) date_str = date_match.group(0) try: dt = datetime.datetime.strptime(date_str, "%a %b %d %H:%M:%S %Z %Y") except ValueError: with util.disable_log_to_console(): - logging.warning("Unable to parse build date from uname version") + LOG.warning("Unable to parse build date from uname version") return _get_kernel_changelog_timestamp(uname) if dt.tzinfo is None: # Give it a default timezone if it didn't get one from strptime diff --git a/uaclient/tests/test_cli.py b/uaclient/tests/test_cli.py index 7343aba432..ef4bef792d 100644 --- a/uaclient/tests/test_cli.py +++ b/uaclient/tests/test_cli.py @@ -509,7 +509,6 @@ def test_errors_handled_gracefully( _m_setup_logging, m_delete_cache_key, capsys, - logging_sandbox, caplog_text, event, exception, @@ -558,7 +557,6 @@ def test_interrupt_errors_handled_gracefully( _m_setup_logging, m_delete_cache_key, capsys, - logging_sandbox, caplog_text, exception, expected_error_msg, @@ -608,7 +606,6 @@ def test_user_facing_error_handled_gracefully( m_get_parser, _m_setup_logging, capsys, - logging_sandbox, caplog_text, event, exception, @@ -664,7 +661,6 @@ def test_url_error_handled_gracefully( error_url, expected_log, capsys, - logging_sandbox, caplog_text, ): m_args = m_get_parser.return_value.parse_args.return_value @@ -690,7 +686,7 @@ def test_url_error_handled_gracefully( @mock.patch("uaclient.cli.setup_logging") @mock.patch("uaclient.cli.get_parser") def test_command_line_is_logged( - self, _m_get_parser, _m_setup_logging, logging_sandbox, caplog_text + self, _m_get_parser, _m_setup_logging, caplog_text ): main(["some", "args"]) @@ -710,7 +706,6 @@ def test_environment_is_logged( _m_pro_environment, _m_get_parser, _m_setup_logging, - logging_sandbox, caplog_text, ): main(["some", "args"]) diff --git a/uaclient/tests/test_cli_auto_attach.py b/uaclient/tests/test_cli_auto_attach.py index 07c9f5d672..208c81c950 100644 --- a/uaclient/tests/test_cli_auto_attach.py +++ b/uaclient/tests/test_cli_auto_attach.py @@ -149,16 +149,23 @@ def test_uncaught_errors_are_handled( api_side_effect, expected_err, expected_ret, - capsys, FakeConfig, + caplog_text, + event, ): m_full_auto_attach.side_effect = api_side_effect cfg = FakeConfig() with pytest.raises(SystemExit) as excinfo: - main_error_handler(action_auto_attach)(mock.MagicMock(), cfg=cfg) + with mock.patch.object( + event, + "_event_logger_mode", + event_logger.EventLoggerMode.JSON, + ): + main_error_handler(action_auto_attach)( + mock.MagicMock(), cfg=cfg + ) assert expected_ret == excinfo.value.code - _out, err = capsys.readouterr() - assert expected_err == err + assert expected_err in caplog_text() assert [] == m_post_cli_attach.call_args_list diff --git a/uaclient/tests/test_esm_cache.py b/uaclient/tests/test_esm_cache.py index 024619ea42..5762cad730 100644 --- a/uaclient/tests/test_esm_cache.py +++ b/uaclient/tests/test_esm_cache.py @@ -1,7 +1,4 @@ -import logging - import mock -import pytest from lib.esm_cache import main from uaclient.exceptions import MissingSeriesOnOSReleaseFile @@ -14,9 +11,8 @@ def test_builds_local_cache(self, m_update_caches, FakeConfig): assert m_update_caches.call_count == 1 - @pytest.mark.parametrize("caplog_text", [logging.ERROR], indirect=True) def test_log_user_facing_exception( - self, m_update_caches, caplog_text, capsys, FakeConfig + self, m_update_caches, capsys, FakeConfig ): expected_exception = MissingSeriesOnOSReleaseFile(version="version") m_update_caches.side_effect = expected_exception @@ -25,10 +21,7 @@ def test_log_user_facing_exception( for line in expected_exception.msg.split("\n"): assert line in err - @pytest.mark.parametrize("caplog_text", [logging.ERROR], indirect=True) - def test_log_exception( - self, m_update_caches, caplog_text, capsys, FakeConfig - ): + def test_log_exception(self, m_update_caches, capsys, FakeConfig): expected_msg = "unexpected exception" expected_exception = Exception(expected_msg) m_update_caches.side_effect = expected_exception diff --git a/uaclient/tests/test_log.py b/uaclient/tests/test_log.py index 7ad586db14..26a81a5496 100644 --- a/uaclient/tests/test_log.py +++ b/uaclient/tests/test_log.py @@ -6,7 +6,7 @@ from uaclient import log as pro_log -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(pro_log.replace_top_level_logger_name(__name__)) LOG_FMT = "%(asctime)s%(name)s%(funcName)s%(lineno)s\ %(levelname)s%(message)s%(extra)s" DATE_FMT = "%Y-%m-%dT%H:%M:%S%z" @@ -137,7 +137,7 @@ class TestLoggerFormatter: ), ), ) - @pytest.mark.parametrize("caplog_text", [logging.NOTSET], indirect=True) + @pytest.mark.parametrize("caplog_text", [logging.DEBUG], indirect=True) def test_valid_json_output( self, caplog_text, message, level, log_fn, levelname, extra ): @@ -151,7 +151,7 @@ def test_valid_json_output( logged_value = buffer.getvalue() val = json.loads(logged_value) assert val[1] == levelname - assert val[2] == __name__ + assert val[2] == pro_log.replace_top_level_logger_name(__name__) assert val[5] == message if extra: assert val[6].get("key") == extra.get("key") diff --git a/uaclient/timer/__init__.py b/uaclient/timer/__init__.py index bd4739e825..64bb0bf0d4 100644 --- a/uaclient/timer/__init__.py +++ b/uaclient/timer/__init__.py @@ -3,7 +3,7 @@ from uaclient import exceptions, system -LOG = logging.getLogger("uaclient.timer") +LOG = logging.getLogger("ubuntu_pro.timer") def start(): diff --git a/uaclient/timer/update_contract_info.py b/uaclient/timer/update_contract_info.py index 52daa8749d..542ba9d6a2 100644 --- a/uaclient/timer/update_contract_info.py +++ b/uaclient/timer/update_contract_info.py @@ -1,12 +1,12 @@ import logging -from uaclient import contract, messages, util +from uaclient import contract, log, messages, util from uaclient.api.u.pro.status.is_attached.v1 import _is_attached from uaclient.config import UAConfig from uaclient.files import notices from uaclient.files.notices import Notice -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) def update_contract_info(cfg: UAConfig) -> bool: diff --git a/uaclient/timer/update_messaging.py b/uaclient/timer/update_messaging.py index 1d639dd0dd..f4db98a37a 100644 --- a/uaclient/timer/update_messaging.py +++ b/uaclient/timer/update_messaging.py @@ -12,7 +12,7 @@ from os.path import exists from typing import Tuple -from uaclient import contract, defaults, messages, system +from uaclient import contract, defaults, log, messages, system from uaclient.api.u.pro.packages.updates.v1 import ( _updates as api_u_pro_packages_updates_v1, ) @@ -25,7 +25,7 @@ UPDATE_NOTIFIER_MOTD_SCRIPT = ( "/usr/lib/update-notifier/update-motd-updates-available" ) -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) @enum.unique diff --git a/uaclient/upgrade_lts_contract.py b/uaclient/upgrade_lts_contract.py index 128c3e8243..ff50b9b070 100755 --- a/uaclient/upgrade_lts_contract.py +++ b/uaclient/upgrade_lts_contract.py @@ -27,7 +27,7 @@ import sys import time -from uaclient import contract, defaults, system +from uaclient import contract, defaults, log, system from uaclient.api.u.pro.status.is_attached.v1 import _is_attached from uaclient.config import UAConfig @@ -46,7 +46,7 @@ "mantic": "lunar", } -LOG = logging.getLogger(__name__) +LOG = logging.getLogger(log.replace_top_level_logger_name(__name__)) def process_contract_delta_after_apt_lock(cfg: UAConfig) -> None: diff --git a/uaclient/util.py b/uaclient/util.py index 643b0bb0c9..136079c6d2 100644 --- a/uaclient/util.py +++ b/uaclient/util.py @@ -17,7 +17,9 @@ event = event_logger.get_event_logger() -LOG = logging.getLogger(__name__) +log_names = __name__.split(".") +log_names[0] = "ubuntu_pro" +LOG = logging.getLogger(".".join(log_names)) class LogFormatter(logging.Formatter): @@ -91,12 +93,15 @@ def disable_log_to_console(): (Note that the @contextmanager decorator also allows this function to be used as a decorator.) """ - uaclient_logger = logging.getLogger("uaclient") - log_handlers = uaclient_logger.handlers - if not log_handlers and uaclient_logger.parent: - log_handlers = uaclient_logger.parent.handlers + # import pdb + # + # pdb.set_trace() + upro_logger = logging.getLogger("ubuntu_pro") + log_handlers = upro_logger.handlers + if not log_handlers and upro_logger.parent: + log_handlers = upro_logger.parent.handlers potential_handlers = [ - handler for handler in log_handlers if handler.name == "ua-console" + handler for handler in log_handlers if handler.name == "upro-console" ] if not potential_handlers: # We didn't find a handler, so execute the body as normal then end diff --git a/uaclient/yaml.py b/uaclient/yaml.py index 2a09d048b7..b751d65d37 100644 --- a/uaclient/yaml.py +++ b/uaclient/yaml.py @@ -3,7 +3,9 @@ from uaclient.messages import BROKEN_YAML_MODULE, MISSING_YAML_MODULE -LOG = logging.getLogger(__name__) +log_names = __name__.split(".") +log_names[0] = "ubuntu_pro" +LOG = logging.getLogger(".".join(log_names)) try: import yaml