From bd77c9b7f31c9b6052f3f44157e571e585c13bd2 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Sat, 12 Aug 2023 00:18:24 -0700 Subject: [PATCH 01/18] initial commit Signed-off-by: Shaanjot Gill --- aries_cloudagent/config/ledger.py | 17 ++++-- aries_cloudagent/config/logging.py | 10 ++-- aries_cloudagent/core/conductor.py | 31 +++++++--- aries_cloudagent/core/event_bus.py | 17 ++++-- aries_cloudagent/indy/credx/holder.py | 9 ++- aries_cloudagent/indy/credx/issuer.py | 15 +++-- aries_cloudagent/indy/credx/verifier.py | 11 ++-- aries_cloudagent/indy/sdk/issuer.py | 17 +++--- aries_cloudagent/indy/sdk/verifier.py | 19 +++--- aries_cloudagent/indy/verifier.py | 19 +++--- aries_cloudagent/ledger/indy.py | 9 ++- .../ledger/multiple_ledger/indy_manager.py | 16 +++-- .../multiple_ledger/indy_vdr_manager.py | 15 +++-- aries_cloudagent/ledger/routes.py | 15 +++-- aries_cloudagent/multitenant/base.py | 11 ++-- aries_cloudagent/multitenant/cache.py | 7 ++- aries_cloudagent/multitenant/route_manager.py | 13 ++++- .../v1_0/handlers/menu_request_handler.py | 11 +++- .../v1_0/handlers/perform_handler.py | 11 +++- .../protocols/actionmenu/v1_0/routes.py | 20 ++++--- .../v1_0/handlers/basicmessage_handler.py | 11 +++- .../handlers/connection_request_handler.py | 19 +++--- .../handlers/connection_response_handler.py | 15 +++-- .../protocols/connections/v1_0/manager.py | 6 +- .../v1_0/handlers/keylist_handler.py | 14 ++--- .../v1_0/handlers/keylist_query_handler.py | 9 ++- .../v1_0/handlers/keylist_update_handler.py | 9 ++- .../keylist_update_response_handler.py | 15 ++++- .../v1_0/handlers/mediation_deny_handler.py | 9 ++- .../v1_0/handlers/mediation_grant_handler.py | 9 ++- .../handlers/mediation_request_handler.py | 9 ++- .../coordinate_mediation/v1_0/manager.py | 13 +++-- .../v1_0/route_manager.py | 16 +++-- .../v1_0/handlers/complete_handler.py | 11 +++- .../v1_0/handlers/request_handler.py | 18 +++--- .../v1_0/handlers/response_handler.py | 15 +++-- .../protocols/didexchange/v1_0/manager.py | 6 +- .../v1_0/handlers/disclose_handler.py | 9 ++- .../discovery/v1_0/handlers/query_handler.py | 9 ++- .../protocols/discovery/v1_0/manager.py | 6 +- .../v2_0/handlers/disclosures_handler.py | 9 ++- .../v2_0/handlers/queries_handler.py | 9 ++- .../protocols/discovery/v2_0/manager.py | 6 +- .../endorsed_transaction_response_handler.py | 14 +++-- .../refused_transaction_response_handler.py | 12 +++- .../transaction_acknowledgement_handler.py | 12 +++- .../handlers/transaction_cancel_handler.py | 12 +++- .../transaction_job_to_send_handler.py | 12 +++- .../handlers/transaction_request_handler.py | 14 +++-- .../handlers/transaction_resend_handler.py | 12 +++- .../endorse_transaction/v1_0/routes.py | 10 ++-- .../introduction/v0_1/demo_service.py | 12 ++-- .../handlers/forward_invitation_handler.py | 11 +++- .../v0_1/handlers/invitation_handler.py | 9 ++- .../handlers/invitation_request_handler.py | 9 ++- .../protocols/introduction/v0_1/routes.py | 9 ++- .../v1_0/handlers/credential_ack_handler.py | 12 +++- .../v1_0/handlers/credential_issue_handler.py | 13 ++++- .../v1_0/handlers/credential_offer_handler.py | 12 +++- .../credential_problem_report_handler.py | 11 +++- .../handlers/credential_proposal_handler.py | 13 ++++- .../handlers/credential_request_handler.py | 15 +++-- .../issue_credential/v1_0/manager.py | 31 +++++----- .../v1_0/models/credential_exchange.py | 10 ++-- .../issue_credential/v2_0/formats/handler.py | 5 ++ .../v2_0/formats/indy/handler.py | 10 ++-- .../v2_0/formats/ld_proof/handler.py | 4 +- .../v2_0/handlers/cred_ack_handler.py | 12 +++- .../v2_0/handlers/cred_issue_handler.py | 14 +++-- .../v2_0/handlers/cred_offer_handler.py | 14 +++-- .../handlers/cred_problem_report_handler.py | 11 +++- .../v2_0/handlers/cred_proposal_handler.py | 14 +++-- .../v2_0/handlers/cred_request_handler.py | 14 +++-- .../issue_credential/v2_0/manager.py | 11 ++-- .../v2_0/models/cred_ex_record.py | 10 ++-- .../protocols/issue_credential/v2_0/routes.py | 58 +++++++++++++++---- .../v1_0/handlers/problem_report_handler.py | 11 +++- .../v1_0/handlers/reuse_accept_handler.py | 13 +++-- .../v1_0/handlers/reuse_handler.py | 11 +++- .../protocols/out_of_band/v1_0/manager.py | 41 ++++++++----- .../present_proof/dif/pres_exch_handler.py | 14 +++-- .../present_proof/indy/pres_exch_handler.py | 11 ++-- .../v1_0/handlers/presentation_ack_handler.py | 12 +++- .../v1_0/handlers/presentation_handler.py | 13 ++++- .../presentation_problem_report_handler.py | 11 +++- .../handlers/presentation_proposal_handler.py | 15 +++-- .../handlers/presentation_request_handler.py | 15 +++-- .../protocols/present_proof/v1_0/manager.py | 15 +++-- .../v1_0/models/presentation_exchange.py | 10 ++-- .../v2_0/handlers/pres_ack_handler.py | 12 +++- .../v2_0/handlers/pres_handler.py | 14 +++-- .../handlers/pres_problem_report_handler.py | 11 +++- .../v2_0/handlers/pres_proposal_handler.py | 14 +++-- .../v2_0/handlers/pres_request_handler.py | 14 +++-- .../protocols/present_proof/v2_0/manager.py | 13 +++-- .../v2_0/models/pres_exchange.py | 10 ++-- .../protocols/problem_report/v1_0/handler.py | 11 +++- .../v1_0/handlers/revoke_handler.py | 9 ++- .../revocation_notification/v1_0/routes.py | 13 +++-- .../v2_0/handlers/revoke_handler.py | 9 ++- .../revocation_notification/v2_0/routes.py | 13 +++-- .../routing/v1_0/handlers/forward_handler.py | 16 +++-- .../protocols/routing/v1_0/manager.py | 27 ++++++--- .../trustping/v1_0/handlers/ping_handler.py | 15 +++-- .../v1_0/handlers/ping_response_handler.py | 12 +++- .../resolver/default/universal.py | 9 ++- aries_cloudagent/revocation/indy.py | 13 +++-- .../models/issuer_rev_reg_record.py | 39 ++++++++----- aries_cloudagent/wallet/routes.py | 19 +++--- 109 files changed, 1035 insertions(+), 437 deletions(-) diff --git a/aries_cloudagent/config/ledger.py b/aries_cloudagent/config/ledger.py index 750ba314ff..091fa9f02c 100644 --- a/aries_cloudagent/config/ledger.py +++ b/aries_cloudagent/config/ledger.py @@ -12,6 +12,7 @@ from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop from prompt_toolkit.formatted_text import HTML +from ..config.logging import get_logger_inst from ..config.settings import Settings from ..core.profile import Profile from ..ledger.base import BaseLedger @@ -128,10 +129,13 @@ async def ledger_config( """Perform Indy ledger configuration.""" session = await profile.session() - + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) ledger = session.inject_or(BaseLedger) if not ledger: - LOGGER.info("Ledger instance not provided") + _logger.info("Ledger instance not provided") return False async with ledger: @@ -252,7 +256,10 @@ async def accept_taa( mechanisms = taa_info["aml_record"]["aml"] mechanism = None - + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) taa_acceptance_mechanism = profile.settings.get("ledger.taa_acceptance_mechanism") taa_acceptance_version = profile.settings.get("ledger.taa_acceptance_version") @@ -278,13 +285,13 @@ async def accept_taa( elif sys.stdout.isatty(): mechanism = await select_aml_tty(taa_info, provision) else: - LOGGER.warning( + _logger.warning( "Cannot accept TAA without interactive terminal or taa accept config" ) if not mechanism: return False - LOGGER.debug(f"Accepting the TAA using mechanism '{mechanism}'") + _logger.debug(f"Accepting the TAA using mechanism '{mechanism}'") await ledger.accept_txn_author_agreement(taa_info["taa_record"], mechanism) return True diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index f3bd59217d..8f4e4b75b2 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -10,19 +10,21 @@ import re import sys import time as mod_time -from typing import Optional, TextIO +from typing import Optional, TextIO, TYPE_CHECKING import pkg_resources from portalocker import LOCK_EX, lock, unlock from pythonjsonlogger import jsonlogger from ..config.settings import Settings -from ..core.profile import Profile from ..version import __version__ from ..wallet.base import BaseWallet, DIDInfo from .banner import Banner from .base import BaseSettings +if TYPE_CHECKING: # To avoid circular import error + from ..core.profile import Profile + DEFAULT_LOGGING_CONFIG_PATH = "aries_cloudagent.config:default_logging_config.ini" @@ -521,7 +523,7 @@ def clear_prev_handlers(logger: logging.Logger) -> logging.Logger: return logger -def get_logger_inst(profile: Profile, logger_name) -> logging.Logger: +def get_logger_inst(profile: "Profile", logger_name) -> logging.Logger: """Return a logger instance with provided name and handlers.""" did_ident = get_did_ident(profile) if did_ident: @@ -536,7 +538,7 @@ def get_logger_inst(profile: Profile, logger_name) -> logging.Logger: ) -def get_did_ident(profile: Profile) -> Optional[str]: +def get_did_ident(profile: "Profile") -> Optional[str]: """Get public did identifier for logging, if applicable.""" did_ident = None if profile.settings.get("log.file"): diff --git a/aries_cloudagent/core/conductor.py b/aries_cloudagent/core/conductor.py index 5e4887930f..3eb8151f26 100644 --- a/aries_cloudagent/core/conductor.py +++ b/aries_cloudagent/core/conductor.py @@ -24,7 +24,7 @@ ledger_config, load_multiple_genesis_transactions_from_config, ) -from ..config.logging import LoggingConfigurator +from ..config.logging import LoggingConfigurator, get_logger_inst from ..config.provider import ClassProvider from ..config.wallet import wallet_config from ..commands.upgrade import ( @@ -551,9 +551,12 @@ def inbound_message_router( can_respond: If the session supports return routing """ - + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) if message.receipt.direct_response_requested and not can_respond: - LOGGER.warning( + _logger.warning( "Direct response requested, but not supported by transport: %s", message.transport_type, ) @@ -569,7 +572,7 @@ def inbound_message_router( lambda completed: self.dispatch_complete(message, completed), ) except (LedgerConfigError, LedgerTransactionError) as e: - LOGGER.error("Shutdown on ledger error %s", str(e)) + _logger.error("Shutdown on ledger error %s", str(e)) if self.admin_server: self.admin_server.notify_fatal_error() raise @@ -660,10 +663,14 @@ async def _outbound_message_router( def handle_not_returned(self, profile: Profile, outbound: OutboundMessage): """Handle a message that failed delivery via an inbound session.""" + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) try: self.dispatcher.run_task(self.queue_outbound(profile, outbound)) except (LedgerConfigError, LedgerTransactionError) as e: - LOGGER.error("Shutdown on ledger error %s", str(e)) + _logger.error("Shutdown on ledger error %s", str(e)) if self.admin_server: self.admin_server.notify_fatal_error() raise @@ -681,6 +688,10 @@ async def queue_outbound( message: An outbound message to be sent inbound: The inbound message that produced this response, if available """ + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) has_target = outbound.target or outbound.target_list # populate connection target(s) @@ -693,10 +704,10 @@ async def queue_outbound( ) ) except ConnectionManagerError: - LOGGER.exception("Error preparing outbound message for transmission") + _logger.exception("Error preparing outbound message for transmission") return OutboundSendStatus.UNDELIVERABLE except (LedgerConfigError, LedgerTransactionError) as e: - LOGGER.error("Shutdown on ledger error %s", str(e)) + _logger.error("Shutdown on ledger error %s", str(e)) if self.admin_server: self.admin_server.notify_fatal_error() raise @@ -716,11 +727,15 @@ async def _queue_message( self, profile: Profile, outbound: OutboundMessage ) -> OutboundSendStatus: """Save the message to an internal outbound queue.""" + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) try: await self.outbound_transport_manager.enqueue_message(profile, outbound) return OutboundSendStatus.QUEUED_FOR_DELIVERY except OutboundDeliveryError: - LOGGER.warning("Cannot queue message for delivery, no supported transport") + _logger.warning("Cannot queue message for delivery, no supported transport") return self.handle_not_delivered(profile, outbound) def handle_not_delivered( diff --git a/aries_cloudagent/core/event_bus.py b/aries_cloudagent/core/event_bus.py index 22d7c8f922..85c0c50ac0 100644 --- a/aries_cloudagent/core/event_bus.py +++ b/aries_cloudagent/core/event_bus.py @@ -19,6 +19,8 @@ ) from functools import partial +from ..config.logging import get_logger_inst + if TYPE_CHECKING: # To avoid circular import error from .profile import Profile @@ -97,8 +99,11 @@ async def notify(self, profile: "Profile", event: Event): # TODO don't block notifier until subscribers have all been called? # TODO trigger each processor but don't await? # TODO log errors but otherwise ignore? - - LOGGER.debug("Notifying subscribers: %s", event) + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) + _logger.debug("Notifying subscribers: %s", event) partials = [] for pattern, subscribers in self.topic_patterns_to_subscribers.items(): @@ -120,7 +125,7 @@ async def notify(self, profile: "Profile", event: Event): try: await processor() except Exception: - LOGGER.exception("Error occurred while processing event") + _logger.exception("Error occurred while processing event") def subscribe(self, pattern: Pattern, processor: Callable): """Subscribe to an event. @@ -168,7 +173,11 @@ def wait_for_event( async def _handle_single_event(profile, event): """Handle the single event.""" - LOGGER.debug( + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) + _logger.debug( "wait_for_event event listener with event %s and profile %s", event, profile, diff --git a/aries_cloudagent/indy/credx/holder.py b/aries_cloudagent/indy/credx/holder.py index d593838319..2bfe3bc4ba 100644 --- a/aries_cloudagent/indy/credx/holder.py +++ b/aries_cloudagent/indy/credx/holder.py @@ -20,13 +20,12 @@ ) from ...askar.profile import AskarProfile +from ...config.logging import get_logger_inst from ...ledger.base import BaseLedger from ...wallet.error import WalletNotFoundError from ..holder import IndyHolder, IndyHolderError -LOGGER = logging.getLogger(__name__) - CATEGORY_CREDENTIAL = "credential" CATEGORY_LINK_SECRET = "master_secret" @@ -61,6 +60,10 @@ def __init__(self, profile: AskarProfile): """ self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property def profile(self) -> AskarProfile: @@ -138,7 +141,7 @@ async def create_credential_request( cred_req_metadata.to_json(), ) - LOGGER.debug( + self._logger.debug( "Created credential request. " "credential_request_json=%s credential_request_metadata_json=%s", cred_req_json, diff --git a/aries_cloudagent/indy/credx/issuer.py b/aries_cloudagent/indy/credx/issuer.py index 6150d9d9ca..91972501b2 100644 --- a/aries_cloudagent/indy/credx/issuer.py +++ b/aries_cloudagent/indy/credx/issuer.py @@ -21,6 +21,7 @@ ) from ...askar.profile import AskarProfile +from ...config.logging import get_logger_inst from ..issuer import ( IndyIssuer, @@ -30,8 +31,6 @@ DEFAULT_SIGNATURE_TYPE, ) -LOGGER = logging.getLogger(__name__) - CATEGORY_CRED_DEF = "credential_def" CATEGORY_CRED_DEF_PRIVATE = "credential_def_private" CATEGORY_CRED_DEF_KEY_PROOF = "credential_def_key_proof" @@ -54,6 +53,10 @@ def __init__(self, profile: AskarProfile): """ self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property def profile(self) -> AskarProfile: @@ -448,7 +451,7 @@ async def revoke_credentials( for rev_id in cred_revoc_ids: rev_id = int(rev_id) if rev_id < 1 or rev_id > max_cred_num: - LOGGER.error( + self._logger.error( "Skipping requested credential revocation" "on rev reg id %s, cred rev id=%s not in range", revoc_reg_id, @@ -456,7 +459,7 @@ async def revoke_credentials( ) failed_crids.add(rev_id) elif rev_id > rev_info["curr_id"]: - LOGGER.warn( + self._logger.warn( "Skipping requested credential revocation" "on rev reg id %s, cred rev id=%s not yet issued", revoc_reg_id, @@ -464,7 +467,7 @@ async def revoke_credentials( ) failed_crids.add(rev_id) elif rev_id in used_ids: - LOGGER.warn( + self._logger.warn( "Skipping requested credential revocation" "on rev reg id %s, cred rev id=%s already revoked", revoc_reg_id, @@ -500,7 +503,7 @@ async def revoke_credentials( CATEGORY_REV_REG_INFO, revoc_reg_id, for_update=True ) if not rev_reg_upd or not rev_reg_info: - LOGGER.warn( + self._logger.warn( "Revocation registry missing, skipping update: {}", revoc_reg_id, ) diff --git a/aries_cloudagent/indy/credx/verifier.py b/aries_cloudagent/indy/credx/verifier.py index 0911009144..16b4e830a9 100644 --- a/aries_cloudagent/indy/credx/verifier.py +++ b/aries_cloudagent/indy/credx/verifier.py @@ -7,12 +7,11 @@ from indy_credx import CredxError, Presentation +from ...config.logging import get_logger_inst from ...core.profile import Profile from ..verifier import IndyVerifier, PresVerifyMsg -LOGGER = logging.getLogger(__name__) - class IndyCredxVerifier(IndyVerifier): """Indy-Credx verifier class.""" @@ -25,6 +24,10 @@ def __init__(self, profile: Profile): """ self.profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def verify_presentation( self, @@ -60,7 +63,7 @@ async def verify_presentation( except ValueError as err: s = str(err) msgs.append(f"{PresVerifyMsg.PRES_VALUE_ERROR.value}::{s}") - LOGGER.error( + self._logger.error( f"Presentation on nonce={pres_req['nonce']} " f"cannot be validated: {str(err)}" ) @@ -81,7 +84,7 @@ async def verify_presentation( except CredxError as err: s = str(err) msgs.append(f"{PresVerifyMsg.PRES_VERIFY_ERROR.value}::{s}") - LOGGER.exception( + self._logger.exception( f"Validation of presentation on nonce={pres_req['nonce']} " "failed with error" ) diff --git a/aries_cloudagent/indy/sdk/issuer.py b/aries_cloudagent/indy/sdk/issuer.py index 8ac62b8637..539aed49cb 100644 --- a/aries_cloudagent/indy/sdk/issuer.py +++ b/aries_cloudagent/indy/sdk/issuer.py @@ -8,6 +8,7 @@ import indy.blob_storage from indy.error import AnoncredsRevocationRegistryFullError, IndyError, ErrorCode +from ...config.logging import get_logger_inst from ...indy.sdk.profile import IndySdkProfile from ...messaging.util import encode from ...storage.error import StorageError @@ -23,8 +24,6 @@ from .error import IndyErrorHandler from .util import create_tails_reader, create_tails_writer -LOGGER = logging.getLogger(__name__) - class IndySdkIssuer(IndyIssuer): """Indy-SDK issuer implementation.""" @@ -37,6 +36,10 @@ def __init__(self, profile: IndySdkProfile): """ self.profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def create_schema( self, @@ -211,7 +214,7 @@ async def create_credential( tails_reader_handle, ) except AnoncredsRevocationRegistryFullError: - LOGGER.warning( + self._logger.warning( "Revocation registry %s is full: cannot create credential", rev_reg_id, ) @@ -223,7 +226,7 @@ async def create_credential( err, "Error when issuing credential", IndyIssuerError ) from err except StorageError as err: - LOGGER.warning( + self._logger.warning( ( "Created issuer cred rev record for " "Could not store issuer cred rev record for " @@ -272,7 +275,7 @@ async def revoke_credentials( ) except IndyError as err: if err.error_code == ErrorCode.AnoncredsInvalidUserRevocId: - LOGGER.error( + self._logger.error( ( "Abstaining from revoking credential on " "rev reg id %s, cred rev id=%s: " @@ -282,7 +285,7 @@ async def revoke_credentials( cred_rev_id, ) else: - LOGGER.error( + self._logger.error( IndyErrorHandler.wrap_error( err, "Revocation error", IndyIssuerError ).roll_up @@ -290,7 +293,7 @@ async def revoke_credentials( failed_crids.add(int(cred_rev_id)) continue except StorageError as err: - LOGGER.warning( + self._logger.warning( ( "Revoked credential on rev reg id %s, cred rev id %s " "without corresponding issuer cred rev record: %s" diff --git a/aries_cloudagent/indy/sdk/verifier.py b/aries_cloudagent/indy/sdk/verifier.py index 81bdc5a601..7a9317b300 100644 --- a/aries_cloudagent/indy/sdk/verifier.py +++ b/aries_cloudagent/indy/sdk/verifier.py @@ -8,12 +8,11 @@ import indy.anoncreds from indy.error import IndyError +from ...config.logging import get_logger_inst from ...core.profile import Profile from ..verifier import IndyVerifier, PresVerifyMsg -LOGGER = logging.getLogger(__name__) - class IndySdkVerifier(IndyVerifier): """Indy-SDK verifier implementation.""" @@ -26,6 +25,10 @@ def __init__(self, profile: Profile): """ self.profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def verify_presentation( self, @@ -47,8 +50,8 @@ async def verify_presentation( rev_reg_entries: revocation registry entries """ - LOGGER.debug(f">>> received presentation: {pres}") - LOGGER.debug(f">>> for pres_req: {pres_req}") + self._logger.debug(f">>> received presentation: {pres}") + self._logger.debug(f">>> for pres_req: {pres_req}") msgs = [] try: msgs += self.non_revoc_intervals(pres_req, pres, credential_definitions) @@ -59,14 +62,14 @@ async def verify_presentation( except ValueError as err: s = str(err) msgs.append(f"{PresVerifyMsg.PRES_VALUE_ERROR.value}::{s}") - LOGGER.error( + self._logger.error( f"Presentation on nonce={pres_req['nonce']} " f"cannot be validated: {str(err)}" ) return (False, msgs) - LOGGER.debug(f">>> verifying presentation: {pres}") - LOGGER.debug(f">>> for pres_req: {pres_req}") + self._logger.debug(f">>> verifying presentation: {pres}") + self._logger.debug(f">>> for pres_req: {pres_req}") try: verified = await indy.anoncreds.verifier_verify_proof( json.dumps(pres_req), @@ -79,7 +82,7 @@ async def verify_presentation( except IndyError as err: s = str(err) msgs.append(f"{PresVerifyMsg.PRES_VERIFY_ERROR.value}::{s}") - LOGGER.exception( + self._logger.exception( f"Validation of presentation on nonce={pres_req['nonce']} " "failed with error" ) diff --git a/aries_cloudagent/indy/verifier.py b/aries_cloudagent/indy/verifier.py index 0b7dd5f536..1d46a9d4fd 100644 --- a/aries_cloudagent/indy/verifier.py +++ b/aries_cloudagent/indy/verifier.py @@ -7,6 +7,7 @@ from time import time from typing import Mapping, Tuple +from ..config.logging import get_logger_inst from ..core.profile import Profile from ..ledger.multiple_ledger.ledger_requests_executor import ( GET_CRED_DEF, @@ -123,14 +124,18 @@ async def check_timestamps( pres: indy proof request rev_reg_defs: rev reg defs by rev reg id, augmented with transaction times """ + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) msgs = [] now = int(time()) non_revoc_intervals = indy_proof_req2non_revoc_intervals(pres_req) - LOGGER.debug(f">>> got non-revoc intervals: {non_revoc_intervals}") + _logger.debug(f">>> got non-revoc intervals: {non_revoc_intervals}") # timestamp for irrevocable credential cred_defs = [] for index, ident in enumerate(pres["identifiers"]): - LOGGER.debug(f">>> got (index, ident): ({index},{ident})") + _logger.debug(f">>> got (index, ident): ({index},{ident})") cred_def_id = ident["cred_def_id"] multitenant_mgr = profile.inject_or(BaseMultitenantManager) if multitenant_mgr: @@ -190,8 +195,8 @@ async def check_timestamps( if (timestamp is not None) ^ bool( non_revoc_intervals.get(uuid) ): - LOGGER.debug(f">>> uuid: {uuid}") - LOGGER.debug( + _logger.debug(f">>> uuid: {uuid}") + _logger.debug( f">>> revealed_attrs[uuid]: {revealed_attrs[uuid]}" ) raise ValueError( @@ -208,7 +213,7 @@ async def check_timestamps( f"{PresVerifyMsg.TSTMP_OUT_NON_REVOC_INTRVAL.value}::" f"{uuid}" ) - LOGGER.info( + _logger.info( f"Timestamp {timestamp} from ledger for item" f"{uuid} falls outside non-revocation interval " f"{non_revoc_intervals[uuid]}" @@ -249,7 +254,7 @@ async def check_timestamps( f"{PresVerifyMsg.TSTMP_OUT_NON_REVOC_INTRVAL.value}::" f"{uuid}" ) - LOGGER.warning( + _logger.warning( f"Timestamp {timestamp} from ledger for item" f"{uuid} falls outside non-revocation interval " f"{non_revoc_intervals[uuid]}" @@ -278,7 +283,7 @@ async def check_timestamps( msgs.append( f"{PresVerifyMsg.TSTMP_OUT_NON_REVOC_INTRVAL.value}::" f"{uuid}" ) - LOGGER.warning( + _logger.warning( f"Best-effort timestamp {timestamp} " "from ledger falls outside non-revocation interval " f"{non_revoc_intervals[uuid]}" diff --git a/aries_cloudagent/ledger/indy.py b/aries_cloudagent/ledger/indy.py index 34e216339a..056b5a80d3 100644 --- a/aries_cloudagent/ledger/indy.py +++ b/aries_cloudagent/ledger/indy.py @@ -16,6 +16,7 @@ from ..cache.base import BaseCache from ..config.base import BaseInjector, BaseProvider, BaseSettings +from ..config.logging import get_logger_inst from ..indy.sdk.error import IndyErrorHandler from ..storage.base import StorageRecord from ..storage.indy import IndySdkStorage @@ -276,6 +277,10 @@ def __init__( """ self.pool = pool self.profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property def pool_handle(self): @@ -1057,7 +1062,7 @@ async def get_revoc_reg_def(self, revoc_reg_id: str) -> dict: found_def["txnTime"] = json.loads(response_json)["result"]["txnTime"] except IndyError as e: - LOGGER.error( + self._logger.error( f"get_revoc_reg_def failed with revoc_reg_id={revoc_reg_id} - " f"{e.error_code}: {getattr(e, 'message', '[no message]')}" ) @@ -1081,7 +1086,7 @@ async def get_revoc_reg_entry(self, revoc_reg_id: str, timestamp: int): ledger_timestamp, ) = await indy.ledger.parse_get_revoc_reg_response(response_json) except IndyError as e: - LOGGER.error( + self._logger.error( f"get_revoc_reg_entry failed with revoc_reg_id={revoc_reg_id} - " f"{e.error_code}: {getattr(e, 'message', '[no message]')}" ) diff --git a/aries_cloudagent/ledger/multiple_ledger/indy_manager.py b/aries_cloudagent/ledger/multiple_ledger/indy_manager.py index cf379b7913..edd3889e5c 100644 --- a/aries_cloudagent/ledger/multiple_ledger/indy_manager.py +++ b/aries_cloudagent/ledger/multiple_ledger/indy_manager.py @@ -1,4 +1,5 @@ """Multiple IndySdkLedger Manager.""" + import asyncio import concurrent.futures import logging @@ -8,6 +9,7 @@ from typing import Optional, Tuple, Mapping, List from ...cache.base import BaseCache +from ...config.logging import get_logger_inst from ...core.profile import Profile from ...ledger.base import BaseLedger from ...ledger.error import LedgerError @@ -22,8 +24,6 @@ from .base_manager import BaseMultipleLedgerManager, MultipleLedgerManagerError -LOGGER = logging.getLogger(__name__) - class MultiIndyLedgerManager(BaseMultipleLedgerManager): """Multiple Indy SDK Ledger Manager.""" @@ -53,6 +53,10 @@ def __init__( self.endorser_map = endorser_map self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=5) self.cache_ttl = cache_ttl + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def get_write_ledgers(self) -> List[str]: """Return the write IndySdkLedger instance.""" @@ -124,7 +128,7 @@ async def _get_ledger_by_did( response = json.loads(response_json) data = response.get("result", {}).get("data") if not data: - LOGGER.warning(f"Did {did} not posted to ledger {ledger_id}") + self._logger.warning(f"Did {did} not posted to ledger {ledger_id}") return None if isinstance(data, str): data = json.loads(data) @@ -132,7 +136,7 @@ async def _get_ledger_by_did( expected_value=prepare_for_state_read(response), proof_nodes=get_proof_nodes(response), ): - LOGGER.warning( + self._logger.warning( f"State Proof validation failed for Did {did} " f"and ledger {ledger_id}" ) @@ -141,13 +145,13 @@ async def _get_ledger_by_did( return (ledger_id, indy_sdk_ledger, True) return (ledger_id, indy_sdk_ledger, False) except asyncio.TimeoutError: - LOGGER.exception( + self._logger.exception( f"get-nym request timedout for Did {did} and " f"ledger {ledger_id}, reply not received within 10 sec" ) return None except LedgerError as err: - LOGGER.error( + self._logger.error( "Exception when building and submitting get-nym request, " f"for Did {did} and ledger {ledger_id}, {err}" ) diff --git a/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py b/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py index 8d2c51c576..10cc2b4d35 100644 --- a/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py +++ b/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py @@ -8,6 +8,7 @@ from typing import Optional, Tuple, Mapping, List from ...cache.base import BaseCache +from ...config.logging import get_logger_inst from ...core.profile import Profile from ...ledger.base import BaseLedger from ...ledger.error import LedgerError @@ -22,8 +23,6 @@ from .base_manager import BaseMultipleLedgerManager, MultipleLedgerManagerError -LOGGER = logging.getLogger(__name__) - class MultiIndyVDRLedgerManager(BaseMultipleLedgerManager): """Multiple Indy VDR Ledger Manager.""" @@ -53,6 +52,10 @@ def __init__( self.endorser_map = endorser_map self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=5) self.cache_ttl = cache_ttl + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def get_write_ledgers(self) -> List[str]: """Return the write IndyVdrLedger instance.""" @@ -130,7 +133,7 @@ async def _get_ledger_by_did( else: data = response.get("data") if not data: - LOGGER.warning(f"Did {did} not posted to ledger {ledger_id}") + self._logger.warning(f"Did {did} not posted to ledger {ledger_id}") return None if isinstance(data, str): data = json.loads(data) @@ -138,7 +141,7 @@ async def _get_ledger_by_did( expected_value=prepare_for_state_read(response), proof_nodes=get_proof_nodes(response), ): - LOGGER.warning( + self._logger.warning( f"State Proof validation failed for Did {did} " f"and ledger {ledger_id}" ) @@ -147,13 +150,13 @@ async def _get_ledger_by_did( return (ledger_id, indy_vdr_ledger, True) return (ledger_id, indy_vdr_ledger, False) except asyncio.TimeoutError: - LOGGER.exception( + self._logger.exception( f"get-nym request timedout for Did {did} and " f"ledger {ledger_id}, reply not received within 10 sec" ) return None except LedgerError as err: - LOGGER.error( + self._logger.error( "Exception when building and submitting get-nym request, " f"for Did {did} and ledger {ledger_id}, {err}" ) diff --git a/aries_cloudagent/ledger/routes.py b/aries_cloudagent/ledger/routes.py index 46aa2612fe..68c357be20 100644 --- a/aries_cloudagent/ledger/routes.py +++ b/aries_cloudagent/ledger/routes.py @@ -15,6 +15,7 @@ from marshmallow import fields, validate from ..admin.request_context import AdminRequestContext +from ..config.logging import get_logger_inst from ..connections.models.conn_record import ConnRecord from ..messaging.models.base import BaseModelError from ..messaging.models.openapi import OpenAPISchema @@ -67,8 +68,6 @@ ) from .util import notify_register_did_event -LOGGER = logging.getLogger(__name__) - class LedgerModulesResultSchema(OpenAPISchema): """Schema for the modules endpoint.""" @@ -655,7 +654,11 @@ async def ledger_accept_taa(request: web.BaseRequest): raise web.HTTPForbidden(reason=reason) accept_input = await request.json() - LOGGER.info(">>> accepting TAA with: %s", accept_input) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.info(">>> accepting TAA with: %s", accept_input) async with ledger: try: taa_info = await ledger.get_txn_author_agreement() @@ -663,14 +666,14 @@ async def ledger_accept_taa(request: web.BaseRequest): raise web.HTTPBadRequest( reason=f"Ledger {ledger.pool_name} TAA not available" ) - LOGGER.info("TAA on ledger: ", taa_info) + _logger.info("TAA on ledger: ", taa_info) # this is a bit of a hack, but the "\ufeff" code is included in the # ledger TAA and digest calculation, so it needs to be included in the # TAA text that the user is accepting # (if you copy the TAA text using swagger it won't include this character) if taa_info["taa_record"]["text"].startswith("\ufeff"): if not accept_input["text"].startswith("\ufeff"): - LOGGER.info( + _logger.info( ">>> pre-pending -endian character to TAA acceptance text" ) accept_input["text"] = "\ufeff" + accept_input["text"] @@ -683,7 +686,7 @@ async def ledger_accept_taa(request: web.BaseRequest): ), } taa_record_digest = taa_record["digest"] - LOGGER.info(">>> accepting with digest: %s", taa_record_digest) + _logger.info(">>> accepting with digest: %s", taa_record_digest) await ledger.accept_txn_author_agreement( taa_record, accept_input["mechanism"] ) diff --git a/aries_cloudagent/multitenant/base.py b/aries_cloudagent/multitenant/base.py index c71eb8ac8c..17ce19d636 100644 --- a/aries_cloudagent/multitenant/base.py +++ b/aries_cloudagent/multitenant/base.py @@ -8,6 +8,7 @@ import jwt from ..config.injection_context import InjectionContext +from ..config.logging import get_logger_inst from ..core.error import BaseError from ..core.profile import Profile, ProfileSession from ..protocols.coordinate_mediation.v1_0.manager import ( @@ -23,8 +24,6 @@ from ..wallet.models.wallet_record import WalletRecord from .error import WalletKeyMissingError -LOGGER = logging.getLogger(__name__) - class MultitenantManagerError(BaseError): """Generic multitenant error.""" @@ -42,6 +41,10 @@ def __init__(self, profile: Profile): self._profile = profile if not profile: raise MultitenantManagerError("Missing profile") + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property @abstractmethod @@ -104,7 +107,7 @@ def get_webhook_urls( if dispatch_type == "both": webhook_urls = list(set(base_webhook_urls) | set(subwallet_webhook_urls)) if not webhook_urls: - LOGGER.warning( + self._logger.warning( "No webhook URLs in context configuration " f"nor wallet record {wallet_id}, but wallet record " f"configures dispatch type {dispatch_type}" @@ -112,7 +115,7 @@ def get_webhook_urls( elif dispatch_type == "default": webhook_urls = subwallet_webhook_urls if not webhook_urls: - LOGGER.warning( + self._logger.warning( f"No webhook URLs in nor wallet record {wallet_id}, but " f"wallet record configures dispatch type {dispatch_type}" ) diff --git a/aries_cloudagent/multitenant/cache.py b/aries_cloudagent/multitenant/cache.py index 1fb3f37e3c..ce9c75497c 100644 --- a/aries_cloudagent/multitenant/cache.py +++ b/aries_cloudagent/multitenant/cache.py @@ -5,6 +5,7 @@ from typing import Optional from weakref import WeakValueDictionary +from ..config.logging import get_logger_inst from ..core.profile import Profile LOGGER = logging.getLogger(__name__) @@ -54,8 +55,12 @@ def get(self, key: str) -> Optional[Profile]: """ value = self.profiles.get(key) if value: + _logger: logging.Logger = get_logger_inst( + profile=value, + logger_name=__name__, + ) if key not in self._cache: - LOGGER.debug( + _logger.debug( f"Rescuing profile {key} from eviction from cache; profile " "will be reinserted into cache" ) diff --git a/aries_cloudagent/multitenant/route_manager.py b/aries_cloudagent/multitenant/route_manager.py index 954b3c98f9..c7b2e76078 100644 --- a/aries_cloudagent/multitenant/route_manager.py +++ b/aries_cloudagent/multitenant/route_manager.py @@ -5,6 +5,7 @@ from typing import List, Optional, Tuple from ..connections.models.conn_record import ConnRecord +from ..config.logging import get_logger_inst from ..core.profile import Profile from ..messaging.responder import BaseResponder from ..protocols.coordinate_mediation.v1_0.manager import MediationManager @@ -48,8 +49,12 @@ async def _route_for_key( skip_if_exists: bool = False, replace_key: Optional[str] = None, ): + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) wallet_id = profile.settings["wallet.id"] - LOGGER.info( + _logger.info( f"Add route record for recipient {recipient_key} to wallet {wallet_id}" ) routing_mgr = RoutingManager(self.root_profile) @@ -134,7 +139,11 @@ async def connection_from_recipient_key( for sub wallets, we check the sub wallet's connections before the base wallet. """ - LOGGER.debug("Retrieving connection for recipient key for multitenant wallet") + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) + _logger.debug("Retrieving connection for recipient key for multitenant wallet") manager = profile.inject(BaseMultitenantManager) profile_to_search = ( await manager.get_profile_for_key( diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py index 905e039ce8..59387be24a 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py @@ -1,5 +1,8 @@ """Action menu request message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -20,10 +23,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - self._logger.debug("MenuRequestHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("MenuRequestHandler called with context %s", context) assert isinstance(context.message, MenuRequest) - self._logger.info("Received action menu request") + _logger.info("Received action menu request") service: BaseMenuService = context.inject_or(BaseMenuService) if service: diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py index 5e38bc90f3..21cb8a65ec 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py @@ -1,5 +1,8 @@ """Action menu perform request message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -20,10 +23,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - self._logger.debug("PerformHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("PerformHandler called with context %s", context) assert isinstance(context.message, Perform) - self._logger.info("Received action menu perform request") + _logger.info("Received action menu perform request") service: BaseMenuService = context.inject_or(BaseMenuService) if service: diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/routes.py b/aries_cloudagent/protocols/actionmenu/v1_0/routes.py index c9c94af9d6..53dcd2a1cc 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/routes.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/routes.py @@ -8,6 +8,7 @@ from marshmallow import fields from ....admin.request_context import AdminRequestContext +from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord from ....messaging.models.base import BaseModelError from ....messaging.models.openapi import OpenAPISchema @@ -19,8 +20,6 @@ from .models.menu_option import MenuOptionSchema from .util import MENU_RECORD_TYPE, retrieve_connection_menu, save_connection_menu -LOGGER = logging.getLogger(__name__) - class ActionMenuModulesResultSchema(OpenAPISchema): """Schema for the modules endpoint.""" @@ -180,12 +179,15 @@ async def actionmenu_request(request: web.BaseRequest): context: AdminRequestContext = request["context"] connection_id = request.match_info["conn_id"] outbound_handler = request["outbound_message_router"] - + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) try: async with context.profile.session() as session: connection = await ConnRecord.retrieve_by_id(session, connection_id) except StorageNotFoundError as err: - LOGGER.debug("Connection not found for action menu request: %s", connection_id) + _logger.debug("Connection not found for action menu request: %s", connection_id) raise web.HTTPNotFound(reason=err.roll_up) from err if connection.is_ready: @@ -211,18 +213,22 @@ async def actionmenu_send(request: web.BaseRequest): connection_id = request.match_info["conn_id"] outbound_handler = request["outbound_message_router"] menu_json = await request.json() - LOGGER.debug("Received send-menu request: %s %s", connection_id, menu_json) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("Received send-menu request: %s %s", connection_id, menu_json) try: msg = Menu.deserialize(menu_json["menu"]) except BaseModelError as err: - LOGGER.exception("Exception deserializing menu: %s", err.roll_up) + _logger.exception("Exception deserializing menu: %s", err.roll_up) raise web.HTTPBadRequest(reason=err.roll_up) from err try: async with context.profile.session() as session: connection = await ConnRecord.retrieve_by_id(session, connection_id) except StorageNotFoundError as err: - LOGGER.debug( + _logger.debug( "Connection not found for action menu send request: %s", connection_id ) raise web.HTTPNotFound(reason=err.roll_up) from err diff --git a/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py b/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py index 93bd91760f..cbc167cde3 100644 --- a/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py +++ b/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py @@ -1,5 +1,8 @@ """Basic message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -19,10 +22,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - self._logger.debug("BasicMessageHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("BasicMessageHandler called with context %s", context) assert isinstance(context.message, BasicMessage) - self._logger.info("Received basic message: %s", context.message.content) + _logger.info("Received basic message: %s", context.message.content) body = context.message.content meta = {"content": body} diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py index 73efd9ecf8..02514506af 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py @@ -1,8 +1,12 @@ """Connection request handler.""" +import logging + +from .....config.logging import get_logger_inst from .....connections.models.conn_record import ConnRecord from .....messaging.base_handler import BaseHandler, BaseResponder, RequestContext from ....coordinate_mediation.v1_0.manager import MediationManager + from ..manager import ConnectionManager, ConnectionManagerError from ..messages.connection_request import ConnectionRequest from ..messages.problem_report import ConnectionProblemReport @@ -18,8 +22,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - - self._logger.debug(f"ConnectionRequestHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"ConnectionRequestHandler called with context {context}") assert isinstance(context.message, ConnectionRequest) profile = context.profile @@ -47,9 +54,9 @@ async def handle(self, context: RequestContext, responder: BaseResponder): response, connection_id=connection.connection_id ) else: - self._logger.debug("Connection request will await acceptance") + _logger.debug("Connection request will await acceptance") except ConnectionManagerError as e: - self._logger.exception("Error receiving connection request") + _logger.exception("Error receiving connection request") if e.error_code: targets = None if context.message.connection and context.message.connection.did_doc: @@ -59,9 +66,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message_receipt.recipient_verkey, ) except ConnectionManagerError: - self._logger.exception( - "Error parsing DIDDoc for problem report" - ) + _logger.exception("Error parsing DIDDoc for problem report") await responder.send_reply( ConnectionProblemReport(problem_code=e.error_code, explain=str(e)), target_list=targets, diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py index 5bb79269db..9215e5d4e3 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py @@ -1,5 +1,8 @@ """Connection response handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -22,7 +25,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - self._logger.debug(f"ConnectionResponseHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"ConnectionResponseHandler called with context {context}") assert isinstance(context.message, ConnectionResponse) profile = context.profile @@ -32,7 +39,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.message_receipt ) except ConnectionManagerError as e: - self._logger.exception("Error receiving connection response") + _logger.exception("Error receiving connection response") if e.error_code: targets = None if context.message.connection and context.message.connection.did_doc: @@ -42,9 +49,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message_receipt.recipient_verkey, ) except ConnectionManagerError: - self._logger.exception( - "Error parsing DIDDoc for problem report" - ) + _logger.exception("Error parsing DIDDoc for problem report") await responder.send_reply( ConnectionProblemReport(problem_code=e.error_code, explain=str(e)), target_list=targets, diff --git a/aries_cloudagent/protocols/connections/v1_0/manager.py b/aries_cloudagent/protocols/connections/v1_0/manager.py index fe33e1dac3..8e30d81e8c 100644 --- a/aries_cloudagent/protocols/connections/v1_0/manager.py +++ b/aries_cloudagent/protocols/connections/v1_0/manager.py @@ -5,6 +5,7 @@ from ....core.oob_processor import OobMessageProcessor +from ....config.logging import get_logger_inst from ....connections.base_manager import BaseConnectionManager from ....connections.models.conn_record import ConnRecord from ....core.error import BaseError @@ -40,7 +41,10 @@ def __init__(self, profile: Profile): profile: The profile for this connection manager """ self._profile = profile - self._logger = logging.getLogger(__name__) + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) super().__init__(self._profile) @property diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py index de00566498..6549d48a25 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py @@ -1,6 +1,7 @@ """Handler for keylist message.""" import logging +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -10,17 +11,16 @@ from ..models.mediation_record import MediationRecord -LOG = logging.getLogger(__name__) - - class KeylistHandler(BaseHandler): """Handler for keylist message.""" async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist message.""" - self._logger.debug( - "%s called with context %s", self.__class__.__name__, context + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, Keylist) if not context.connection_ready: @@ -32,11 +32,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): session, context.connection_record.connection_id ) except StorageNotFoundError as err: - LOG.warning( + _logger.warning( "Received keylist from connection that is not acting as mediator: %s", err, ) return # TODO verify our keylist matches? - LOG.info("Keylist received: %s", context.message) + _logger.info("Keylist received: %s", context.message) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py index 7d47296b64..dabb5a75a8 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py @@ -1,5 +1,8 @@ """Handler for keylist-query message.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -16,9 +19,11 @@ class KeylistQueryHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist-query message.""" - self._logger.debug( - "%s called with context %s", self.__class__.__name__, context + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, KeylistQuery) if not context.connection_ready: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py index 20c63a5e15..050924b926 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py @@ -1,5 +1,8 @@ """Handler for keylist-update messages.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -16,9 +19,11 @@ class KeylistUpdateHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist-update messages.""" - self._logger.debug( - "%s called with context %s", self.__class__.__name__, context + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, KeylistUpdate) if not context.connection_ready: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py index d2c33704d8..95da6ea67a 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py @@ -1,5 +1,8 @@ """Handler for keylist-update-response message.""" +import logging + +from .....config.logging import get_logger_inst from .....core.profile import Profile from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -16,9 +19,11 @@ class KeylistUpdateResponseHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist-update-response message.""" - self._logger.debug( - "%s called with context %s", self.__class__.__name__, context + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, KeylistUpdateResponse) if not context.connection_ready: @@ -36,8 +41,12 @@ async def notify_keylist_updated( self, profile: Profile, connection_id: str, response: KeylistUpdateResponse ): """Notify of keylist update response received.""" + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) route_manager = profile.inject(RouteManager) - self._logger.debug( + _logger.debug( "Retrieving connection ID from route manager of type %s", type(route_manager).__name__, ) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py index 7a27a8fdce..ff8c686237 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py @@ -1,5 +1,8 @@ """Handler for mediate-deny message.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -15,9 +18,11 @@ class MediationDenyHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle mediate-deny message.""" - self._logger.debug( - "%s called with context %s", self.__class__.__name__, context + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, MediationDeny) if not context.connection_ready: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py index fc597b63c7..2d5abcaac0 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py @@ -1,5 +1,8 @@ """Handler for mediate-grant message.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -16,9 +19,11 @@ class MediationGrantHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle mediate-grant message.""" - self._logger.debug( - "%s called with context %s", self.__class__.__name__, context + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, MediationGrant) if not context.connection_ready: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py index fedd7da258..489c83ac29 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py @@ -1,5 +1,8 @@ """Handler for mediate-request message.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -14,9 +17,11 @@ class MediationRequestHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle mediate-request message.""" - self._logger.debug( - "%s called with context %s", self.__class__.__name__, context + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, MediationRequest) if not context.connection_ready: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py index 8a5a1143ec..a1834c9397 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py @@ -3,6 +3,7 @@ import logging from typing import Dict, Optional, Sequence, Tuple +from ....config.logging import get_logger_inst from ....core.error import BaseError from ....core.profile import Profile, ProfileSession from ....storage.base import BaseStorage @@ -28,8 +29,6 @@ from .models.mediation_record import MediationRecord from .normalization import normalize_from_did_key -LOGGER = logging.getLogger(__name__) - class MediationManagerError(BaseError): """Generic Mediation error.""" @@ -67,6 +66,10 @@ def __init__(self, profile: Profile): self._profile = profile if not profile: raise MediationManagerError("Missing profile") + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) # Role: Server {{{ @@ -580,7 +583,7 @@ async def store_update_results( for updated in results: if updated.result != KeylistUpdated.RESULT_SUCCESS: # TODO better handle different results? - LOGGER.warning( + self._logger.warning( "Keylist update failure: %s(%s): %s", updated.action, updated.recipient_key, @@ -614,13 +617,13 @@ async def store_update_results( }, ) except StorageNotFoundError as err: - LOGGER.error( + self._logger.error( "No route found while processing keylist update response: %s", err, ) else: if len(records) > 1: - LOGGER.error( + self._logger.error( f"Too many ({len(records)}) routes found " "while processing keylist update response" ) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py index 990252cd5a..1915fe58e6 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py @@ -8,6 +8,7 @@ import logging from typing import List, Optional, Tuple +from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -23,9 +24,6 @@ from .normalization import normalize_from_did_key -LOGGER = logging.getLogger(__name__) - - class RouteManagerError(Exception): """Raised on error from route manager.""" @@ -129,7 +127,11 @@ async def route_connection_as_invitee( mediation_record: Optional[MediationRecord] = None, ) -> Optional[KeylistUpdate]: """Set up routing for a new connection when we are the invitee.""" - LOGGER.debug("Routing connection as invitee") + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) + _logger.debug("Routing connection as invitee") my_info = await self.get_or_create_my_did(profile, conn_record) return await self._route_for_key( profile, my_info.verkey, mediation_record, skip_if_exists=True @@ -142,7 +144,11 @@ async def route_connection_as_inviter( mediation_record: Optional[MediationRecord] = None, ) -> Optional[KeylistUpdate]: """Set up routing for a new connection when we are the inviter.""" - LOGGER.debug("Routing connection as inviter") + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) + _logger.debug("Routing connection as inviter") my_info = await self.get_or_create_my_did(profile, conn_record) replace_key = conn_record.invitation_key diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py index 72122aa62f..754064f1b2 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py @@ -1,5 +1,8 @@ """Connection complete handler under RFC 23 (DID exchange).""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -20,7 +23,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - self._logger.debug(f"DIDXCompleteHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"DIDXCompleteHandler called with context {context}") assert isinstance(context.message, DIDXComplete) profile = context.profile @@ -29,4 +36,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): await mgr.accept_complete(context.message, context.message_receipt) except DIDXManagerError: # no corresponding request: no targets to send problem report; log and quit - self._logger.exception("Error receiving connection complete") + _logger.exception("Error receiving connection complete") diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py index b4b85eb1dc..ee8b8b29cc 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py @@ -3,6 +3,9 @@ from aries_cloudagent.protocols.didexchange.v1_0.messages.problem_report import ( DIDXProblemReport, ) +import logging + +from .....config.logging import get_logger_inst from .....connections.models.conn_record import ConnRecord from .....messaging.base_handler import BaseHandler, BaseResponder, RequestContext from ....coordinate_mediation.v1_0.manager import MediationManager @@ -20,8 +23,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - - self._logger.debug(f"DIDXRequestHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"DIDXRequestHandler called with context {context}") assert isinstance(context.message, DIDXRequest) profile = context.profile @@ -59,10 +65,10 @@ async def handle(self, context: RequestContext, responder: BaseResponder): async with context.session() as session: await conn_rec.save(session, reason="Sent connection response") else: - self._logger.debug("DID exchange request will await acceptance") + _logger.debug("DID exchange request will await acceptance") except DIDXManagerError as e: - self._logger.exception("Error receiving RFC 23 connection request") + _logger.exception("Error receiving RFC 23 connection request") if e.error_code: targets = None if context.message.did_doc_attach: @@ -72,9 +78,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message_receipt.recipient_verkey, ) except DIDXManagerError: - self._logger.exception( - "Error parsing DIDDoc for problem report" - ) + _logger.exception("Error parsing DIDDoc for problem report") await responder.send_reply( DIDXProblemReport( description={"en": e.message, "code": e.error_code} diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py index c2c094320a..73f3f84f8b 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py @@ -3,6 +3,9 @@ from aries_cloudagent.protocols.didexchange.v1_0.messages.problem_report import ( DIDXProblemReport, ) +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -25,7 +28,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - self._logger.debug(f"DIDXResponseHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"DIDXResponseHandler called with context {context}") assert isinstance(context.message, DIDXResponse) profile = context.profile @@ -35,7 +42,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.message_receipt ) except DIDXManagerError as e: - self._logger.exception("Error receiving DID exchange response") + _logger.exception("Error receiving DID exchange response") if e.error_code: targets = None if context.message.did_doc_attach: @@ -45,9 +52,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message_receipt.recipient_verkey, ) except DIDXManagerError: - self._logger.exception( - "Error parsing DIDDoc for problem report" - ) + _logger.exception("Error parsing DIDDoc for problem report") await responder.send_reply( DIDXProblemReport( description={"en": e.message, "code": e.error_code} diff --git a/aries_cloudagent/protocols/didexchange/v1_0/manager.py b/aries_cloudagent/protocols/didexchange/v1_0/manager.py index 0db2702e51..2aefdd5dca 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/manager.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/manager.py @@ -8,6 +8,7 @@ from pydid import BaseDIDDocument as ResolvedDocument from pydid import DIDCommService +from ....config.logging import get_logger_inst from ....connections.base_manager import BaseConnectionManager from ....connections.models.conn_record import ConnRecord from ....connections.models.diddoc import DIDDoc @@ -54,7 +55,10 @@ def __init__(self, profile: Profile): profile: The profile for this did exchange manager """ self._profile = profile - self._logger = logging.getLogger(__name__) + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) super().__init__(self._profile) @property diff --git a/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py b/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py index 7c5a313fc4..b7c2dc662e 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py +++ b/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py @@ -1,5 +1,8 @@ """Handler for incoming disclose messages.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -16,7 +19,11 @@ class DiscloseHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - self._logger.debug("DiscloseHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("DiscloseHandler called with context %s", context) assert isinstance(context.message, Disclose) if not context.connection_ready: raise HandlerException( diff --git a/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py b/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py index 0336b01351..02f53f31f0 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py +++ b/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py @@ -1,5 +1,8 @@ """Handler for incoming query messages.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -15,7 +18,11 @@ class QueryHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - self._logger.debug("QueryHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("QueryHandler called with context %s", context) assert isinstance(context.message, Query) profile = context.profile mgr = V10DiscoveryMgr(profile) diff --git a/aries_cloudagent/protocols/discovery/v1_0/manager.py b/aries_cloudagent/protocols/discovery/v1_0/manager.py index c01093f631..632d4f8565 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/manager.py +++ b/aries_cloudagent/protocols/discovery/v1_0/manager.py @@ -5,6 +5,7 @@ from typing import Optional +from ....config.logging import get_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....core.protocol_registry import ProtocolRegistry @@ -30,7 +31,10 @@ def __init__(self, profile: Profile): profile: The profile for this manager """ self._profile = profile - self._logger = logging.getLogger(__name__) + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property def profile(self) -> Profile: diff --git a/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py b/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py index adab14bf3e..e3822f82d1 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py +++ b/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py @@ -1,5 +1,8 @@ """Handler for incoming disclose messages.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -16,7 +19,11 @@ class DisclosuresHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - self._logger.debug("DiscloseHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("DiscloseHandler called with context %s", context) assert isinstance(context.message, Disclosures) if not context.connection_ready: raise HandlerException( diff --git a/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py b/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py index e970ad0c6f..1636246800 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py +++ b/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py @@ -1,5 +1,8 @@ """Handler for incoming queries messages.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -15,7 +18,11 @@ class QueriesHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - self._logger.debug("QueryHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("QueryHandler called with context %s", context) assert isinstance(context.message, Queries) profile = context.profile mgr = V20DiscoveryMgr(profile) diff --git a/aries_cloudagent/protocols/discovery/v2_0/manager.py b/aries_cloudagent/protocols/discovery/v2_0/manager.py index 05609e3c09..7c71c4489f 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/manager.py +++ b/aries_cloudagent/protocols/discovery/v2_0/manager.py @@ -5,6 +5,7 @@ from typing import Tuple, Optional, Sequence +from ....config.logging import get_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....core.protocol_registry import ProtocolRegistry @@ -31,7 +32,10 @@ def __init__(self, profile: Profile): profile: The profile for this manager """ self._profile = profile - self._logger = logging.getLogger(__name__) + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property def profile(self) -> Profile: diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py index 88dff4f6e8..0d5865e140 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py @@ -1,5 +1,8 @@ """Endorsed transaction response handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -22,8 +25,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( f"EndorsedTransactionResponseHandler called with context {context}" ) assert isinstance(context.message, EndorsedTransactionResponse) @@ -36,7 +42,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): try: transaction = await mgr.receive_endorse_response(context.message) except TransactionManagerError: - self._logger.exception("Error receiving endorsed transaction response") + _logger.exception("Error receiving endorsed transaction response") # Automatically write transaction if flag is set if context.settings.get("endorser.auto_write"): @@ -51,4 +57,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): connection_id=transaction.connection_id, ) except (StorageError, TransactionManagerError) as err: - self._logger.exception(err) + _logger.exception(err) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py index 46da51853e..ff8229fd44 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py @@ -1,5 +1,8 @@ """Refused transaction response handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,8 +24,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( f"RefusedTransactionResponseHandler called with context {context}" ) assert isinstance(context.message, RefusedTransactionResponse) @@ -34,4 +40,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): try: await mgr.receive_refuse_response(context.message) except TransactionManagerError: - self._logger.exception("Error receiving refused transaction response") + _logger.exception("Error receiving refused transaction response") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py index 0803a7216b..51d9d7f7c9 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py @@ -1,5 +1,8 @@ """Transaction acknowledgement message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,8 +24,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( f"TransactionAcknowledgementHandler called with context {context}" ) assert isinstance(context.message, TransactionAcknowledgement) @@ -36,4 +42,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.connection_record.connection_id ) except TransactionManagerError: - self._logger.exception("Error receiving transaction acknowledgement") + _logger.exception("Error receiving transaction acknowledgement") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py index 0154b4e723..7a18f25313 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py @@ -1,5 +1,8 @@ """Cancel transaction request handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,8 +24,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - - self._logger.debug(f"TransactionCancelHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"TransactionCancelHandler called with context {context}") assert isinstance(context.message, CancelTransaction) if not context.connection_ready: @@ -34,4 +40,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.connection_record.connection_id ) except TransactionManagerError: - self._logger.exception("Error receiving cancel transaction request") + _logger.exception("Error receiving cancel transaction request") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py index 35e1d50bed..97b90c3797 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py @@ -1,5 +1,8 @@ """Transaction Job to send handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -20,8 +23,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - - self._logger.debug(f"TransactionJobToSendHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"TransactionJobToSendHandler called with context {context}") assert isinstance(context.message, TransactionJobToSend) mgr = TransactionManager(context.profile) @@ -30,4 +36,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.message_receipt ) except TransactionManagerError: - self._logger.exception("Error receiving transaction jobs") + _logger.exception("Error receiving transaction jobs") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py index bc60a9a69b..bf2f6740fa 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py @@ -1,5 +1,8 @@ """Transaction request handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -24,8 +27,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - - self._logger.debug(f"TransactionRequestHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"TransactionRequestHandler called with context {context}") assert isinstance(context.message, TransactionRequest) if not context.connection_ready: @@ -37,7 +43,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.connection_record.connection_id ) except TransactionManagerError as err: - self._logger.exception(err) + _logger.exception(err) return # Automatically endorse transaction if flag is set @@ -56,4 +62,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): connection_id=transaction.connection_id, ) except (StorageError, TransactionManagerError) as err: - self._logger.exception(err) + _logger.exception(err) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py index 268b3f85f2..a2bc62b22d 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py @@ -1,5 +1,8 @@ """Transaction resend handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,8 +24,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - - self._logger.debug(f"TransactionResendHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"TransactionResendHandler called with context {context}") assert isinstance(context.message, TransactionResend) if not context.connection_ready: @@ -34,4 +40,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.connection_record.connection_id ) except TransactionManagerError: - self._logger.exception("Error receiving resend transaction request") + _logger.exception("Error receiving resend transaction request") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py index 57c0b054e4..56b4ac157c 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py @@ -16,6 +16,7 @@ from ....admin.request_context import AdminRequestContext from ....connections.models.conn_record import ConnRecord +from ....config.logging import get_logger_inst from ....core.event_bus import Event, EventBus from ....core.profile import Profile from ....core.util import SHUTDOWN_EVENT_PATTERN, STARTUP_EVENT_PATTERN @@ -36,8 +37,6 @@ from .transaction_jobs import TransactionJob from .util import get_endorser_connection_id, is_author_role -LOGGER = logging.getLogger(__name__) - class TransactionListSchema(OpenAPISchema): """Result schema for transaction list.""" @@ -719,7 +718,10 @@ def register_events(event_bus: EventBus): async def on_startup_event(profile: Profile, event: Event): """Handle any events we need to support.""" - + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) # auto setup is only for authors if not is_author_role(profile): return @@ -796,7 +798,7 @@ async def on_startup_event(profile: Profile, event: Event): except Exception: # log the error, but continue - LOGGER.exception( + _logger.exception( "Error accepting endorser invitation/configuring endorser connection: %s", ) diff --git a/aries_cloudagent/protocols/introduction/v0_1/demo_service.py b/aries_cloudagent/protocols/introduction/v0_1/demo_service.py index 3f54dd6f8c..916c2fbe23 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/demo_service.py +++ b/aries_cloudagent/protocols/introduction/v0_1/demo_service.py @@ -3,6 +3,7 @@ import json import logging +from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.profile import ProfileSession from ....storage.base import ( @@ -16,8 +17,6 @@ from .messages.invitation import Invitation as IntroInvitation from .messages.invitation_request import InvitationRequest as IntroInvitationRequest -LOGGER = logging.getLogger(__name__) - class DemoIntroductionService(BaseIntroductionService): """Service handler for allowing connections to exchange invitations.""" @@ -110,7 +109,10 @@ async def return_invitation( outbound_handler: The outbound handler coroutine for sending a message """ thread_id = invitation._thread_id - + _logger: logging.Logger = get_logger_inst( + profile=session.profile, + logger_name=__name__, + ) tag_filter = {"target_connection_id": target_connection_id} storage = session.inject(BaseStorage) records = await storage.find_all_records( @@ -134,8 +136,8 @@ async def return_invitation( init_connection_id = row.tags["init_connection_id"] await outbound_handler(msg, connection_id=init_connection_id) found = True - LOGGER.info("Forwarded fwd-invitation to %s", init_connection_id) + _logger.info("Forwarded fwd-invitation to %s", init_connection_id) break if not found: - LOGGER.error("Could not forward invitation, no pending introduction found") + _logger.error("Could not forward invitation, no pending introduction found") diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py index 2b6cbeadba..35d0264ca5 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py @@ -1,5 +1,8 @@ """Handler for incoming forward invitation messages.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -18,7 +21,11 @@ class ForwardInvitationHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - self._logger.debug("ForwardInvitationHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("ForwardInvitationHandler called with context %s", context) assert isinstance(context.message, ForwardInvitation) if not context.connection_ready: @@ -33,7 +40,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): try: await connection_mgr.receive_invitation(context.message.invitation) except ConnectionManagerError as e: - self._logger.exception("Error receiving forward connection invitation") + _logger.exception("Error receiving forward connection invitation") await responder.send_reply( ProblemReport( description={ diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py index 3244d2e338..cff6cc9c44 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py @@ -1,5 +1,8 @@ """Handler for incoming invitation messages.""" +import logging + +from .....config.logging import get_logger_inst from typing import Optional from .....messaging.base_handler import ( BaseHandler, @@ -17,7 +20,11 @@ class InvitationHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - self._logger.debug("InvitationHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("InvitationHandler called with context %s", context) assert isinstance(context.message, IntroInvitation) if not context.connection_ready: diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py index c1d284c1f3..0e1658b0a0 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py @@ -1,5 +1,8 @@ """Handler for incoming invitation request messages.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -18,7 +21,11 @@ class InvitationRequestHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - self._logger.debug("InvitationRequestHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("InvitationRequestHandler called with context %s", context) assert isinstance(context.message, IntroInvitationRequest) if not context.connection_ready: diff --git a/aries_cloudagent/protocols/introduction/v0_1/routes.py b/aries_cloudagent/protocols/introduction/v0_1/routes.py index ed1e9ea226..7bea8dc82f 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/routes.py +++ b/aries_cloudagent/protocols/introduction/v0_1/routes.py @@ -9,13 +9,12 @@ from marshmallow import fields from ....admin.request_context import AdminRequestContext +from ....config.logging import get_logger_inst from ....messaging.models.openapi import OpenAPISchema from ....messaging.valid import UUID4_EXAMPLE from ....storage.error import StorageError from .base_service import BaseIntroductionService, IntroductionError -LOGGER = logging.getLogger(__name__) - class IntroModuleResponseSchema(OpenAPISchema): """Response schema for Introduction Module.""" @@ -60,8 +59,12 @@ async def introduction_start(request: web.BaseRequest): request: aiohttp request object """ - LOGGER.info("Introduction requested") context: AdminRequestContext = request["context"] + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.info("Introduction requested") outbound_handler = request["outbound_message_router"] init_connection_id = request.match_info["conn_id"] target_connection_id = request.query.get("target_connection_id") diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py index 1c7f2f7d87..ed7f310394 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py @@ -1,5 +1,8 @@ """Credential ack message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -21,10 +24,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - - self._logger.debug("CredentialAckHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("CredentialAckHandler called with context %s", context) assert isinstance(context.message, CredentialAck) - self._logger.info( + _logger.info( "Received credential ack message: %s", context.message.serialize(as_string=True), ) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py index 778a9985aa..801ff9d640 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py @@ -1,5 +1,8 @@ """Credential issue message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError from .....messaging.base_handler import BaseHandler, HandlerException @@ -27,10 +30,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) profile = context.profile - self._logger.debug("CredentialHandler called with context %s", context) + _logger.debug("CredentialHandler called with context %s", context) assert isinstance(context.message, CredentialIssue) - self._logger.info( + _logger.info( "Received credential message: %s", context.message.serialize(as_string=True) ) @@ -76,7 +83,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, ) as err: # treat failure to store as mangled on receipt hence protocol error - self._logger.exception("Error storing issued credential") + _logger.exception("Error storing issued credential") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py index f2e1b0e324..79261b4739 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py @@ -1,6 +1,8 @@ """Credential offer message handler.""" +import logging +from .....config.logging import get_logger_inst from .....wallet.util import default_did_from_verkey from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError @@ -30,10 +32,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) profile = context.profile - self._logger.debug("CredentialOfferHandler called with context %s", context) + _logger.debug("CredentialOfferHandler called with context %s", context) assert isinstance(context.message, CredentialOffer) - self._logger.info( + _logger.info( "Received credential offer message: %s", context.message.serialize(as_string=True), ) @@ -98,7 +104,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): LedgerError, StorageError, ) as err: - self._logger.exception("Error responding to credential offer") + _logger.exception("Error responding to credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py index 3936dece50..ba3b7104c1 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py @@ -1,5 +1,8 @@ """Credential problem report message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,7 +22,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( "Issue-credential v1.0 problem report handler called with context %s", context, ) @@ -42,6 +49,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.connection_record.connection_id, ) except (StorageError, StorageNotFoundError): - self._logger.exception( + _logger.exception( "Error processing issue-credential v1.0 problem report message" ) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py index 5b4ff0b1ce..5f015e3cf5 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py @@ -1,5 +1,8 @@ """Credential proposal message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -27,11 +30,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) profile = context.profile - self._logger.debug("CredentialProposalHandler called with context %s", context) + _logger.debug("CredentialProposalHandler called with context %s", context) assert isinstance(context.message, CredentialProposal) - self._logger.info( + _logger.info( "Received credential proposal message: %s", context.message.serialize(as_string=True), ) @@ -76,7 +83,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): LedgerError, StorageError, ) as err: - self._logger.exception("Error responding to credential proposal") + _logger.exception("Error responding to credential proposal") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py index 02794bca6f..239a899586 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py @@ -1,5 +1,8 @@ """Credential request message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError @@ -28,10 +31,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) profile = context.profile - self._logger.debug("CredentialRequestHandler called with context %s", context) + _logger.debug("CredentialRequestHandler called with context %s", context) assert isinstance(context.message, CredentialRequest) - self._logger.info( + _logger.info( "Received credential request message: %s", context.message.serialize(as_string=True), ) @@ -87,7 +94,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): LedgerError, StorageError, ) as err: - self._logger.exception("Error responding to credential request") + _logger.exception("Error responding to credential request") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( @@ -108,7 +115,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): perf_counter=r_time, ) else: - self._logger.warning( + _logger.warning( "Operation set for auto-issue but credential exchange record " f"{cred_ex_record.credential_exchange_id} " "has no attribute values" diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/manager.py b/aries_cloudagent/protocols/issue_credential/v1_0/manager.py index f0dabfedff..53a6b5e555 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/manager.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/manager.py @@ -7,6 +7,7 @@ from typing import Mapping, Optional, Tuple from ....cache.base import BaseCache +from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.error import BaseError from ....core.profile import Profile @@ -44,8 +45,6 @@ V10CredentialExchange, ) -LOGGER = logging.getLogger(__name__) - class CredentialManagerError(BaseError): """Credential error.""" @@ -61,6 +60,10 @@ def __init__(self, profile: Profile): profile: The profile instance for this credential manager """ self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property def profile(self) -> Profile: @@ -439,7 +442,7 @@ async def _create(): } if cred_ex_record.state == V10CredentialExchange.STATE_REQUEST_SENT: - LOGGER.warning( + self._logger.warning( "create_request called multiple times for v1.0 credential exchange: %s", cred_ex_record.credential_exchange_id, ) @@ -541,7 +544,7 @@ async def receive_request( "Indy issue credential format can't start from credential request" ) from None if cred_ex_record.state != V10CredentialExchange.STATE_OFFER_SENT: - LOGGER.error( + self._logger.error( "Skipping credential request; exchange state is %s (id=%s)", cred_ex_record.state, cred_ex_record.credential_exchange_id, @@ -580,7 +583,7 @@ async def issue_credential( credential_ser = None if cred_ex_record.credential: - LOGGER.warning( + self._logger.warning( "issue_credential called multiple times for v1.0 credential exchange %s", cred_ex_record.credential_exchange_id, ) @@ -625,7 +628,7 @@ async def issue_credential( for attempt in range(max(retries, 1)): if attempt > 0: - LOGGER.info( + self._logger.info( "Waiting 2s before retrying credential issuance " "for cred def '%s'", cred_def_id, @@ -830,7 +833,9 @@ async def store_credential( rev_reg_def=revoc_reg_def, ) except IndyHolderError as e: - LOGGER.error("Error storing credential: %s: %s", e.error_code, e.message) + self._logger.error( + "Error storing credential: %s: %s", e.error_code, e.message + ) raise e credential_json = await holder.get_credential(credential_id) @@ -884,7 +889,7 @@ async def send_credential_ack( txn, cred_ex_record.credential_exchange_id, for_update=True ) except StorageNotFoundError: - LOGGER.warning( + self._logger.warning( "Skipping credential exchange ack, record not found: '%s'", cred_ex_record.credential_exchange_id, ) @@ -894,7 +899,7 @@ async def send_credential_ack( cred_ex_record.state != V10CredentialExchange.STATE_CREDENTIAL_RECEIVED ): - LOGGER.warning( + self._logger.warning( "Skipping credential exchange ack, state is '%s' for record '%s'", cred_ex_record.state, cred_ex_record.credential_exchange_id, @@ -910,7 +915,7 @@ async def send_credential_ack( await cred_ex_record.delete_record(session) # all done: delete except StorageError: - LOGGER.exception( + self._logger.exception( "Error updating credential exchange" ) # holder still owes an ack: carry on @@ -921,7 +926,7 @@ async def send_credential_ack( connection_id=cred_ex_record.connection_id, ) else: - LOGGER.warning( + self._logger.warning( "Configuration has no BaseResponder: cannot ack credential on %s", cred_ex_record.thread_id, ) @@ -951,7 +956,7 @@ async def receive_credential_ack( ) ) except StorageNotFoundError: - LOGGER.warning( + self._logger.warning( "Skip ack message on credential exchange, record not found %s", message._thread_id, ) @@ -988,7 +993,7 @@ async def receive_problem_report( ) ) except StorageNotFoundError: - LOGGER.warning( + self._logger.warning( "Skip problem report on credential exchange, record not found %s", message._thread_id, ) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py b/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py index 2137d04986..d2d2804093 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py @@ -5,6 +5,7 @@ from marshmallow import fields, validate +from .....config.logging import get_logger_inst from .....core.profile import ProfileSession from .....indy.models.cred import IndyCredential, IndyCredentialSchema from .....indy.models.cred_abstract import IndyCredAbstract, IndyCredAbstractSchema @@ -24,8 +25,6 @@ from ..messages.credential_proposal import CredentialProposal, CredentialProposalSchema from . import UNENCRYPTED_TAGS -LOGGER = logging.getLogger(__name__) - class V10CredentialExchange(BaseExchangeRecord): """Represents an Aries#0036 credential exchange.""" @@ -206,7 +205,10 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - + _logger: logging.Logger = get_logger_inst( + profile=session.profile, + logger_name=__name__, + ) if self._last_state == state: # already done return @@ -222,7 +224,7 @@ async def save_error_state( log_override=log_override, ) except StorageError: - LOGGER.exception("Error saving credential exchange error state") + _logger.exception("Error saving credential exchange error state") # Override async def emit_event(self, session: ProfileSession, payload: Any = None): diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py index 183ecbf0a0..ea2d314bd5 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py @@ -5,6 +5,7 @@ from typing import Mapping, Tuple +from .....config.logging import get_logger_inst from .....core.error import BaseError from .....core.profile import Profile from .....messaging.decorators.attach_decorator import AttachDecorator @@ -35,6 +36,10 @@ def __init__(self, profile: Profile): super().__init__() self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property def profile(self) -> Profile: diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py index d6329cfcb6..e00f4f9944 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py @@ -47,8 +47,6 @@ from ..handler import CredFormatAttachment, V20CredFormatError, V20CredFormatHandler -LOGGER = logging.getLogger(__name__) - class IndyCredFormatHandler(V20CredFormatHandler): """Indy credential format handler.""" @@ -96,7 +94,7 @@ async def get_detail_record(self, cred_ex_id: str) -> V20CredExRecordIndy: ) if len(records) > 1: - LOGGER.warning( + self._logger.warning( "Cred ex id %s has %d %s detail records: should be 1", cred_ex_id, len(records), @@ -355,7 +353,7 @@ async def issue_credential( for attempt in range(max(retries, 1)): if attempt > 0: - LOGGER.info( + self._logger.info( "Waiting 2s before retrying credential issuance for cred def '%s'", cred_def_id, ) @@ -493,5 +491,7 @@ async def store_credential( session, reason="store credential v2.0", event=True ) except IndyHolderError as e: - LOGGER.error(f"Error storing credential: {e.error_code} - {e.message}") + self._logger.error( + f"Error storing credential: {e.error_code} - {e.message}" + ) raise e diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py index 02231f134d..3f18a40a4b 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py @@ -53,8 +53,6 @@ from .models.cred_detail_options import LDProofVCDetailOptions from .models.cred_detail import LDProofVCDetail, LDProofVCDetailSchema -LOGGER = logging.getLogger(__name__) - SUPPORTED_ISSUANCE_PROOF_PURPOSES = { CredentialIssuancePurpose.term, AuthenticationProofPurpose.term, @@ -134,7 +132,7 @@ async def get_detail_record(self, cred_ex_id: str) -> V20CredExRecordLDProof: ) if len(records) > 1: - LOGGER.warning( + self._logger.warning( "Cred ex id %s has %d %s detail records: should be 1", cred_ex_id, len(records), diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py index 26f5d10498..53914b1d6d 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py @@ -1,5 +1,8 @@ """Credential ack message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -21,10 +24,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - - self._logger.debug("V20CredAckHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("V20CredAckHandler called with context %s", context) assert isinstance(context.message, V20CredAck) - self._logger.info( + _logger.info( "Received v2.0 credential ack message: %s", context.message.serialize(as_string=True), ) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py index f3c5704252..7b6a4dbb37 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py @@ -1,5 +1,8 @@ """Credential issue message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError from .....messaging.base_handler import BaseHandler, HandlerException @@ -27,10 +30,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - - self._logger.debug("V20CredIssueHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("V20CredIssueHandler called with context %s", context) assert isinstance(context.message, V20CredIssue) - self._logger.info( + _logger.info( "Received v2.0 credential issue message: %s", context.message.serialize(as_string=True), ) @@ -75,7 +81,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): V20CredManagerError, ) as err: # treat failure to store as mangled on receipt hence protocol error - self._logger.exception("Error storing issued credential") + _logger.exception("Error storing issued credential") if cred_ex_record: async with context.profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py index 3184b79b55..9d6d30c172 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py @@ -1,5 +1,8 @@ """Credential offer message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....wallet.util import default_did_from_verkey from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError @@ -29,10 +32,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - - self._logger.debug("V20CredOfferHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("V20CredOfferHandler called with context %s", context) assert isinstance(context.message, V20CredOffer) - self._logger.info( + _logger.info( "Received v2.0 credential offer message: %s", context.message.serialize(as_string=True), ) @@ -93,7 +99,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, V20CredManagerError, ) as err: - self._logger.exception("Error responding to credential offer") + _logger.exception("Error responding to credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py index d3b85ecacd..400f42988c 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py @@ -1,5 +1,8 @@ """Credential problem report message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,7 +22,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( "Issue-credential v2.0 problem report handler called with context %s", context, ) @@ -42,6 +49,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.connection_record.connection_id, ) except (StorageError, StorageNotFoundError): - self._logger.exception( + _logger.exception( "Error processing issue-credential v2.0 problem report message" ) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py index 4ff09f70aa..d1f55e4046 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py @@ -1,5 +1,8 @@ """Credential proposal message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -27,10 +30,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - - self._logger.debug("V20CredProposalHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("V20CredProposalHandler called with context %s", context) assert isinstance(context.message, V20CredProposal) - self._logger.info( + _logger.info( "Received v2.0 credential proposal message: %s", context.message.serialize(as_string=True), ) @@ -73,7 +79,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, V20CredManagerError, ) as err: - self._logger.exception("Error responding to credential proposal") + _logger.exception("Error responding to credential proposal") async with profile.session() as session: await cred_ex_record.save_error_state( session, diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py index ecf0d6fb15..3fb43d54d9 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py @@ -1,5 +1,8 @@ """Credential request message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError @@ -28,10 +31,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - - self._logger.debug("V20CredRequestHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("V20CredRequestHandler called with context %s", context) assert isinstance(context.message, V20CredRequest) - self._logger.info( + _logger.info( "Received v2.0 credential request message: %s", context.message.serialize(as_string=True), ) @@ -84,7 +90,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, V20CredManagerError, ) as err: - self._logger.exception(err) + _logger.exception(err) async with profile.session() as session: await cred_ex_record.save_error_state( session, diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/manager.py b/aries_cloudagent/protocols/issue_credential/v2_0/manager.py index fe737c27f6..ddcb0b0c9a 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/manager.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/manager.py @@ -4,6 +4,7 @@ from typing import Mapping, Optional, Tuple +from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.oob_processor import OobRecord from ....core.error import BaseError @@ -21,8 +22,6 @@ from .messages.inner.cred_preview import V20CredPreview from .models.cred_ex_record import V20CredExRecord -LOGGER = logging.getLogger(__name__) - class V20CredManagerError(BaseError): """Credential manager error under issue-credential protocol v2.0.""" @@ -38,6 +37,10 @@ def __init__(self, profile: Profile): profile: The profile instance for this credential manager """ self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property def profile(self) -> Profile: @@ -649,7 +652,7 @@ async def send_cred_ack( await self.delete_cred_ex_record(cred_ex_record.cred_ex_id) except StorageError: - LOGGER.exception( + self._logger.exception( "Error sending credential ack" ) # holder still owes an ack: carry on @@ -660,7 +663,7 @@ async def send_cred_ack( connection_id=cred_ex_record.connection_id, ) else: - LOGGER.warning( + self._logger.warning( "Configuration has no BaseResponder: cannot ack credential on %s", cred_ex_record.thread_id, ) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py b/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py index 1eece14bac..741d19e368 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py @@ -5,6 +5,7 @@ from marshmallow import Schema, fields, validate +from .....config.logging import get_logger_inst from .....core.profile import ProfileSession from .....messaging.models.base_record import BaseExchangeRecord, BaseExchangeSchema from .....messaging.valid import UUID4_EXAMPLE @@ -18,8 +19,6 @@ from ..messages.inner.cred_preview import V20CredPreviewSchema from . import UNENCRYPTED_TAGS -LOGGER = logging.getLogger(__name__) - class V20CredExRecord(BaseExchangeRecord): """Represents an Aries#0036 credential exchange.""" @@ -162,7 +161,10 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - + _logger: logging.Logger = get_logger_inst( + profile=session.profile, + logger_name=__name__, + ) if self._last_state == state: # already done return @@ -178,7 +180,7 @@ async def save_error_state( log_override=log_override, ) except StorageError as err: - LOGGER.exception(err) + _logger.exception(err) # Override async def emit_event(self, session: ProfileSession, payload: Any = None): diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/routes.py b/aries_cloudagent/protocols/issue_credential/v2_0/routes.py index 721128b4ae..ca653106c7 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/routes.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/routes.py @@ -16,6 +16,7 @@ from marshmallow import ValidationError, fields, validate, validates_schema from ....admin.request_context import AdminRequestContext +from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.profile import Profile from ....indy.holder import IndyHolderError @@ -54,8 +55,6 @@ from .models.detail.indy import V20CredExRecordIndySchema from .models.detail.ld_proof import V20CredExRecordLDProofSchema -LOGGER = logging.getLogger(__name__) - class V20IssueCredentialModuleResponseSchema(OpenAPISchema): """Response schema for v2.0 Issue Credential Module.""" @@ -680,6 +679,10 @@ async def credential_exchange_send(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -743,7 +746,7 @@ async def credential_exchange_send(request: web.BaseRequest): V20CredManagerError, V20CredFormatError, ) as err: - LOGGER.exception("Error preparing credential offer") + _logger.exception("Error preparing credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -790,6 +793,10 @@ async def credential_exchange_send_proposal(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -831,7 +838,7 @@ async def credential_exchange_send_proposal(request: web.BaseRequest): result = cred_ex_record.serialize() except (BaseModelError, StorageError) as err: - LOGGER.exception("Error preparing credential proposal") + _logger.exception("Error preparing credential proposal") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -922,7 +929,10 @@ async def credential_exchange_create_free_offer(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) body = await request.json() auto_issue = body.get( @@ -955,7 +965,7 @@ async def credential_exchange_create_free_offer(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - LOGGER.exception("Error creating free credential offer") + _logger.exception("Error creating free credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -992,6 +1002,10 @@ async def credential_exchange_send_free_offer(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -1038,7 +1052,7 @@ async def credential_exchange_send_free_offer(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - LOGGER.exception("Error preparing free credential offer") + _logger.exception("Error preparing free credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1086,6 +1100,10 @@ async def credential_exchange_send_bound_offer(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) outbound_handler = request["outbound_message_router"] body = await request.json() if request.body_exists else {} @@ -1144,7 +1162,7 @@ async def credential_exchange_send_bound_offer(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - LOGGER.exception("Error preparing bound credential offer") + _logger.exception("Error preparing bound credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1193,6 +1211,10 @@ async def credential_exchange_send_free_request(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -1248,7 +1270,7 @@ async def credential_exchange_send_free_request(request: web.BaseRequest): StorageError, V20CredManagerError, ) as err: - LOGGER.exception("Error preparing free credential request") + _logger.exception("Error preparing free credential request") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1293,6 +1315,10 @@ async def credential_exchange_send_bound_request(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) outbound_handler = request["outbound_message_router"] try: @@ -1364,7 +1390,7 @@ async def credential_exchange_send_bound_request(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - LOGGER.exception("Error preparing bound credential request") + _logger.exception("Error preparing bound credential request") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1411,6 +1437,10 @@ async def credential_exchange_issue(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -1457,7 +1487,7 @@ async def credential_exchange_issue(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - LOGGER.exception("Error preparing issued credential") + _logger.exception("Error preparing issued credential") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1504,6 +1534,10 @@ async def credential_exchange_store(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) outbound_handler = request["outbound_message_router"] try: @@ -1543,7 +1577,7 @@ async def credential_exchange_store(request: web.BaseRequest): StorageError, V20CredManagerError, ) as err: # treat failure to store as mangled on receipt hence protocol error - LOGGER.exception("Error storing issued credential") + _logger.exception("Error storing issued credential") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py index 9602d5ce7d..7044cde893 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py @@ -1,5 +1,8 @@ """OOB Problem Report Message Handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -21,9 +24,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - self._logger.debug( - f"OOBProblemReportMessageHandler called with context {context}" + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + _logger.debug(f"OOBProblemReportMessageHandler called with context {context}") assert isinstance(context.message, OOBProblemReport) profile = context.profile @@ -35,4 +40,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): conn_record=context.connection_record, ) except OutOfBandManagerError: - self._logger.exception("Error processing OOB Problem Report message") + _logger.exception("Error processing OOB Problem Report message") diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py index ae19d16441..34911efc7e 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py @@ -1,5 +1,8 @@ """Handshake Reuse Accepted Message Handler under RFC 0434.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -18,7 +21,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( f"HandshakeReuseAcceptMessageHandler called with context {context}" ) assert isinstance(context.message, HandshakeReuseAccept) @@ -32,6 +39,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): conn_record=context.connection_record, ) except OutOfBandManagerError as e: - self._logger.exception( - f"Error processing Handshake Reuse Accept message, {e}" - ) + _logger.exception(f"Error processing Handshake Reuse Accept message, {e}") diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py index a312a2af1f..a2889305cb 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py @@ -1,5 +1,8 @@ """Handshake Reuse Message Handler under RFC 0434.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -18,9 +21,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - self._logger.debug( - f"HandshakeReuseMessageHandler called with context {context}" + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + _logger.debug(f"HandshakeReuseMessageHandler called with context {context}") assert isinstance(context.message, HandshakeReuse) profile = context.profile @@ -30,4 +35,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.message_receipt, context.connection_record ) except OutOfBandManagerError as e: - self._logger.exception(f"Error processing Handshake Reuse message, {e}") + _logger.exception(f"Error processing Handshake Reuse message, {e}") diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/manager.py b/aries_cloudagent/protocols/out_of_band/v1_0/manager.py index 007b43a675..9aa54c480c 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/manager.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/manager.py @@ -6,8 +6,8 @@ from typing import Mapping, Optional, Sequence, Union, Text import uuid - from ....messaging.decorators.service_decorator import ServiceDecorator +from ....config.logging import get_logger_inst from ....core.event_bus import EventBus from ....core.util import get_version_from_message from ....connections.base_manager import BaseConnectionManager @@ -40,7 +40,6 @@ from .messages.service import Service from .message_types import DEFAULT_VERSION -LOGGER = logging.getLogger(__name__) REUSE_WEBHOOK_TOPIC = "acapy::webhook::connection_reuse" REUSE_ACCEPTED_WEBHOOK_TOPIC = "acapy::webhook::connection_reuse_accepted" @@ -63,6 +62,10 @@ def __init__(self, profile: Profile): profile: The profile for this out of band manager """ self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) super().__init__(self._profile) @property @@ -459,7 +462,7 @@ async def receive_invitation( if ( public_did is not None and use_existing_connection ): # invite has public DID: seek existing connection - LOGGER.debug( + self._logger.debug( "Trying to find existing connection for oob invitation with " f"did {public_did}" ) @@ -482,7 +485,7 @@ async def receive_invitation( oob_record, conn_rec, get_version_from_message(invitation) ) - LOGGER.warning( + self._logger.warning( f"Connection reuse request finished with state {oob_record.state}" ) @@ -503,7 +506,7 @@ async def receive_invitation( mediation_id=mediation_id, service_accept=service_accept, ) - LOGGER.debug( + self._logger.debug( f"Performed handshake with connection {oob_record.connection_id}" ) # re-fetch connection record @@ -527,7 +530,7 @@ async def receive_invitation( # Handle any attachments if invitation.requests_attach: - LOGGER.debug( + self._logger.debug( f"Process attached messages for oob exchange {oob_record.oob_id} " f"(connection_id {oob_record.connection_id})" ) @@ -579,9 +582,9 @@ async def _process_request_attach(self, oob_record: OobRecord): service = oob_record.invitation.services[0] their_service = await self._service_decorator_from_service(service) if their_service: - LOGGER.debug("Found service for oob record %s", their_service) + self._logger.debug("Found service for oob record %s", their_service) else: - LOGGER.debug("No service decorator obtained from %s", service) + self._logger.debug("No service decorator obtained from %s", service) await message_processor.handle_message( self.profile, messages, oob_record=oob_record, their_service=their_service @@ -626,7 +629,7 @@ async def _service_decorator_from_service( routing_keys=routing_keys, ) else: - LOGGER.warning( + self._logger.warning( "Unexpected type `%s` passed to `_service_decorator_from_service`", type(service), ) @@ -672,9 +675,11 @@ async def _wait_for_state() -> OobRecord: ]: return oob_record - LOGGER.debug(f"Wait for oob {oob_id} to receive reuse accepted mesage") + self._logger.debug( + f"Wait for oob {oob_id} to receive reuse accepted mesage" + ) event = await await_event - LOGGER.debug("Received reuse response message") + self._logger.debug("Received reuse response message") return OobRecord.deserialize(event.payload) try: @@ -696,7 +701,7 @@ async def _wait_for_conn_rec_active( "^acapy::record::connections::(active|completed|response)$" ) - LOGGER.debug(f"Wait for connection {connection_id} to become active") + self._logger.debug(f"Wait for connection {connection_id} to become active") async def _wait_for_state() -> ConnRecord: event = self.profile.inject(EventBus) @@ -715,7 +720,9 @@ async def _wait_for_state() -> ConnRecord: if conn_record.is_ready: return conn_record - LOGGER.debug(f"Wait for connection {connection_id} to become active") + self._logger.debug( + f"Wait for connection {connection_id} to become active" + ) # Wait for connection record to be in state event = await await_event return ConnRecord.deserialize(event.payload) @@ -727,7 +734,9 @@ async def _wait_for_state() -> ConnRecord: ) except asyncio.TimeoutError: - LOGGER.warning(f"Connection for connection_id {connection_id} not ready") + self._logger.warning( + f"Connection for connection_id {connection_id} not ready" + ) return None async def _handle_hanshake_reuse( @@ -740,7 +749,7 @@ async def _handle_hanshake_reuse( # Wait for the reuse accepted message oob_record = await self._wait_for_reuse_response(oob_record.oob_id) - LOGGER.debug( + self._logger.debug( f"Oob reuse for oob id {oob_record.oob_id} with connection " f"{oob_record.connection_id} finished with state {oob_record.state}" ) @@ -825,7 +834,7 @@ async def _perform_handshake( } ) - LOGGER.debug(f"Creating connection with public did {public_did}") + self._logger.debug(f"Creating connection with public did {public_did}") conn_record = None for protocol in supported_handshake_protocols: diff --git a/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py b/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py index 46492d8e87..0011cc7862 100644 --- a/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py +++ b/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py @@ -21,6 +21,7 @@ from unflatten import unflatten from uuid import uuid4 +from ....config.logging import get_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....storage.vc_holder.vc_record import VCRecord @@ -64,7 +65,6 @@ PRESENTATION_SUBMISSION_JSONLD_TYPE = "PresentationSubmission" PYTZ_TIMEZONE_PATTERN = re.compile(r"(([a-zA-Z]+)(?:\/)([a-zA-Z]+))") LIST_INDEX_PATTERN = re.compile(r"\[(\W+)\]|\[(\d+)\]") -LOGGER = logging.getLogger(__name__) class DIFPresExchError(BaseError): @@ -111,6 +111,10 @@ def __init__( self.proof_type = proof_type self.is_holder = False self.reveal_doc_frame = reveal_doc + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def _get_issue_suite( self, @@ -785,7 +789,7 @@ def exclusive_minimum_check(self, val: any, _filter: Filter) -> bool: val = self.is_numeric(val) return val > _filter.exclusive_min except DIFPresExchError as err: - LOGGER.error(err) + self._logger.error(err) return False except (TypeError, ValueError, ParserError): return False @@ -815,7 +819,7 @@ def exclusive_maximum_check(self, val: any, _filter: Filter) -> bool: val = self.is_numeric(val) return val < _filter.exclusive_max except DIFPresExchError as err: - LOGGER.error(err) + self._logger.error(err) return False except (TypeError, ValueError, ParserError): return False @@ -845,7 +849,7 @@ def maximum_check(self, val: any, _filter: Filter) -> bool: val = self.is_numeric(val) return val <= _filter.maximum except DIFPresExchError as err: - LOGGER.error(err) + self._logger.error(err) return False except (TypeError, ValueError, ParserError): return False @@ -875,7 +879,7 @@ def minimum_check(self, val: any, _filter: Filter) -> bool: val = self.is_numeric(val) return val >= _filter.minimum except DIFPresExchError as err: - LOGGER.error(err) + self._logger.error(err) return False except (TypeError, ValueError, ParserError): return False diff --git a/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py b/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py index 4bff88cc89..3170135e6d 100644 --- a/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py +++ b/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py @@ -5,6 +5,7 @@ from typing import Union, Tuple +from ....config.logging import get_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....indy.holder import IndyHolder, IndyHolderError @@ -21,8 +22,6 @@ from ..v2_0.messages.pres_format import V20PresFormat from ..v2_0.models.pres_exchange import V20PresExRecord -LOGGER = logging.getLogger(__name__) - class IndyPresExchHandlerError(BaseError): """Base class for Indy Presentation Exchange related errors.""" @@ -38,6 +37,10 @@ def __init__( """Initialize PresExchange Handler.""" super().__init__() self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def return_presentation( self, @@ -83,7 +86,7 @@ async def return_presentation( if not credentials[req_item["cred_id"]].get( "rev_reg_id" ) and req_item.pop("timestamp", None): - LOGGER.info( + self._logger.info( f"Removed superfluous timestamp from requested_credentials {r} " f"{reft} for non-revocable credential {req_item['cred_id']}" ) @@ -190,7 +193,7 @@ async def return_presentation( ) ) except IndyHolderError as e: - LOGGER.error( + self._logger.error( f"Failed to create revocation state: {e.error_code}, {e.message}" ) raise e diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py index 6a3dfa9eef..f8dc5868b5 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py @@ -1,5 +1,8 @@ """Presentation ack message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -21,10 +24,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - - self._logger.debug("PresentationAckHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("PresentationAckHandler called with context %s", context) assert isinstance(context.message, PresentationAck) - self._logger.info( + _logger.info( "Received presentation ack message: %s", context.message.serialize(as_string=True), ) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py index 7aa96f7f27..b666ae3209 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py @@ -1,5 +1,8 @@ """Presentation message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -27,10 +30,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) profile = context.profile - self._logger.debug("PresentationHandler called with context %s", context) + _logger.debug("PresentationHandler called with context %s", context) assert isinstance(context.message, Presentation) - self._logger.info( + _logger.info( "Received presentation message: %s", context.message.serialize(as_string=True), ) @@ -73,7 +80,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): presentation_exchange_record, responder ) except (BaseModelError, LedgerError, StorageError) as err: - self._logger.exception(err) + _logger.exception(err) if presentation_exchange_record: async with profile.session() as session: await presentation_exchange_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py index 56ca1a6848..aeb5e91cec 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py @@ -1,5 +1,8 @@ """Presentation problem report message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,7 +22,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( "Present-proof v1.0 problem report handler called with context %s", context, ) @@ -42,6 +49,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.connection_record.connection_id, ) except (StorageError, StorageNotFoundError): - self._logger.exception( + _logger.exception( "Error processing present-proof v1.0 problem report message" ) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py index d513123258..19ac38fb94 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py @@ -1,5 +1,8 @@ """Presentation proposal message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.models.base import BaseModelError @@ -26,12 +29,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - profile = context.profile - self._logger.debug( - "PresentationProposalHandler called with context %s", context + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, ) + profile = context.profile + _logger.debug("PresentationProposalHandler called with context %s", context) assert isinstance(context.message, PresentationProposal) - self._logger.info( + _logger.info( "Received presentation proposal message: %s", context.message.serialize(as_string=True), ) @@ -71,7 +76,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): ) await responder.send_reply(presentation_request_message) except (BaseModelError, LedgerError, StorageError) as err: - self._logger.exception(err) + _logger.exception(err) if presentation_exchange_record: async with profile.session() as session: await presentation_exchange_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py index a34cdde4cd..4030d70098 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py @@ -1,5 +1,8 @@ """Presentation request message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolder, IndyHolderError from .....indy.models.xform import indy_proof_req_preview2indy_requested_creds @@ -31,11 +34,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) profile = context.profile - self._logger.debug("PresentationRequestHandler called with context %s", context) + _logger.debug("PresentationRequestHandler called with context %s", context) assert isinstance(context.message, PresentationRequest) - self._logger.info( + _logger.info( "Received presentation request message: %s", context.message.serialize(as_string=True), ) @@ -125,7 +132,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): holder=context.inject(IndyHolder), ) except ValueError as err: - self._logger.warning(f"{err}") + _logger.warning(f"{err}") return # not a protocol error: prover could still build proof manually presentation_message = None @@ -148,7 +155,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, WalletNotFoundError, ) as err: - self._logger.exception(err) + _logger.exception(err) if presentation_exchange_record: async with profile.session() as session: await presentation_exchange_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/manager.py b/aries_cloudagent/protocols/present_proof/v1_0/manager.py index b5a85278f9..7198fe6a0c 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/manager.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/manager.py @@ -4,7 +4,7 @@ import logging from typing import Optional -from ...out_of_band.v1_0.models.oob_record import OobRecord +from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.error import BaseError from ....core.profile import Profile @@ -12,6 +12,9 @@ from ....messaging.decorators.attach_decorator import AttachDecorator from ....messaging.responder import BaseResponder from ....storage.error import StorageNotFoundError + +from ...out_of_band.v1_0.models.oob_record import OobRecord + from ..indy.pres_exch_handler import IndyPresExchHandler from .messages.presentation_ack import PresentationAck @@ -25,8 +28,6 @@ from .message_types import ATTACH_DECO_IDS, PRESENTATION, PRESENTATION_REQUEST from .models.presentation_exchange import V10PresentationExchange -LOGGER = logging.getLogger(__name__) - class PresentationManagerError(BaseError): """Presentation error.""" @@ -43,6 +44,10 @@ def __init__(self, profile: Profile): """ self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def create_exchange_for_proposal( self, @@ -469,7 +474,7 @@ async def send_presentation_ack( except StorageNotFoundError: # This can happen in AIP1 style connectionless exchange. ACA-PY only # supported this for receiving a presentation - LOGGER.error( + self._logger.error( "Unable to send connectionless presentation ack without associated " "oob record. This can happen if proof request was sent without " "wrapping it in an out of band invitation (AIP1-style)." @@ -498,7 +503,7 @@ async def send_presentation_ack( async with self._profile.session() as session: await presentation_exchange_record.delete_record(session) else: - LOGGER.warning( + self._logger.warning( "Configuration has no BaseResponder: cannot ack presentation on %s", presentation_exchange_record.thread_id, ) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py b/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py index a32c1355eb..324a6e3bf3 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py @@ -5,6 +5,7 @@ from marshmallow import fields, validate +from .....config.logging import get_logger_inst from .....core.profile import ProfileSession from .....indy.models.proof import IndyProof, IndyProofSchema from .....indy.models.proof_request import IndyProofRequest, IndyProofRequestSchema @@ -22,8 +23,6 @@ from ..messages.presentation_webhook import V10PresentationExchangeWebhook from . import UNENCRYPTED_TAGS -LOGGER = logging.getLogger(__name__) - class V10PresentationExchange(BaseExchangeRecord): """Represents an Aries#0037 v1.0 presentation exchange.""" @@ -176,7 +175,10 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - + _logger: logging.Logger = get_logger_inst( + profile=session.profile, + logger_name=__name__, + ) if self._last_state == state: # already done return @@ -192,7 +194,7 @@ async def save_error_state( log_override=log_override, ) except StorageError as err: - LOGGER.exception(err) + _logger.exception(err) # Override async def emit_event(self, session: ProfileSession, payload: Any = None): diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py index 2534a65c4f..79cd6522ec 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py @@ -1,5 +1,8 @@ """Presentation ack message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -21,10 +24,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - - self._logger.debug("V20PresAckHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("V20PresAckHandler called with context %s", context) assert isinstance(context.message, V20PresAck) - self._logger.info( + _logger.info( "Received v2.0 presentation ack message: %s", context.message.serialize(as_string=True), ) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py index 9a93d68cc0..957587c1ef 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py @@ -1,5 +1,8 @@ """Presentation message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -27,10 +30,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - - self._logger.debug("V20PresHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("V20PresHandler called with context %s", context) assert isinstance(context.message, V20Pres) - self._logger.info( + _logger.info( "Received presentation message: %s", context.message.serialize(as_string=True), ) @@ -71,7 +77,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): try: await pres_manager.verify_pres(pres_ex_record, responder) except (BaseModelError, LedgerError, StorageError) as err: - self._logger.exception(err) + _logger.exception(err) if pres_ex_record: async with context.profile.session() as session: await pres_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py index 32c5e23e0a..5f8436cee8 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py @@ -1,5 +1,8 @@ """Presentation problem report message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,7 +22,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( "Present-proof v2.0 problem report handler called with context %s", context, ) @@ -32,6 +39,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.connection_record.connection_id, ) except (StorageError, StorageNotFoundError): - self._logger.exception( + _logger.exception( "Error processing present-proof v2.0 problem report message" ) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py index 23b16c0ebf..328fa5a730 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py @@ -1,5 +1,8 @@ """Presentation proposal message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.models.base import BaseModelError @@ -26,10 +29,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - - self._logger.debug("V20PresProposalHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("V20PresProposalHandler called with context %s", context) assert isinstance(context.message, V20PresProposal) - self._logger.info( + _logger.info( "Received v2.0 presentation proposal message: %s", context.message.serialize(as_string=True), ) @@ -70,7 +76,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): ) await responder.send_reply(pres_request_message) except (BaseModelError, LedgerError, StorageError) as err: - self._logger.exception(err) + _logger.exception(err) if pres_ex_record: async with profile.session() as session: await pres_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py index abac0f7398..4cec97aca9 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py @@ -1,5 +1,8 @@ """Presentation request message handler.""" +import logging + +from .....config.logging import get_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError from .....ledger.error import LedgerError @@ -31,10 +34,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - - self._logger.debug("V20PresRequestHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("V20PresRequestHandler called with context %s", context) assert isinstance(context.message, V20PresRequest) - self._logger.info( + _logger.info( "Received v2.0 presentation request message: %s", context.message.serialize(as_string=True), ) @@ -122,7 +128,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): WalletNotFoundError, V20PresFormatHandlerError, ) as err: - self._logger.exception(err) + _logger.exception(err) if pres_ex_record: async with profile.session() as session: await pres_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/manager.py b/aries_cloudagent/protocols/present_proof/v2_0/manager.py index 083dcac5ac..063a841460 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/manager.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/manager.py @@ -4,12 +4,14 @@ from typing import Optional, Tuple -from ...out_of_band.v1_0.models.oob_record import OobRecord +from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.error import BaseError from ....core.profile import Profile from ....messaging.responder import BaseResponder +from ...out_of_band.v1_0.models.oob_record import OobRecord + from .messages.pres import V20Pres from .messages.pres_ack import V20PresAck from .messages.pres_format import V20PresFormat @@ -19,9 +21,6 @@ from .models.pres_exchange import V20PresExRecord -LOGGER = logging.getLogger(__name__) - - class V20PresManagerError(BaseError): """Presentation error.""" @@ -37,6 +36,10 @@ def __init__(self, profile: Profile): """ self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def create_exchange_for_proposal( self, @@ -440,7 +443,7 @@ async def send_pres_ack( async with self._profile.session() as session: await pres_ex_record.delete_record(session) else: - LOGGER.warning( + self._logger.warning( "Configuration has no BaseResponder: cannot ack presentation on %s", pres_ex_record.thread_id, ) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py b/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py index 06f43036ea..80c10a46f0 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py @@ -5,6 +5,7 @@ from marshmallow import Schema, fields, validate +from .....config.logging import get_logger_inst from .....core.profile import ProfileSession from .....messaging.models.base_record import BaseExchangeRecord, BaseExchangeSchema from .....messaging.valid import UUID4_EXAMPLE @@ -16,8 +17,6 @@ from ..messages.pres_webhook import V20PresExRecordWebhook from . import UNENCRYPTED_TAGS -LOGGER = logging.getLogger(__name__) - class V20PresExRecord(BaseExchangeRecord): """Represents a v2.0 presentation exchange.""" @@ -162,7 +161,10 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - + _logger: logging.Logger = get_logger_inst( + profile=session.profile, + logger_name=__name__, + ) if self._last_state == state: # already done return @@ -178,7 +180,7 @@ async def save_error_state( log_override=log_override, ) except StorageError as err: - LOGGER.exception(err) + _logger.exception(err) # Override async def emit_event(self, session: ProfileSession, payload: Any = None): diff --git a/aries_cloudagent/protocols/problem_report/v1_0/handler.py b/aries_cloudagent/protocols/problem_report/v1_0/handler.py index 99e1c1d179..0cded7bb1f 100644 --- a/aries_cloudagent/protocols/problem_report/v1_0/handler.py +++ b/aries_cloudagent/protocols/problem_report/v1_0/handler.py @@ -1,5 +1,8 @@ """Generic problem report handler.""" +import logging + +from ....config.logging import get_logger_inst from ....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -20,10 +23,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: Responder used to reply """ - self._logger.debug("ProblemReportHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("ProblemReportHandler called with context %s", context) assert isinstance(context.message, ProblemReport) - self._logger.info( + _logger.info( "Received problem report from: %s, %r", context.message_receipt.sender_did, context.message, diff --git a/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py b/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py index 366cbcd6c2..91aed2c656 100644 --- a/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py +++ b/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py @@ -1,5 +1,8 @@ """Handler for revoke message.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -16,7 +19,11 @@ class RevokeHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle revoke message.""" assert isinstance(context.message, Revoke) - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( "Received notification of revocation for cred issued in thread %s " "with comment: %s", context.message.thread_id, diff --git a/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py b/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py index cdefdaf642..fa194271f8 100644 --- a/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py +++ b/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py @@ -2,6 +2,7 @@ import logging import re +from ....config.logging import get_logger_inst from ....core.event_bus import Event, EventBus from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -13,8 +14,6 @@ from ....storage.error import StorageError, StorageNotFoundError from .models.rev_notification_record import RevNotificationRecord -LOGGER = logging.getLogger(__name__) - def register_events(event_bus: EventBus): """Register to handle events.""" @@ -30,7 +29,11 @@ def register_events(event_bus: EventBus): async def on_revocation_published(profile: Profile, event: Event): """Handle issuer revoke event.""" - LOGGER.debug("Sending notification of revocation to recipient: %s", event.payload) + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) + _logger.debug("Sending notification of revocation to recipient: %s", event.payload) responder = profile.inject(BaseResponder) crids = event.payload.get("crids") or [] @@ -50,12 +53,12 @@ async def on_revocation_published(profile: Profile, event: Event): ) except StorageNotFoundError: - LOGGER.info( + _logger.info( "No revocation notification record found for revoked credential; " "no notification will be sent" ) except StorageError: - LOGGER.exception("Failed to retrieve revocation notification record") + _logger.exception("Failed to retrieve revocation notification record") async def on_pending_cleared(profile: Profile, event: Event): diff --git a/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py b/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py index f2ffafe7e0..c953a1ca6a 100644 --- a/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py +++ b/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py @@ -1,5 +1,8 @@ """Handler for revoke message.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -16,7 +19,11 @@ class RevokeHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle revoke message.""" assert isinstance(context.message, Revoke) - self._logger.debug( + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug( "Received notification of revocation for %s cred %s with comment: %s", context.message.revocation_format, context.message.credential_id, diff --git a/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py b/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py index 83ba81fe63..cc05851c9d 100644 --- a/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py +++ b/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py @@ -2,6 +2,7 @@ import logging import re +from ....config.logging import get_logger_inst from ....core.event_bus import Event, EventBus from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -13,8 +14,6 @@ from ....storage.error import StorageError, StorageNotFoundError from .models.rev_notification_record import RevNotificationRecord -LOGGER = logging.getLogger(__name__) - def register_events(event_bus: EventBus): """Register to handle events.""" @@ -30,7 +29,11 @@ def register_events(event_bus: EventBus): async def on_revocation_published(profile: Profile, event: Event): """Handle issuer revoke event.""" - LOGGER.debug("Sending notification of revocation to recipient: %s", event.payload) + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) + _logger.debug("Sending notification of revocation to recipient: %s", event.payload) should_notify = profile.settings.get("revocation.notify", False) responder = profile.inject(BaseResponder) @@ -52,12 +55,12 @@ async def on_revocation_published(profile: Profile, event: Event): ) except StorageNotFoundError: - LOGGER.info( + _logger.info( "No revocation notification record found for revoked credential; " "no notification will be sent" ) except StorageError: - LOGGER.exception("Failed to retrieve revocation notification record") + _logger.exception("Failed to retrieve revocation notification record") async def on_pending_cleared(profile: Profile, event: Event): diff --git a/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py b/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py index 47654fc5b0..5a1fa431c3 100644 --- a/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py +++ b/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py @@ -1,7 +1,9 @@ """Handler for incoming forward messages.""" +import logging import json +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -18,12 +20,16 @@ class ForwardHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - self._logger.debug("ForwardHandler called with context %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("ForwardHandler called with context %s", context) assert isinstance(context.message, Forward) if not context.message_receipt.recipient_verkey: raise HandlerException("Cannot forward message: unknown recipient") - self._logger.info( + _logger.info( "Received forward for: %s", context.message_receipt.recipient_verkey ) @@ -35,7 +41,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): try: recipient = await rt_mgr.get_recipient(target) except RoutingManagerError: - self._logger.exception("Error resolving recipient for forwarded message") + _logger.exception("Error resolving recipient for forwarded message") return # load connection @@ -47,9 +53,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): connection_verkey = connection_targets[0].recipient_keys[0] # Note: not currently vetting the state of the connection here - self._logger.info( - f"Forwarding message to connection: {recipient.connection_id}" - ) + _logger.info(f"Forwarding message to connection: {recipient.connection_id}") send_status = await responder.send( packed, diff --git a/aries_cloudagent/protocols/routing/v1_0/manager.py b/aries_cloudagent/protocols/routing/v1_0/manager.py index a5fe48c924..fd4aaf5dc3 100644 --- a/aries_cloudagent/protocols/routing/v1_0/manager.py +++ b/aries_cloudagent/protocols/routing/v1_0/manager.py @@ -4,6 +4,7 @@ import logging from typing import Sequence +from ....config.logging import get_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....storage.error import ( @@ -14,8 +15,6 @@ from .models.route_record import RouteRecord -LOGGER = logging.getLogger(__name__) - RECIP_ROUTE_PAUSE = 0.1 RECIP_ROUTE_RETRY = 10 @@ -42,6 +41,10 @@ def __init__(self, profile: Profile): self._profile = profile if not profile: raise RoutingManagerError("Missing profile") + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def get_recipient(self, recip_verkey: str) -> RouteRecord: """Resolve the recipient for a verkey. @@ -60,20 +63,28 @@ async def get_recipient(self, recip_verkey: str) -> RouteRecord: record = None while not record: try: - LOGGER.info(">>> fetching routing record for verkey: " + recip_verkey) + self._logger.info( + ">>> fetching routing record for verkey: " + recip_verkey + ) async with self._profile.session() as session: record = await RouteRecord.retrieve_by_recipient_key( session, recip_verkey ) - LOGGER.info(">>> FOUND routing record for verkey: " + recip_verkey) + self._logger.info( + ">>> FOUND routing record for verkey: " + recip_verkey + ) return record except StorageDuplicateError: - LOGGER.info(">>> DUPLICATE routing record for verkey: " + recip_verkey) + self._logger.info( + ">>> DUPLICATE routing record for verkey: " + recip_verkey + ) raise RouteNotFoundError( f"More than one route record found with recipient key: {recip_verkey}" ) except StorageNotFoundError: - LOGGER.info(">>> NOT FOUND routing record for verkey: " + recip_verkey) + self._logger.info( + ">>> NOT FOUND routing record for verkey: " + recip_verkey + ) i += 1 if i > RECIP_ROUTE_RETRY: raise RouteNotFoundError( @@ -145,7 +156,7 @@ async def create_route_record( ) if not recipient_key: raise RoutingManagerError("Missing recipient_key") - LOGGER.info(">>> creating routing record for verkey: " + recipient_key) + self._logger.info(">>> creating routing record for verkey: " + recipient_key) route = RouteRecord( connection_id=client_connection_id, wallet_id=internal_wallet_id, @@ -153,5 +164,5 @@ async def create_route_record( ) async with self._profile.session() as session: await route.save(session, reason="Created new route") - LOGGER.info(">>> CREATED routing record for verkey: " + recipient_key) + self._logger.info(">>> CREATED routing record for verkey: " + recipient_key) return route diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py index 7963109e43..9253ef874a 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py @@ -1,5 +1,8 @@ """Ping handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,15 +24,17 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: Responder used to reply """ - self._logger.debug(f"PingHandler called with context {context}") + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug(f"PingHandler called with context {context}") assert isinstance(context.message, Ping) - self._logger.info( - "Received trust ping from: %s", context.message_receipt.sender_did - ) + _logger.info("Received trust ping from: %s", context.message_receipt.sender_did) if not context.connection_ready: - self._logger.info( + _logger.info( "Connection not active, skipping ping response: %s", context.message_receipt.sender_did, ) diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py index c66c68158a..9a1e0d1806 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py @@ -1,5 +1,8 @@ """Ping response handler.""" +import logging + +from .....config.logging import get_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -20,11 +23,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: Responder used to reply """ - - self._logger.debug("PingResponseHandler called with context: %s", context) + _logger: logging.Logger = get_logger_inst( + profile=context.profile, + logger_name=__name__, + ) + _logger.debug("PingResponseHandler called with context: %s", context) assert isinstance(context.message, PingResponse) - self._logger.info( + _logger.info( "Received trust ping response from: %s", context.message_receipt.sender_did ) diff --git a/aries_cloudagent/resolver/default/universal.py b/aries_cloudagent/resolver/default/universal.py index 2efee46009..63620afb42 100644 --- a/aries_cloudagent/resolver/default/universal.py +++ b/aries_cloudagent/resolver/default/universal.py @@ -7,10 +7,10 @@ import aiohttp from ...config.injection_context import InjectionContext +from ...config.logging import get_logger_inst from ...core.profile import Profile from ..base import BaseDIDResolver, DIDNotFound, ResolverError, ResolverType -LOGGER = logging.getLogger(__name__) DEFAULT_ENDPOINT = "https://dev.uniresolver.io/1.0" @@ -84,13 +84,16 @@ async def _resolve( service_accept: Optional[Sequence[Text]] = None, ) -> dict: """Resolve DID through remote universal resolver.""" - + _logger: logging.Logger = get_logger_inst( + profile=_profile, + logger_name=__name__, + ) async with aiohttp.ClientSession(headers=self.__default_headers) as session: async with session.get(f"{self._endpoint}/identifiers/{did}") as resp: if resp.status == 200: doc = await resp.json() did_doc = doc["didDocument"] - LOGGER.info("Retrieved doc: %s", did_doc) + _logger.info("Retrieved doc: %s", did_doc) return did_doc if resp.status == 404: raise DIDNotFound(f"{did} not found by {self.__class__.__name__}") diff --git a/aries_cloudagent/revocation/indy.py b/aries_cloudagent/revocation/indy.py index 622ef3f583..beb59d86f3 100644 --- a/aries_cloudagent/revocation/indy.py +++ b/aries_cloudagent/revocation/indy.py @@ -3,6 +3,7 @@ from typing import Optional, Sequence, Tuple from uuid import uuid4 +from ..config.logging import get_logger_inst from ..core.profile import Profile from ..ledger.base import BaseLedger from ..ledger.multiple_ledger.ledger_requests_executor import ( @@ -27,8 +28,6 @@ from .models.revocation_registry import RevocationRegistry from .util import notify_revocation_reg_init_event -LOGGER = logging.getLogger(__name__) - class IndyRevocation: """Class for managing Indy credential revocation.""" @@ -38,6 +37,10 @@ class IndyRevocation: def __init__(self, profile: Profile): """Initialize the IndyRevocation instance.""" self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) async def init_issuer_registry( self, @@ -125,9 +128,9 @@ async def decommission_registry(self, cred_def_id: str): ) for rec in recs: - LOGGER.debug(f"decommission {rec.state} rev. reg.") - LOGGER.debug(f"revoc_reg_id: {rec.revoc_reg_id}") - LOGGER.debug(f"cred_def_id: {cred_def_id}") + self._logger.debug(f"decommission {rec.state} rev. reg.") + self._logger.debug(f"revoc_reg_id: {rec.revoc_reg_id}") + self._logger.debug(f"cred_def_id: {cred_def_id}") # decommission active registry, we need to init a replacement init = IssuerRevRegRecord.STATE_ACTIVE == rec.state await self._set_registry_status( diff --git a/aries_cloudagent/revocation/models/issuer_rev_reg_record.py b/aries_cloudagent/revocation/models/issuer_rev_reg_record.py index ccb47e63ed..e973d16b77 100644 --- a/aries_cloudagent/revocation/models/issuer_rev_reg_record.py +++ b/aries_cloudagent/revocation/models/issuer_rev_reg_record.py @@ -12,6 +12,7 @@ from marshmallow import fields, validate +from ...config.logging import get_logger_inst from ...core.profile import Profile, ProfileSession from ...indy.issuer import IndyIssuer, IndyIssuerError from ...indy.models.revocation import ( @@ -43,8 +44,6 @@ DEFAULT_REGISTRY_SIZE = 1000 -LOGGER = logging.getLogger(__name__) - @total_ordering class IssuerRevRegRecord(BaseRecord): @@ -184,6 +183,10 @@ def _check_url(self, url) -> None: async def generate_registry(self, profile: Profile): """Create the revocation registry definition and tails file.""" + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) if not self.tag: self.tag = self._id or str(uuid.uuid4()) @@ -197,7 +200,7 @@ async def generate_registry(self, profile: Profile): issuer = profile.inject(IndyIssuer) tails_hopper_dir = indy_client_dir(join("tails", ".hopper"), create=True) - LOGGER.debug("Creating revocation registry with size: %d", self.max_cred_num) + _logger.debug("Creating revocation registry with size: %d", self.max_cred_num) try: ( @@ -285,6 +288,10 @@ async def send_entry( endorser_did: str = None, ) -> dict: """Send a registry entry to the ledger.""" + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) if not ( self.revoc_reg_id and self.revoc_def_type @@ -325,27 +332,27 @@ async def send_entry( # Ledger rejected transaction request: client request invalid: # InvalidClientRequest(...) # In this scenario we try to post a correction - LOGGER.warn("Retry ledger update/fix due to error") - LOGGER.warn(err) + _logger.warn("Retry ledger update/fix due to error") + _logger.warn(err) (_, _, res) = await self.fix_ledger_entry( profile, True, ledger.pool.genesis_txns, ) rev_entry_res = {"result": res} - LOGGER.warn("Ledger update/fix applied") + _logger.warn("Ledger update/fix applied") elif "InvalidClientTaaAcceptanceError" in err.roll_up: # if no write access (with "InvalidClientTaaAcceptanceError") # e.g. aries_cloudagent.ledger.error.LedgerTransactionError: # Ledger rejected transaction request: client request invalid: # InvalidClientTaaAcceptanceError(...) - LOGGER.error("Ledger update failed due to TAA issue") - LOGGER.error(err) + _logger.error("Ledger update failed due to TAA issue") + _logger.error(err) raise err else: # not sure what happened, raise an error - LOGGER.error("Ledger update failed due to unknown issue") - LOGGER.error(err) + _logger.error("Ledger update failed due to unknown issue") + _logger.error(err) raise err if self.state == IssuerRevRegRecord.STATE_POSTED: self.state = IssuerRevRegRecord.STATE_ACTIVE # initial entry activates @@ -364,6 +371,10 @@ async def fix_ledger_entry( ) -> Tuple[dict, dict, dict]: """Fix the ledger entry to match wallet-recorded credentials.""" # get rev reg delta (revocations published to ledger) + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) ledger = profile.inject(BaseLedger) async with ledger: (rev_reg_delta, _) = await ledger.get_revoc_reg_delta(self.revoc_reg_id) @@ -387,12 +398,12 @@ async def fix_ledger_entry( # await rec.set_state(session, IssuerCredRevRecord.STATE_ISSUED) rec_count += 1 - LOGGER.debug(">>> fixed entry recs count = %s", rec_count) - LOGGER.debug( + _logger.debug(">>> fixed entry recs count = %s", rec_count) + _logger.debug( ">>> rev_reg_record.revoc_reg_entry.value: %s", self.revoc_reg_entry.value, ) - LOGGER.debug( + _logger.debug( '>>> rev_reg_delta.get("value"): %s', rev_reg_delta.get("value") ) @@ -412,7 +423,7 @@ async def fix_ledger_entry( ) recovery_txn = json.loads(calculated_txn.to_json()) - LOGGER.debug(">>> apply_ledger_update = %s", apply_ledger_update) + _logger.debug(">>> apply_ledger_update = %s", apply_ledger_update) if apply_ledger_update: ledger = session.inject_or(BaseLedger) if not ledger: diff --git a/aries_cloudagent/wallet/routes.py b/aries_cloudagent/wallet/routes.py index 20dd8727c1..cc88c28cc3 100644 --- a/aries_cloudagent/wallet/routes.py +++ b/aries_cloudagent/wallet/routes.py @@ -10,6 +10,7 @@ from marshmallow import fields, validate from ..admin.request_context import AdminRequestContext +from ..config.logging import get_logger_inst from ..connections.models.conn_record import ConnRecord from ..core.event_bus import Event, EventBus from ..core.profile import Profile @@ -58,8 +59,6 @@ from .key_type import BLS12381G2, ED25519, KeyTypes from .util import EVENT_LISTENER_PATTERN -LOGGER = logging.getLogger(__name__) - class WalletModuleResponseSchema(OpenAPISchema): """Response schema for Wallet Module.""" @@ -1048,7 +1047,10 @@ def register_events(event_bus: EventBus): async def on_register_nym_event(profile: Profile, event: Event): """Handle any events we need to support.""" - + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) # after the nym record is written, promote to wallet public DID if is_author_role(profile) and profile.context.settings.get_value( "endorser.auto_promote_author_did" @@ -1061,7 +1063,7 @@ async def on_register_nym_event(profile: Profile, event: Event): ) except Exception as err: # log the error, but continue - LOGGER.exception( + _logger.exception( "Error promoting to public DID: %s", err, ) @@ -1074,9 +1076,8 @@ async def on_register_nym_event(profile: Profile, event: Event): ) except StorageError as err: # log the error, but continue - LOGGER.exception( - "Error accepting endorser invitation/configuring endorser" - " connection: %s", + _logger.exception( + "Error accepting endorser invitation/configuring endorser connection: %s", err, ) return @@ -1092,7 +1093,7 @@ async def on_register_nym_event(profile: Profile, event: Event): ) except (StorageError, TransactionManagerError) as err: # log the error, but continue - LOGGER.exception( + _logger.exception( "Error creating endorser transaction request: %s", err, ) @@ -1106,7 +1107,7 @@ async def on_register_nym_event(profile: Profile, event: Event): connection_id=connection_id, ) else: - LOGGER.warning( + _logger.warning( "Configuration has no BaseResponder: cannot update " "ATTRIB record on DID: %s", did, From a45f806410ba5d04607f9a5734f021849e1ae393 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Sat, 12 Aug 2023 00:18:54 -0700 Subject: [PATCH 02/18] incomplete test changes Signed-off-by: Shaanjot Gill --- aries_cloudagent/core/tests/test_event_bus.py | 120 +++++++++++++----- .../v1_0/tests/test_mediation_manager.py | 23 +++- .../tests/test_credential_issue_handler.py | 6 +- .../tests/test_credential_offer_handler.py | 6 +- .../tests/test_credential_proposal_handler.py | 6 +- .../tests/test_credential_request_handler.py | 6 +- .../models/tests/test_credential_exchange.py | 6 +- .../v1_0/tests/test_manager.py | 26 +++- .../v2_0/formats/indy/tests/test_handler.py | 7 +- .../formats/ld_proof/tests/test_handler.py | 7 +- .../handlers/tests/test_cred_offer_handler.py | 6 +- .../tests/test_cred_proposal_handler.py | 6 +- .../tests/test_cred_request_handler.py | 6 +- .../v2_0/models/tests/test_cred_ex_record.py | 6 +- .../v2_0/tests/test_manager.py | 12 +- .../tests/test_problem_report_handler.py | 10 +- .../tests/test_presentation_handler.py | 6 +- .../test_presentation_proposal_handler.py | 6 +- .../test_presentation_request_handler.py | 6 +- .../v1_0/models/tests/test_record.py | 6 +- .../present_proof/v1_0/tests/test_manager.py | 6 +- .../v2_0/formats/dif/tests/test_handler.py | 36 +++++- .../v2_0/handlers/tests/test_pres_handler.py | 6 +- .../tests/test_pres_proposal_handler.py | 6 +- .../tests/test_pres_request_handler.py | 6 +- .../v2_0/models/tests/test_record.py | 6 +- .../present_proof/v2_0/tests/test_manager.py | 12 +- .../transport/outbound/tests/test_manager.py | 18 ++- 28 files changed, 302 insertions(+), 77 deletions(-) diff --git a/aries_cloudagent/core/tests/test_event_bus.py b/aries_cloudagent/core/tests/test_event_bus.py index 26ce28dacf..5380f3d372 100644 --- a/aries_cloudagent/core/tests/test_event_bus.py +++ b/aries_cloudagent/core/tests/test_event_bus.py @@ -85,7 +85,14 @@ def test_unsub_unsubbed_processor(event_bus: EventBus, processor): async def test_sub_notify(event_bus: EventBus, profile, event, processor): """Test subscriber receives event.""" event_bus.subscribe(re.compile(".*"), processor) - await event_bus.notify(profile, event) + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), + ), + ): + await event_bus.notify(profile, event) assert processor.profile == profile assert processor.event == event @@ -106,7 +113,14 @@ def _raise_exception(profile, event): event_bus.subscribe(re.compile(".*"), bad_processor) event_bus.subscribe(re.compile(".*"), processor) with async_mock.patch.object( - test_module.LOGGER, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock( + debug=async_mock.MagicMock(), + exception=async_mock.MagicMock(), + ), + ), ) as mock_log_exc: await event_bus.notify(profile, event) @@ -128,53 +142,87 @@ async def test_sub_notify_regex_filtering( event_bus: EventBus, profile, processor, pattern, topic ): """Test events are filtered correctly.""" - event = Event(topic) - event_bus.subscribe(re.compile(pattern), processor) - await event_bus.notify(profile, event) - assert processor.profile == profile - assert processor.event == event + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), + ), + ): + event = Event(topic) + event_bus.subscribe(re.compile(pattern), processor) + await event_bus.notify(profile, event) + assert processor.profile == profile + assert processor.event == event @pytest.mark.asyncio async def test_sub_notify_no_match(event_bus: EventBus, profile, event, processor): """Test event not given to processor when pattern doesn't match.""" - event_bus.subscribe(re.compile("^$"), processor) - await event_bus.notify(profile, event) - assert processor.profile is None - assert processor.event is None + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), + ), + ): + event_bus.subscribe(re.compile("^$"), processor) + await event_bus.notify(profile, event) + assert processor.profile is None + assert processor.event is None @pytest.mark.asyncio async def test_sub_notify_only_one(event_bus: EventBus, profile, event, processor): """Test only one subscriber is called when pattern matches only one.""" - processor1 = MockProcessor() - event_bus.subscribe(re.compile(".*"), processor) - event_bus.subscribe(re.compile("^$"), processor1) - await event_bus.notify(profile, event) - assert processor.profile == profile - assert processor.event == event - assert processor1.profile is None - assert processor1.event is None + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), + ), + ): + processor1 = MockProcessor() + event_bus.subscribe(re.compile(".*"), processor) + event_bus.subscribe(re.compile("^$"), processor1) + await event_bus.notify(profile, event) + assert processor.profile == profile + assert processor.event == event + assert processor1.profile is None + assert processor1.event is None @pytest.mark.asyncio async def test_sub_notify_both(event_bus: EventBus, profile, event, processor): """Test both subscribers are called when pattern matches both.""" - processor1 = MockProcessor() - event_bus.subscribe(re.compile(".*"), processor) - event_bus.subscribe(re.compile("anything"), processor1) - await event_bus.notify(profile, event) - assert processor.profile == profile - assert processor.event == event - assert processor1.profile == profile - assert processor1.event == event + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), + ), + ): + processor1 = MockProcessor() + event_bus.subscribe(re.compile(".*"), processor) + event_bus.subscribe(re.compile("anything"), processor1) + await event_bus.notify(profile, event) + assert processor.profile == profile + assert processor.event == event + assert processor1.profile == profile + assert processor1.event == event @pytest.mark.asyncio async def test_wait_for_event_multiple_do_not_collide(event_bus: EventBus, profile): """Test multiple wait_for_event calls don't collide.""" pattern = re.compile(".*") - with event_bus.wait_for_event(profile, pattern) as event1: + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), + ), + ), event_bus.wait_for_event(profile, pattern) as event1: with event_bus.wait_for_event(profile, pattern) as event2: assert len(event_bus.topic_patterns_to_subscribers) == 1 assert len(event_bus.topic_patterns_to_subscribers[pattern]) == 2 @@ -186,7 +234,13 @@ async def test_wait_for_event_multiple_do_not_collide(event_bus: EventBus, profi @pytest.mark.asyncio async def test_wait_for_event(event_bus: EventBus, profile, event): - with event_bus.wait_for_event(profile, re.compile(".*")) as returned_event: + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), + ), + ), event_bus.wait_for_event(profile, re.compile(".*")) as returned_event: await event_bus.notify(profile, event) assert await returned_event == event @@ -195,7 +249,13 @@ async def test_wait_for_event(event_bus: EventBus, profile, event): async def test_wait_for_event_condition(event_bus: EventBus, profile, event): with event_bus.wait_for_event( profile, re.compile(".*"), lambda e: e.payload == "asdf" - ) as returned_event: + ) as returned_event, async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), + ), + ): # This shouldn't trigger our condition because payload == "payload" await event_bus.notify(profile, event) assert not returned_event.done() diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py index 5ccab85c5f..c2f86812a4 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py @@ -376,6 +376,7 @@ async def test_store_update_results( self, session: ProfileSession, manager: MediationManager, + profile: Profile, ): """test_store_update_results.""" await RouteRecord( @@ -412,23 +413,37 @@ async def test_store_update_results( with async_mock.patch.object( RouteRecord, "query", async_mock.CoroutineMock() ) as mock_route_rec_query, async_mock.patch.object( - test_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock( + error=async_mock.MagicMock(), + ), + ) ) as mock_logger_error: + _manager_with_mock_logger = MediationManager(profile) mock_route_rec_query.side_effect = StorageNotFoundError("no record") - await manager.store_update_results(TEST_CONN_ID, results) + await _manager_with_mock_logger.store_update_results(TEST_CONN_ID, results) mock_logger_error.assert_called_once() with async_mock.patch.object( RouteRecord, "query", async_mock.CoroutineMock() ) as mock_route_rec_query, async_mock.patch.object( - test_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock( + error=async_mock.MagicMock(), + ), + ) ) as mock_logger_error: + _manager_with_mock_logger = MediationManager(profile) mock_route_rec_query.return_value = [ async_mock.MagicMock(delete_record=async_mock.CoroutineMock()) ] * 2 - await manager.store_update_results(TEST_CONN_ID, results) + await _manager_with_mock_logger.store_update_results(TEST_CONN_ID, results) mock_logger_error.assert_called_once() async def test_store_update_results_exists_relay(self, session, manager): diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py index 0f831927a1..ae5fe7e4a5 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py @@ -125,7 +125,11 @@ async def test_called_auto_store_x(self): with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() ) as mock_send_reply, async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py index a9aedbb0a9..52d39fc296 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py @@ -117,7 +117,11 @@ async def test_called_auto_request_x(self): with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() ) as mock_send_reply, async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py index 911f056d43..20b26fb8b3 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py @@ -91,7 +91,11 @@ async def test_called_auto_offer_x(self): with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() ) as mock_send_reply, async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py index b74bf445ef..fd702fbece 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py @@ -149,7 +149,11 @@ async def test_called_auto_issue_x(self): with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() ) as mock_send_reply, async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/models/tests/test_credential_exchange.py b/aries_cloudagent/protocols/issue_credential/v1_0/models/tests/test_credential_exchange.py index d1df7d7f71..130bb30300 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/models/tests/test_credential_exchange.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/models/tests/test_credential_exchange.py @@ -80,7 +80,11 @@ async def test_save_error_state(self): with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( - test_module.LOGGER, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="test") diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py index 66cf6315a5..7d28dce2c6 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py @@ -1552,20 +1552,34 @@ async def test_send_credential_ack(self): ) as mock_save_ex, async_mock.patch.object( V10CredentialExchange, "delete_record", autospec=True ) as mock_delete_ex, async_mock.patch.object( - test_module.LOGGER, "exception", async_mock.MagicMock() - ) as mock_log_exception, async_mock.patch.object( - test_module.LOGGER, "warning", async_mock.MagicMock() - ) as mock_log_warning: + test_module, "get_logger_inst", async_mock.MagicMock( + return_value=async_mock.MagicMock( + exception=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + ), + ) + ) as mock_log_exception: + # async_mock.patch.object( + # test_module, "get_logger_inst", async_mock.MagicMock( + # return_value=async_mock.MagicMock( + # exception=async_mock.MagicMock(), + # warning=async_mock.MagicMock(), + # ), + # ) + # ) as mock_logger + _manager = CredentialManager(self.profile) mock_delete_ex.side_effect = test_module.StorageError() - (exch, ack) = await self.manager.send_credential_ack(stored_exchange) + (exch, ack) = await _manager.send_credential_ack(stored_exchange) assert ack._thread + # raise Exception(str(mock_logger.exception.call_count) + "\n\n" + str(mock_logger.warning.call_count)) + raise Exception(str(mock_log_exception.call_count)) mock_log_exception.assert_called_once() # cover exception log-and-continue mock_log_warning.assert_called_once() # no BaseResponder assert exch.state == V10CredentialExchange.STATE_ACKED mock_responder = MockResponder() # cover with responder self.context.injector.bind_instance(BaseResponder, mock_responder) - (exch, ack) = await self.manager.send_credential_ack(stored_exchange) + (exch, ack) = await _manager.send_credential_ack(stored_exchange) assert ack._thread assert exch.state == V10CredentialExchange.STATE_ACKED diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py index 66ac360d3e..27afc637dd 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py @@ -42,7 +42,6 @@ from ...handler import V20CredFormatError from ..handler import IndyCredFormatHandler -from ..handler import LOGGER as INDY_LOGGER TEST_DID = "LjgpST2rjsoxYegQDRm7EL" SCHEMA_NAME = "bc-reg" @@ -289,7 +288,11 @@ async def test_get_indy_detail_record(self): await details_indy[1].save(self.session) # exercise logger warning on get() with async_mock.patch.object( - INDY_LOGGER, "warning", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), + ), ) as mock_warning: assert await self.handler.get_detail_record(cred_ex_id) in details_indy mock_warning.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py index f17202fd31..afa816549e 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py @@ -59,7 +59,6 @@ from ...handler import V20CredFormatError from ..handler import LDProofCredFormatHandler -from ..handler import LOGGER as LD_PROOF_LOGGER TEST_DID_SOV = "did:sov:LjgpST2rjsoxYegQDRm7EL" TEST_DID_KEY = "did:key:z6Mkgg342Ycpuk263R9d8Aq6MUaxPn1DDeHyGo38EefXmgDL" @@ -214,7 +213,11 @@ async def test_get_ld_proof_detail_record(self): await details_ld_proof[1].save(self.session) # exercise logger warning on get() with async_mock.patch.object( - LD_PROOF_LOGGER, "warning", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), + ), ) as mock_warning: assert await self.handler.get_detail_record(cred_ex_id) in details_ld_proof mock_warning.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py index 66e295ce34..34409dff11 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py @@ -117,7 +117,11 @@ async def test_called_auto_request_x(self): with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() ) as mock_send_reply, async_mock.patch.object( - handler._logger, "exception", async_mock.CoroutineMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py index daaf4c0d79..d9d7ae9acc 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py @@ -91,7 +91,11 @@ async def test_called_auto_offer_x(self): with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() ) as mock_send_reply, async_mock.patch.object( - handler._logger, "exception", async_mock.CoroutineMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py index 25edba8b36..80fc118bf0 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py @@ -126,7 +126,11 @@ async def test_called_auto_issue_x(self): with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() ) as mock_send_reply, async_mock.patch.object( - handler._logger, "exception", async_mock.CoroutineMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py b/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py index d46fd498d7..ff41602295 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py @@ -128,7 +128,11 @@ async def test_save_error_state(self): with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( - test_module.LOGGER, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="test") diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py index b1ed8216ea..c7194c55da 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py @@ -1286,9 +1286,17 @@ async def test_send_cred_ack(self): ) as mock_save_ex, async_mock.patch.object( V20CredExRecord, "delete_record", autospec=True ) as mock_delete_ex, async_mock.patch.object( - test_module.LOGGER, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exception, async_mock.patch.object( - test_module.LOGGER, "warning", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), + ), ) as mock_log_warning: mock_delete_ex.side_effect = test_module.StorageError() (_, ack) = await self.manager.send_cred_ack(stored_exchange) diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py index c8b69357cb..7416c8775b 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py @@ -13,6 +13,8 @@ from ...manager import OutOfBandManagerError from ...messages.problem_report import OOBProblemReport, ProblemReportReason +from .. import problem_report_handler as test_module + @pytest.fixture() async def request_context() -> RequestContext: @@ -69,8 +71,12 @@ async def test_exception(self, mock_oob_mgr, request_context, connection_record) ) handler = test_module.OOBProblemReportMessageHandler() with async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() - ) as mock_exc_logger: + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), + ) as mock_exc_logger: responder = MockResponder() await handler.handle(context=request_context, responder=responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py index 28b4747502..6253d2d141 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py @@ -106,7 +106,11 @@ async def test_called_auto_verify_x(self): responder = MockResponder() with async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py index 95c963f704..3144cb5945 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py @@ -100,7 +100,11 @@ async def test_called_auto_request_x(self): responder = MockResponder() with async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py index 83329461a4..d40bc9c1a4 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py @@ -350,7 +350,11 @@ async def test_called_auto_present_x(self): responder = MockResponder() with async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py b/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py index 0498a89a8e..8ca486bc11 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py @@ -132,7 +132,11 @@ async def test_save_error_state(self): with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( - test_module.LOGGER, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="testing") diff --git a/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py index 97f77aac9e..c8914cbe54 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py @@ -646,7 +646,11 @@ async def test_create_presentation_no_revocation(self): ) as save_ex, async_mock.patch.object( test_module, "AttachDecorator", autospec=True ) as mock_attach_decorator, async_mock.patch.object( - test_indy_util_module.LOGGER, "info", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(info=async_mock.MagicMock()), + ), ) as mock_log_info: mock_attach_decorator.data_base64 = async_mock.MagicMock( return_value=mock_attach_decorator diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py index 8143083c0a..c2e0d283fc 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py @@ -1968,7 +1968,11 @@ async def test_verify_received_pres_invalid_jsonpath(self): error_msg="error", ) with async_mock.patch.object( - test_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ), ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) mock_log_err.assert_called_once() @@ -2021,7 +2025,11 @@ async def test_verify_received_pres_no_match_a(self): error_msg="error", ) with async_mock.patch.object( - test_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ), ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) mock_log_err.assert_called_once() @@ -2074,7 +2082,11 @@ async def test_verify_received_pres_no_match_b(self): error_msg="error", ) with async_mock.patch.object( - test_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ), ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) mock_log_err.assert_called_once() @@ -2124,7 +2136,11 @@ async def test_verify_received_pres_limit_disclosure_fail_a(self): error_msg="error", ) with async_mock.patch.object( - test_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ), ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) mock_log_err.assert_called_once() @@ -2174,7 +2190,11 @@ async def test_verify_received_pres_limit_disclosure_fail_b(self): error_msg="error", ) with async_mock.patch.object( - test_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ), ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) mock_log_err.assert_called_once() @@ -2264,7 +2284,11 @@ async def test_verify_received_pres_fail_schema_filter(self): error_msg="error", ) with async_mock.patch.object( - test_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ), ) as mock_log_err, async_mock.patch.object( jsonld, "expand", async_mock.MagicMock() ) as mock_jsonld_expand: diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py index b28027c263..16bfb2e7ff 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py @@ -106,7 +106,11 @@ async def test_called_auto_verify_x(self): responder = MockResponder() with async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py index 033742133e..51649836cb 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py @@ -100,7 +100,11 @@ async def test_called_auto_request_x(self): responder = MockResponder() with async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py index 786d78bee5..cb2f8671e7 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py @@ -363,7 +363,11 @@ async def test_called_auto_present_x(self): responder = MockResponder() with async_mock.patch.object( - handler._logger, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py b/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py index ba27e20f45..809b1bb6bc 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py @@ -129,7 +129,11 @@ async def test_save_error_state(self): with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( - test_module.LOGGER, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_log_exc: mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="testing") diff --git a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py index 51da3c6450..b3d8f32348 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py @@ -1046,7 +1046,11 @@ async def test_create_pres_no_revocation(self): ) as save_ex, async_mock.patch.object( test_indy_handler, "AttachDecorator", autospec=True ) as mock_attach_decorator, async_mock.patch.object( - test_indy_util_module.LOGGER, "info", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(info=async_mock.MagicMock()), + ), ) as mock_log_info: mock_attach_decorator.data_base64 = async_mock.MagicMock( return_value=mock_attach_decorator @@ -1144,7 +1148,11 @@ async def test_create_pres_bad_revoc_state(self): ) as mock_attach_decorator, async_mock.patch.object( test_indy_util_module, "RevocationRegistry", autospec=True ) as mock_rr, async_mock.patch.object( - test_indy_util_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ), ) as mock_log_error: mock_rr.from_definition = async_mock.MagicMock(return_value=more_magic_rr) diff --git a/aries_cloudagent/transport/outbound/tests/test_manager.py b/aries_cloudagent/transport/outbound/tests/test_manager.py index 7521173734..f046a5edb5 100644 --- a/aries_cloudagent/transport/outbound/tests/test_manager.py +++ b/aries_cloudagent/transport/outbound/tests/test_manager.py @@ -304,11 +304,23 @@ async def test_finished_deliver_x_log_debug(self): mgr = OutboundTransportManager(profile, mock_handle_not_delivered) mgr.outbound_buffer.append(mock_queued) with async_mock.patch.object( - test_module.LOGGER, "exception", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), ) as mock_logger_exception, async_mock.patch.object( - test_module.LOGGER, "error", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ), ) as mock_logger_error, async_mock.patch.object( - test_module.LOGGER, "isEnabledFor", async_mock.MagicMock() + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(isEnabledFor=async_mock.MagicMock()), + ), ) as mock_logger_enabled, async_mock.patch.object( mgr, "process_queued", async_mock.MagicMock() ) as mock_process: From c57eaf6060bd743cb585848f66a535612732c1a5 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Wed, 16 Aug 2023 23:21:35 +0530 Subject: [PATCH 03/18] unit test changes Signed-off-by: Shaanjot Gill --- aries_cloudagent/config/logging.py | 1 + .../v1_0/tests/test_mediation_manager.py | 4 +- .../v1_0/tests/test_manager.py | 34 ++++--- .../issue_credential/v2_0/formats/handler.py | 2 - .../v2_0/formats/indy/handler.py | 2 - .../v2_0/formats/indy/tests/test_handler.py | 16 ++-- .../v2_0/formats/ld_proof/handler.py | 2 - .../formats/ld_proof/tests/test_handler.py | 16 ++-- .../v2_0/tests/test_manager.py | 20 ++--- .../tests/test_problem_report_handler.py | 12 +-- .../present_proof/v1_0/tests/test_manager.py | 9 +- .../present_proof/v2_0/formats/dif/handler.py | 9 +- .../v2_0/formats/dif/tests/test_handler.py | 90 ++++++++++--------- .../present_proof/v2_0/formats/handler.py | 7 +- .../v2_0/formats/indy/handler.py | 5 +- .../present_proof/v2_0/tests/test_manager.py | 7 +- .../resolver/default/tests/test_universal.py | 16 +++- .../resolver/tests/test_did_resolver.py | 30 +++++-- .../transport/outbound/tests/test_manager.py | 18 +--- 19 files changed, 149 insertions(+), 151 deletions(-) diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index 8f4e4b75b2..7e61b9a138 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -1,4 +1,5 @@ """Utilities related to logging.""" + import asyncio from datetime import datetime, timedelta from io import TextIOWrapper diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py index c2f86812a4..9c1c14bb85 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py @@ -419,7 +419,7 @@ async def test_store_update_results( return_value=async_mock.MagicMock( error=async_mock.MagicMock(), ), - ) + ), ) as mock_logger_error: _manager_with_mock_logger = MediationManager(profile) mock_route_rec_query.side_effect = StorageNotFoundError("no record") @@ -436,7 +436,7 @@ async def test_store_update_results( return_value=async_mock.MagicMock( error=async_mock.MagicMock(), ), - ) + ), ) as mock_logger_error: _manager_with_mock_logger = MediationManager(profile) mock_route_rec_query.return_value = [ diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py index 7d28dce2c6..8159c5f07b 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py @@ -1546,35 +1546,31 @@ async def test_send_credential_ack(self): new_with_id=True, ) await stored_exchange.save(self.session) + mock_logger_inst = async_mock.MagicMock( + exception=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + ) with async_mock.patch.object( V10CredentialExchange, "save", autospec=True ) as mock_save_ex, async_mock.patch.object( V10CredentialExchange, "delete_record", autospec=True ) as mock_delete_ex, async_mock.patch.object( - test_module, "get_logger_inst", async_mock.MagicMock( - return_value=async_mock.MagicMock( - exception=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - ), - ) - ) as mock_log_exception: - # async_mock.patch.object( - # test_module, "get_logger_inst", async_mock.MagicMock( - # return_value=async_mock.MagicMock( - # exception=async_mock.MagicMock(), - # warning=async_mock.MagicMock(), - # ), - # ) - # ) as mock_logger + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=mock_logger_inst, + ), + ) as mock_logger: _manager = CredentialManager(self.profile) mock_delete_ex.side_effect = test_module.StorageError() (exch, ack) = await _manager.send_credential_ack(stored_exchange) assert ack._thread - # raise Exception(str(mock_logger.exception.call_count) + "\n\n" + str(mock_logger.warning.call_count)) - raise Exception(str(mock_log_exception.call_count)) - mock_log_exception.assert_called_once() # cover exception log-and-continue - mock_log_warning.assert_called_once() # no BaseResponder + mock_logger.assert_called_once() + assert ( + mock_logger_inst.exception.call_count == 1 + ) # cover exception log-and-continue + assert mock_logger_inst.warning.call_count == 1 # no BaseResponder assert exch.state == V10CredentialExchange.STATE_ACKED mock_responder = MockResponder() # cover with responder diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py index ea2d314bd5..33df21616e 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py @@ -17,8 +17,6 @@ from ..messages.cred_issue import V20CredIssue from ..models.cred_ex_record import V20CredExRecord -LOGGER = logging.getLogger(__name__) - CredFormatAttachment = Tuple[V20CredFormat, AttachDecorator] diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py index e00f4f9944..386028a8a6 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py @@ -1,7 +1,5 @@ """V2.0 issue-credential indy credential format handler.""" -import logging - from marshmallow import RAISE import json from typing import Mapping, Tuple diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py index 27afc637dd..96cda66574 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py @@ -286,16 +286,16 @@ async def test_get_indy_detail_record(self): ] await details_indy[0].save(self.session) await details_indy[1].save(self.session) # exercise logger warning on get() - + mock_logger = async_mock.MagicMock( + return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), + ) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), - ), - ) as mock_warning: + self.handler, + "_logger", + mock_logger, + ): assert await self.handler.get_detail_record(cred_ex_id) in details_indy - mock_warning.assert_called_once() + assert mock_logger.warning.call_count == 1 async def test_check_uniqueness(self): with async_mock.patch.object( diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py index 3f18a40a4b..15705bf3e4 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py @@ -1,7 +1,5 @@ """V2.0 issue-credential linked data proof credential format handler.""" - -import logging from typing import Mapping, Optional from marshmallow import EXCLUDE, INCLUDE diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py index afa816549e..716c386e12 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py @@ -211,16 +211,16 @@ async def test_get_ld_proof_detail_record(self): ] await details_ld_proof[0].save(self.session) await details_ld_proof[1].save(self.session) # exercise logger warning on get() - + mock_logger = async_mock.MagicMock( + return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), + ) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), - ), - ) as mock_warning: + self.handler, + "_logger", + mock_logger, + ): assert await self.handler.get_detail_record(cred_ex_id) in details_ld_proof - mock_warning.assert_called_once() + assert mock_logger.warning.call_count == 1 async def test_assert_can_issue_with_id_and_proof_type(self): with self.assertRaises(V20CredFormatError) as context: diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py index c7194c55da..727f7d9d3a 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py @@ -1280,7 +1280,10 @@ async def test_send_cred_ack(self): trace=False, auto_remove=True, ) - + mock_logger_inst = async_mock.MagicMock( + exception=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + ) with async_mock.patch.object( V20CredExRecord, "save", autospec=True ) as mock_save_ex, async_mock.patch.object( @@ -1289,21 +1292,14 @@ async def test_send_cred_ack(self): test_module, "get_logger_inst", async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + return_value=mock_logger_inst, ), - ) as mock_log_exception, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), - ), - ) as mock_log_warning: + ) as mock_logger: mock_delete_ex.side_effect = test_module.StorageError() (_, ack) = await self.manager.send_cred_ack(stored_exchange) assert ack._thread - mock_log_exception.assert_called_once() # cover exception log-and-continue - mock_log_warning.assert_called_once() # no BaseResponder - + mock_logger_inst.exception.call_count == 1 # cover exception log-and-continue + mock_logger_inst.warning.call_count == 1 # no BaseResponder mock_responder = MockResponder() # cover with responder self.context.injector.bind_instance(BaseResponder, mock_responder) (cx_rec, ack) = await self.manager.send_cred_ack(stored_exchange) diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py index 7416c8775b..594ef505db 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py @@ -71,12 +71,12 @@ async def test_exception(self, mock_oob_mgr, request_context, connection_record) ) handler = test_module.OOBProblemReportMessageHandler() with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_exc_logger: + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), + ), + ) as mock_exc_logger: responder = MockResponder() await handler.handle(context=request_context, responder=responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py index c8914cbe54..386c52a6e6 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py @@ -645,13 +645,7 @@ async def test_create_presentation_no_revocation(self): V10PresentationExchange, "save", autospec=True ) as save_ex, async_mock.patch.object( test_module, "AttachDecorator", autospec=True - ) as mock_attach_decorator, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(info=async_mock.MagicMock()), - ), - ) as mock_log_info: + ) as mock_attach_decorator: mock_attach_decorator.data_base64 = async_mock.MagicMock( return_value=mock_attach_decorator ) @@ -670,7 +664,6 @@ async def test_create_presentation_no_revocation(self): for pred_reft_spec in req_creds["requested_predicates"].values(): pred_reft_spec["timestamp"] = 1234567890 await self.manager.create_presentation(exchange_in, req_creds) - mock_log_info.assert_called_once() async def test_create_presentation_bad_revoc_state(self): exchange_in = V10PresentationExchange() diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py index 868d7148bf..2236a2a76d 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py @@ -1,7 +1,6 @@ """V2.0 present-proof dif presentation-exchange format handler.""" import json -import logging from marshmallow import RAISE from typing import Mapping, Tuple, Sequence @@ -48,8 +47,6 @@ from ..handler import V20PresFormatHandler, V20PresFormatHandlerError -LOGGER = logging.getLogger(__name__) - class DIFPresFormatHandler(V20PresFormatHandler): """DIF presentation format handler.""" @@ -356,7 +353,7 @@ async def create_pres( except StorageNotFoundError as err: raise V20PresFormatHandlerError(err) except TypeError as err: - LOGGER.error(str(err)) + self._logger.error(str(err)) responder = self._profile.inject_or(BaseResponder) if responder: report = ProblemReport( @@ -391,7 +388,7 @@ async def create_pres( ) return self.get_format_data(PRES_20, pres) except DIFPresExchError as err: - LOGGER.error(str(err)) + self._logger.error(str(err)) responder = self._profile.inject_or(BaseResponder) if responder: report = ProblemReport( @@ -444,7 +441,7 @@ async def receive_pres(self, message: V20Pres, pres_ex_record: V20PresExRecord): await dif_handler.verify_received_pres(pd=pres_definition, pres=dif_proof) return True except DIFPresExchError as err: - LOGGER.error(str(err)) + self._logger.error(str(err)) responder = self._profile.inject_or(BaseResponder) if responder: report = ProblemReport( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py index c2e0d283fc..099195f0fd 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py @@ -1967,15 +1967,16 @@ async def test_verify_received_pres_invalid_jsonpath(self): auto_present=True, error_msg="error", ) + mock_logger = async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ), - ) as mock_log_err: + self.handler, + "_logger", + mock_logger, + ): await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - mock_log_err.assert_called_once() + assert mock_logger.error.call_count == 1 async def test_verify_received_pres_no_match_a(self): dif_proof_req = deepcopy(DIF_PRES_REQUEST_B) @@ -2024,15 +2025,16 @@ async def test_verify_received_pres_no_match_a(self): auto_present=True, error_msg="error", ) + mock_logger = async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ), - ) as mock_log_err: + self.handler, + "_logger", + mock_logger, + ): await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - mock_log_err.assert_called_once() + assert mock_logger.error.call_count == 1 async def test_verify_received_pres_no_match_b(self): dif_proof_req = deepcopy(DIF_PRES_REQUEST_B) @@ -2081,15 +2083,16 @@ async def test_verify_received_pres_no_match_b(self): auto_present=True, error_msg="error", ) + mock_logger = async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ), - ) as mock_log_err: + self.handler, + "_logger", + mock_logger, + ): await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - mock_log_err.assert_called_once() + assert mock_logger.error.call_count == 1 async def test_verify_received_pres_limit_disclosure_fail_a(self): dif_proof = deepcopy(DIF_PRES) @@ -2135,15 +2138,16 @@ async def test_verify_received_pres_limit_disclosure_fail_a(self): auto_present=True, error_msg="error", ) + mock_logger = async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ), - ) as mock_log_err: + self.handler, + "_logger", + mock_logger, + ): await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - mock_log_err.assert_called_once() + assert mock_logger.error.call_count == 1 async def test_verify_received_pres_limit_disclosure_fail_b(self): dif_proof = deepcopy(DIF_PRES) @@ -2189,15 +2193,16 @@ async def test_verify_received_pres_limit_disclosure_fail_b(self): auto_present=True, error_msg="error", ) + mock_logger = async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ), - ) as mock_log_err: + self.handler, + "_logger", + mock_logger, + ): await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - mock_log_err.assert_called_once() + assert mock_logger.error.call_count == 1 async def test_verify_received_pres_fail_schema_filter(self): dif_proof = deepcopy(DIF_PRES) @@ -2283,18 +2288,19 @@ async def test_verify_received_pres_fail_schema_filter(self): auto_present=True, error_msg="error", ) + mock_logger = async_mock.MagicMock( + return_value=async_mock.MagicMock(error=async_mock.MagicMock()), + ) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ), - ) as mock_log_err, async_mock.patch.object( + self.handler, + "_logger", + mock_logger, + ), async_mock.patch.object( jsonld, "expand", async_mock.MagicMock() ) as mock_jsonld_expand: mock_jsonld_expand.return_value = EXPANDED_CRED_FHIR_TYPE_2 await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - mock_log_err.assert_called_once() + assert mock_logger.error.call_count == 1 async def test_create_pres_catch_typeerror(self): self.context.injector.bind_instance( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py index 1d8a2e5d07..766a984b42 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py @@ -6,14 +6,13 @@ from .....core.error import BaseError from .....core.profile import Profile +from .....config.logging import get_logger_inst from .....messaging.decorators.attach_decorator import AttachDecorator from ..messages.pres import V20Pres from ..messages.pres_format import V20PresFormat from ..models.pres_exchange import V20PresExRecord -LOGGER = logging.getLogger(__name__) - PresFormatAttachment = Tuple[V20PresFormat, AttachDecorator] @@ -30,6 +29,10 @@ def __init__(self, profile: Profile): """Initialize PresExchange Handler.""" super().__init__() self._profile = profile + self._logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) @property def profile(self) -> Profile: diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py index 16ebb7fec6..1892a36ee9 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py @@ -1,7 +1,6 @@ """V2.0 present-proof indy presentation-exchange format handler.""" import json -import logging from marshmallow import RAISE from typing import Mapping, Tuple @@ -30,8 +29,6 @@ from ..handler import V20PresFormatHandler, V20PresFormatHandlerError -LOGGER = logging.getLogger(__name__) - class IndyPresExchangeHandler(V20PresFormatHandler): """Indy presentation format handler.""" @@ -146,7 +143,7 @@ async def create_pres( ) ) except ValueError as err: - LOGGER.warning(f"{err}") + self._logger.warning(f"{err}") raise V20PresFormatHandlerError( f"No matching Indy credentials found: {err}" ) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py index b3d8f32348..b017e1d858 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py @@ -1040,7 +1040,7 @@ async def test_create_pres_no_revocation(self): ) self.holder.create_presentation = async_mock.CoroutineMock(return_value="{}") self.profile.context.injector.bind_instance(IndyHolder, self.holder) - + mock_logger = async_mock.MagicMock(info=async_mock.MagicMock()) with async_mock.patch.object( V20PresExRecord, "save", autospec=True ) as save_ex, async_mock.patch.object( @@ -1049,9 +1049,9 @@ async def test_create_pres_no_revocation(self): test_module, "get_logger_inst", async_mock.MagicMock( - return_value=async_mock.MagicMock(info=async_mock.MagicMock()), + return_value=mock_logger, ), - ) as mock_log_info: + ): mock_attach_decorator.data_base64 = async_mock.MagicMock( return_value=mock_attach_decorator ) @@ -1084,7 +1084,6 @@ async def test_create_pres_no_revocation(self): } } await self.manager.create_pres(px_rec_in, request_data) - mock_log_info.assert_called_once() async def test_create_pres_bad_revoc_state(self): pres_request = V20PresRequest( diff --git a/aries_cloudagent/resolver/default/tests/test_universal.py b/aries_cloudagent/resolver/default/tests/test_universal.py index 96e5d0827f..51bdde6f9f 100644 --- a/aries_cloudagent/resolver/default/tests/test_universal.py +++ b/aries_cloudagent/resolver/default/tests/test_universal.py @@ -17,9 +17,19 @@ @pytest.fixture async def resolver(): """Resolver fixture.""" - yield UniversalResolver( - endpoint="https://example.com", supported_did_regex=re.compile("^did:sov:.*$") - ) + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock( + debug=async_mock.MagicMock(), + ), + ), + ): + yield UniversalResolver( + endpoint="https://example.com", + supported_did_regex=re.compile("^did:sov:.*$"), + ) @pytest.fixture diff --git a/aries_cloudagent/resolver/tests/test_did_resolver.py b/aries_cloudagent/resolver/tests/test_did_resolver.py index 26d984a12b..80eeb6e71b 100644 --- a/aries_cloudagent/resolver/tests/test_did_resolver.py +++ b/aries_cloudagent/resolver/tests/test_did_resolver.py @@ -18,6 +18,7 @@ ResolverType, ) from ..did_resolver import DIDResolver +from .. import did_resolver as test_module from . import DOC @@ -89,11 +90,20 @@ async def _resolve(self, profile, did, accept): @pytest.fixture def resolver(): - did_resolver_registry = [] - for method in TEST_DID_METHODS: - resolver = MockResolver([method], DIDDocument.deserialize(DOC)) - did_resolver_registry.append(resolver) - return DIDResolver(did_resolver_registry) + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock( + debug=async_mock.MagicMock(), + ), + ), + ): + did_resolver_registry = [] + for method in TEST_DID_METHODS: + resolver = MockResolver([method], DIDDocument.deserialize(DOC)) + did_resolver_registry.append(resolver) + yield DIDResolver(did_resolver_registry) @pytest.fixture @@ -207,5 +217,13 @@ async def test_resolve_did_x_not_found(profile): py_did = DID("did:cowsay:EiDahaOGH-liLLdDtTxEAdc8i-cfCz-WUcQdRJheMVNn3A") cowsay_resolver_not_found = MockResolver(["cowsay"], resolved=DIDNotFound()) resolver = DIDResolver([cowsay_resolver_not_found]) - with pytest.raises(DIDNotFound): + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock( + debug=async_mock.MagicMock(), + ), + ), + ), pytest.raises(DIDNotFound): await resolver.resolve(profile, py_did) diff --git a/aries_cloudagent/transport/outbound/tests/test_manager.py b/aries_cloudagent/transport/outbound/tests/test_manager.py index f046a5edb5..7521173734 100644 --- a/aries_cloudagent/transport/outbound/tests/test_manager.py +++ b/aries_cloudagent/transport/outbound/tests/test_manager.py @@ -304,23 +304,11 @@ async def test_finished_deliver_x_log_debug(self): mgr = OutboundTransportManager(profile, mock_handle_not_delivered) mgr.outbound_buffer.append(mock_queued) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), + test_module.LOGGER, "exception", async_mock.MagicMock() ) as mock_logger_exception, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ), + test_module.LOGGER, "error", async_mock.MagicMock() ) as mock_logger_error, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(isEnabledFor=async_mock.MagicMock()), - ), + test_module.LOGGER, "isEnabledFor", async_mock.MagicMock() ) as mock_logger_enabled, async_mock.patch.object( mgr, "process_queued", async_mock.MagicMock() ) as mock_process: From cb1cb825d7cc1bceab4c15f86cb44883566910e6 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Thu, 17 Aug 2023 21:18:21 +0530 Subject: [PATCH 04/18] unit tests fix Signed-off-by: Shaanjot Gill --- aries_cloudagent/resolver/did_resolver.py | 6 +++- .../resolver/tests/test_did_resolver.py | 36 ++++++++++++++----- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/aries_cloudagent/resolver/did_resolver.py b/aries_cloudagent/resolver/did_resolver.py index a25576254c..382ebaa348 100644 --- a/aries_cloudagent/resolver/did_resolver.py +++ b/aries_cloudagent/resolver/did_resolver.py @@ -115,7 +115,11 @@ async def _match_did_to_resolver( for resolver in self.resolvers if await resolver.supports(profile, did) ] - LOGGER.debug("Valid resolvers for DID %s: %s", did, valid_resolvers) + _logger: logging.Logger = get_logger_inst( + profile=profile, + logger_name=__name__, + ) + _logger.debug("Valid resolvers for DID %s: %s", did, valid_resolvers) native_resolvers = filter(lambda resolver: resolver.native, valid_resolvers) non_native_resolvers = filter( lambda resolver: not resolver.native, valid_resolvers diff --git a/aries_cloudagent/resolver/tests/test_did_resolver.py b/aries_cloudagent/resolver/tests/test_did_resolver.py index 80eeb6e71b..a1ad2dd1a0 100644 --- a/aries_cloudagent/resolver/tests/test_did_resolver.py +++ b/aries_cloudagent/resolver/tests/test_did_resolver.py @@ -136,9 +136,18 @@ async def test_match_did_to_resolver_native_priority(profile): non_native = MockResolver(["sov"], native=False) registry = [non_native, native] resolver = DIDResolver(registry) - assert [native, non_native] == await resolver._match_did_to_resolver( - profile, TEST_DID0 - ) + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock( + debug=async_mock.MagicMock(), + ), + ) + ): + assert [native, non_native] == await resolver._match_did_to_resolver( + profile, TEST_DID0 + ) @pytest.mark.asyncio @@ -149,12 +158,21 @@ async def test_match_did_to_resolver_registration_order(profile): native4 = MockResolver(["sov"], native=True) registry = [native1, native2, non_native3, native4] resolver = DIDResolver(registry) - assert [ - native1, - native2, - native4, - non_native3, - ] == await resolver._match_did_to_resolver(profile, TEST_DID0) + with async_mock.patch.object( + test_module, + "get_logger_inst", + async_mock.MagicMock( + return_value=async_mock.MagicMock( + debug=async_mock.MagicMock(), + ), + ) + ): + assert [ + native1, + native2, + native4, + non_native3, + ] == await resolver._match_did_to_resolver(profile, TEST_DID0) @pytest.mark.asyncio From 214803fc9d0c70171ba3de3391538d7602249197 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Thu, 17 Aug 2023 21:24:41 +0530 Subject: [PATCH 05/18] fmt fix Signed-off-by: Shaanjot Gill --- aries_cloudagent/resolver/tests/test_did_resolver.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/aries_cloudagent/resolver/tests/test_did_resolver.py b/aries_cloudagent/resolver/tests/test_did_resolver.py index a1ad2dd1a0..a1ffe8d8a3 100644 --- a/aries_cloudagent/resolver/tests/test_did_resolver.py +++ b/aries_cloudagent/resolver/tests/test_did_resolver.py @@ -143,7 +143,7 @@ async def test_match_did_to_resolver_native_priority(profile): return_value=async_mock.MagicMock( debug=async_mock.MagicMock(), ), - ) + ), ): assert [native, non_native] == await resolver._match_did_to_resolver( profile, TEST_DID0 @@ -165,7 +165,7 @@ async def test_match_did_to_resolver_registration_order(profile): return_value=async_mock.MagicMock( debug=async_mock.MagicMock(), ), - ) + ), ): assert [ native1, From 85a52f8ef1653f80df1a511db77d57cafa8b1e6c Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Tue, 22 Aug 2023 20:19:49 +0530 Subject: [PATCH 06/18] optimization + demo updates Signed-off-by: Shaanjot Gill --- aries_cloudagent/config/logging.py | 182 ++++++++++++++++------------- aries_cloudagent/config/util.py | 7 +- demo/runners/agent_container.py | 72 ++++++++++++ demo/runners/alice.py | 15 +++ demo/runners/faber.py | 15 +++ demo/runners/performance.py | 119 ++++++++++++++++++- demo/runners/support/agent.py | 36 ++++++ 7 files changed, 359 insertions(+), 87 deletions(-) diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index 7e61b9a138..e02449d8a1 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -11,7 +11,7 @@ import re import sys import time as mod_time -from typing import Optional, TextIO, TYPE_CHECKING +from typing import Optional, TextIO, Tuple, TYPE_CHECKING import pkg_resources from portalocker import LOCK_EX, lock, unlock @@ -60,6 +60,9 @@ def configure( logging_config_path: str = None, log_level: str = None, log_file: str = None, + log_interval: int = None, + log_bak_count: int = None, + log_at_when: str = None, ): """Configure logger. @@ -83,9 +86,11 @@ def configure( if log_file: logging.root.handlers.clear() - logging.root.handlers.append( - logging.FileHandler(log_file, encoding="utf-8") + timed_file_handler, std_out_handler = get_log_file_handlers( + log_file, log_interval, log_bak_count, log_at_when ) + logging.root.handlers.append(timed_file_handler) + logging.root.handlers.append(std_out_handler) if log_level: log_level = log_level.upper() @@ -514,6 +519,29 @@ def doRollover(self): ) +def get_log_file_handlers( + log_file_name: str, + log_interval: int = None, + log_bak_count: int = None, + log_at_when: str = None, +) -> Tuple[TimedRotatingFileMultiProcessHandler, logging.StreamHandler]: + """Get TimedRotatingFileMultiProcessHandler and StreamHandler log handlers.""" + file_path = os.path.join( + os.path.dirname(os.path.realpath(__file__)).replace( + "aries_cloudagent/config", "" + ), + log_file_name, + ) + timed_file_handler = TimedRotatingFileMultiProcessHandler( + filename=file_path, + interval=log_interval or 7, + when=log_at_when or "d", + backupCount=log_bak_count or 1, + ) + std_out_handler = logging.StreamHandler(sys.stdout) + return (timed_file_handler, std_out_handler) + + def clear_prev_handlers(logger: logging.Logger) -> logging.Logger: """Remove all handler classes associated with logger instance.""" iter_count = 0 @@ -526,36 +554,41 @@ def clear_prev_handlers(logger: logging.Logger) -> logging.Logger: def get_logger_inst(profile: "Profile", logger_name) -> logging.Logger: """Return a logger instance with provided name and handlers.""" - did_ident = get_did_ident(profile) - if did_ident: - logger_name = f"{logger_name}_{did_ident}" - return get_logger_with_handlers( - settings=profile.settings, - logger=logging.getLogger(logger_name), - did_ident=did_ident, - interval=profile.settings.get("log.handler_interval") or 7, - backup_count=profile.settings.get("log.handler_bakcount") or 1, - at_when=profile.settings.get("log.handler_when") or "d", - ) + if not profile.settings.get("log.file"): + return logging.getLogger(logger_name) + else: + did_ident = get_did_ident(profile) + if did_ident: + logger_name = f"{logger_name}_{did_ident}" + return get_logger_with_handlers( + settings=profile.settings, + logger=logging.getLogger(logger_name), + did_ident=did_ident, + interval=profile.settings.get("log.handler_interval") or 7, + backup_count=profile.settings.get("log.handler_bakcount") or 1, + at_when=profile.settings.get("log.handler_when") or "d", + ) def get_did_ident(profile: "Profile") -> Optional[str]: - """Get public did identifier for logging, if applicable.""" - did_ident = None - if profile.settings.get("log.file"): - - async def _fetch_did() -> Optional[str]: - async with profile.session() as session: - wallet = session.inject(BaseWallet) - req_did_info: DIDInfo = await wallet.get_public_did() - if not req_did_info: - req_did_info: DIDInfo = (await wallet.get_local_dids())[0] - if req_did_info: - did_ident = req_did_info.did - return did_ident - - loop = asyncio.get_event_loop() - did_ident = loop.run_until_complete(_fetch_did()) + """Get public did identifier for logging.""" + + async def _fetch_did() -> Optional[str]: + async with profile.session() as session: + wallet = session.inject(BaseWallet) + public_did_info: DIDInfo = await wallet.get_public_did() + req_did_info = None + _did = None + if not public_did_info: + local_did_info: DIDInfo = await wallet.get_local_dids() + if local_did_info: + req_did_info = local_did_info[0] + if req_did_info: + _did = req_did_info.did + return _did + + loop = asyncio.get_event_loop() + did_ident = loop.run_until_complete(_fetch_did()) return did_ident @@ -568,61 +601,48 @@ def get_logger_with_handlers( did_ident: str = None, ) -> logging.Logger: """Return logger instance with necessary handlers if required.""" - if settings.get("log.file"): - # Clear handlers set previously for this logger instance - logger = clear_prev_handlers(logger) - # log file handler - file_path = settings.get("log.file") - file_handler = TimedRotatingFileMultiProcessHandler( - filename=file_path, - interval=interval, - when=at_when, - backupCount=backup_count, - ) - if did_ident: - if settings.get("log.json_fmt"): - file_handler.setFormatter( - jsonlogger.JsonFormatter( - settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_ALIAS_PATTERN - ) - ) - else: - file_handler.setFormatter( - logging.Formatter( - settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_ALIAS_PATTERN - ) + # Clear handlers set previously for this logger instance + logger = clear_prev_handlers(logger) + # log file handler + file_handler, std_out_handler = get_log_file_handlers( + settings.get("log.file"), interval, backup_count, at_when + ) + if did_ident: + if settings.get("log.json_fmt"): + file_handler.setFormatter( + jsonlogger.JsonFormatter( + settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_ALIAS_PATTERN ) + ) else: - if settings.get("log.json_fmt"): - file_handler.setFormatter( - jsonlogger.JsonFormatter( - settings.get("log.fmt_pattern") - or LOG_FORMAT_FILE_NO_ALIAS_PATTERN - ) + file_handler.setFormatter( + logging.Formatter( + settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_ALIAS_PATTERN ) - else: - file_handler.setFormatter( - logging.Formatter( - settings.get("log.fmt_pattern") - or LOG_FORMAT_FILE_NO_ALIAS_PATTERN - ) + ) + else: + if settings.get("log.json_fmt"): + file_handler.setFormatter( + jsonlogger.JsonFormatter( + settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_NO_ALIAS_PATTERN ) - logger.addHandler(file_handler) - # stream console handler - std_out_handler = logging.StreamHandler(sys.stdout) - std_out_handler.setFormatter( - logging.Formatter( - settings.get("log.fmt_pattern") or LOG_FORMAT_STREAM_PATTERN ) - ) - logger.addHandler(std_out_handler) - if did_ident: - logger = logging.LoggerAdapter(logger, {"did": did_ident}) - # set log level - logger_level = ( - (settings.get("log.level")).upper() - if settings.get("log.level") - else logging.INFO + else: + file_handler.setFormatter( + logging.Formatter( + settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_NO_ALIAS_PATTERN + ) + ) + logger.addHandler(file_handler) + # stream console handler + std_out_handler.setFormatter( + logging.Formatter(settings.get("log.fmt_pattern") or LOG_FORMAT_STREAM_PATTERN) ) - logger.setLevel(logger_level) + logger.addHandler(std_out_handler) + if did_ident: + logger = logging.LoggerAdapter(logger, {"did": did_ident}) + # set log level + if settings.get("log.level"): + logger_level = settings.get("log.level").upper() + logger.setLevel(logger_level) return logger diff --git a/aries_cloudagent/config/util.py b/aries_cloudagent/config/util.py index 00a7d5c534..5376d014ba 100644 --- a/aries_cloudagent/config/util.py +++ b/aries_cloudagent/config/util.py @@ -15,7 +15,12 @@ def common_config(settings: Mapping[str, Any]): log_config = settings.get("log.config") log_level = settings.get("log.level") or os.getenv("LOG_LEVEL") log_file = settings.get("log.file") - LoggingConfigurator.configure(log_config, log_level, log_file) + log_interval = settings.get("log.handler_interval") + log_at_when = settings.get("log.handler_when") + log_bak_count = settings.get("log.handler_bakcount") + LoggingConfigurator.configure( + log_config, log_level, log_file, log_interval, log_bak_count, log_at_when + ) class BoundedInt: diff --git a/demo/runners/agent_container.py b/demo/runners/agent_container.py index b50a569134..e237061b8b 100644 --- a/demo/runners/agent_container.py +++ b/demo/runners/agent_container.py @@ -56,6 +56,11 @@ def __init__( endorser_role: str = None, revocation: bool = False, anoncreds_legacy_revocation: str = None, + log_file: str = None, + log_handler_config: str = None, + log_fmt_pattern: str = None, + log_level: str = None, + log_json_fmt: bool = False, **kwargs, ): extra_args = [] @@ -81,6 +86,11 @@ def __init__( endorser_role=endorser_role, revocation=revocation, extra_args=extra_args, + log_file=log_file, + log_handler_config=log_handler_config, + log_fmt_pattern=log_fmt_pattern, + log_json_fmt=log_json_fmt, + log_level=log_level, **kwargs, ) self.connection_id = None @@ -679,6 +689,11 @@ def __init__( reuse_connections: bool = False, taa_accept: bool = False, anoncreds_legacy_revocation: str = None, + log_file: str = None, + log_handler_config: str = None, + log_fmt_pattern: str = None, + log_json_fmt: bool = False, + log_level: str = None, ): # configuration parameters self.genesis_txns = genesis_txns @@ -702,6 +717,11 @@ def __init__( self.endorser_agent = None self.endorser_role = endorser_role self.anoncreds_legacy_revocation = anoncreds_legacy_revocation + self.log_file = log_file + self.log_handler_config = log_handler_config + self.log_fmt_pattern = log_fmt_pattern + self.log_json_fmt = log_json_fmt + self.log_level = log_level if endorser_role: # endorsers and authors need public DIDs (assume cred_type is Indy) if endorser_role == "author" or endorser_role == "endorser": @@ -748,6 +768,11 @@ async def initialize( aip=self.aip, arg_file=self.arg_file, endorser_role=self.endorser_role, + log_file=self.log_file, + log_handler_config=self.log_handler_config, + log_fmt_pattern=self.log_fmt_pattern, + log_json_fmt=self.log_json_fmt, + log_level=self.log_level, ) else: self.agent = the_agent @@ -1281,6 +1306,41 @@ def arg_parser(ident: str = None, port: int = 8020): action="store_true", help="Accept the ledger's TAA, if required", ) + parser.add_argument( + "--log-file", + type=str, + metavar="", + help="Output destination for the root logger.", + ) + parser.add_argument( + "--log-level", + type=str, + metavar="", + default=None, + help=( + "Specifies a custom logging level as one of: " + "('debug', 'info', 'warning', 'error', 'critical')" + ), + ) + parser.add_argument( + "--log-handler-config", + type=str, + metavar="", + help=( + "Specifies when, interval, backupCount for the TimedRotatingFileHandler." + ), + ) + parser.add_argument( + "--log-fmt-pattern", + type=str, + metavar="", + help="Specifies logging formatter pattern as string.", + ) + parser.add_argument( + "--log-json-fmt", + action="store_true", + help="JSON logging formatter.", + ) return parser @@ -1312,6 +1372,13 @@ async def create_agent_with_args(args, ident: str = None): with open(arg_file) as f: arg_file_dict = yaml.safe_load(f) + log_file = args.log_file or os.getenv("ACAPY_LOG_FILE") + log_level = args.log_level + log_handler_config = args.log_handler_config or os.getenv( + "ACAPY_LOG_HANDLER_CONFIG" + ) + log_fmt_pattern = args.log_fmt_pattern or os.getenv("ACAPY_LOG_FMT_PATTERN") + log_json_fmt = args.log_json_fmt or False # if we don't have a tails server url then guess it if ("revocation" in args and args.revocation) and not tails_server_base_url: # assume we're running in docker @@ -1389,6 +1456,11 @@ async def create_agent_with_args(args, ident: str = None): reuse_connections=reuse_connections, taa_accept=args.taa_accept, anoncreds_legacy_revocation=anoncreds_legacy_revocation, + log_file=log_file, + log_handler_config=log_handler_config, + log_fmt_pattern=log_fmt_pattern, + log_json_fmt=log_json_fmt, + log_level=log_level, ) return agent diff --git a/demo/runners/alice.py b/demo/runners/alice.py index 8bea579d29..32c9eebe0c 100644 --- a/demo/runners/alice.py +++ b/demo/runners/alice.py @@ -36,6 +36,11 @@ def __init__( no_auto: bool = False, aip: int = 20, endorser_role: str = None, + log_file: str = None, + log_handler_config: str = None, + log_fmt_pattern: str = None, + log_json_fmt: bool = False, + log_level: str = None, **kwargs, ): super().__init__( @@ -47,6 +52,11 @@ def __init__( seed=None, aip=aip, endorser_role=endorser_role, + log_file=log_file, + log_handler_config=log_handler_config, + log_fmt_pattern=log_fmt_pattern, + log_json_fmt=log_json_fmt, + log_level=log_level, **kwargs, ) self.connection_id = None @@ -130,6 +140,11 @@ async def main(args): wallet_type=alice_agent.wallet_type, aip=alice_agent.aip, endorser_role=alice_agent.endorser_role, + log_file=alice_agent.log_file, + log_handler_config=alice_agent.log_handler_config, + log_fmt_pattern=alice_agent.log_fmt_pattern, + log_json_fmt=alice_agent.log_json_fmt, + log_level=alice_agent.log_level, ) await alice_agent.initialize(the_agent=agent) diff --git a/demo/runners/faber.py b/demo/runners/faber.py index 5a26eb2669..166e15254a 100644 --- a/demo/runners/faber.py +++ b/demo/runners/faber.py @@ -47,6 +47,11 @@ def __init__( endorser_role: str = None, revocation: bool = False, anoncreds_legacy_revocation: str = None, + log_file: str = None, + log_handler_config: str = None, + log_fmt_pattern: str = None, + log_json_fmt: bool = False, + log_level: str = None, **kwargs, ): super().__init__( @@ -58,6 +63,11 @@ def __init__( endorser_role=endorser_role, revocation=revocation, anoncreds_legacy_revocation=anoncreds_legacy_revocation, + log_file=log_file, + log_handler_config=log_handler_config, + log_fmt_pattern=log_fmt_pattern, + log_json_fmt=log_json_fmt, + log_level=log_level, **kwargs, ) self.connection_id = None @@ -403,6 +413,11 @@ async def main(args): aip=faber_agent.aip, endorser_role=faber_agent.endorser_role, anoncreds_legacy_revocation=faber_agent.anoncreds_legacy_revocation, + log_file=faber_agent.log_file, + log_handler_config=faber_agent.log_handler_config, + log_fmt_pattern=faber_agent.log_fmt_pattern, + log_json_fmt=faber_agent.log_json_fmt, + log_level=faber_agent.log_level, ) faber_schema_name = "degree schema" diff --git a/demo/runners/performance.py b/demo/runners/performance.py index 4c79bf6437..cbbed96d03 100644 --- a/demo/runners/performance.py +++ b/demo/runners/performance.py @@ -32,11 +32,27 @@ def __init__( ident: str, port: int, prefix: str = None, + log_file: str = None, + log_handler_config: str = None, + log_fmt_pattern: str = None, + log_json_fmt: bool = False, + log_level: str = None, **kwargs, ): if prefix is None: prefix = ident - super().__init__(ident, port, port + 1, prefix=prefix, **kwargs) + super().__init__( + ident, + port, + port + 1, + prefix=prefix, + log_file=log_file, + log_handler_config=log_handler_config, + log_fmt_pattern=log_fmt_pattern, + log_json_fmt=log_json_fmt, + log_level=log_level, + **kwargs, + ) self._connection_id = None self._connection_ready = None self.credential_state = {} @@ -158,8 +174,27 @@ def check_task_exception(self, fut: asyncio.Task): class AliceAgent(BaseAgent): - def __init__(self, port: int, **kwargs): - super().__init__("Alice", port, seed=None, **kwargs) + def __init__( + self, + port: int, + log_file: str = None, + log_handler_config: str = None, + log_fmt_pattern: str = None, + log_json_fmt: bool = False, + log_level: str = None, + **kwargs, + ): + super().__init__( + "Alice", + port, + seed=None, + log_file=log_file, + log_handler_config=log_handler_config, + log_fmt_pattern=log_fmt_pattern, + log_json_fmt=log_json_fmt, + log_level=log_level, + **kwargs, + ) self.extra_args = [ "--auto-accept-invites", "--auto-accept-requests", @@ -195,8 +230,27 @@ async def propose_credential( class FaberAgent(BaseAgent): - def __init__(self, port: int, **kwargs): - super().__init__("Faber", port, seed="random", **kwargs) + def __init__( + self, + port: int, + log_file: str = None, + log_handler_config: str = None, + log_fmt_pattern: str = None, + log_json_fmt: bool = False, + log_level: str = None, + **kwargs, + ): + super().__init__( + "Faber", + port, + seed="random", + log_file=log_file, + log_handler_config=log_handler_config, + log_fmt_pattern=log_fmt_pattern, + log_json_fmt=log_json_fmt, + log_level=log_level, + **kwargs, + ) self.extra_args = [ "--auto-accept-invites", "--auto-accept-requests", @@ -282,6 +336,11 @@ async def main( batch_size: int = 30, wallet_type: str = None, arg_file: str = None, + log_file: str = None, + log_handler_config: str = None, + log_fmt_pattern: str = None, + log_json_fmt: bool = False, + log_level: str = None, ): if multi_ledger: genesis = None @@ -310,6 +369,11 @@ async def main( mediation=mediation, wallet_type=wallet_type, arg_file=arg_file, + log_file=log_file, + log_handler_config=log_handler_config, + log_fmt_pattern=log_fmt_pattern, + log_json_fmt=log_json_fmt, + log_level=log_level, ) await alice.listen_webhooks(start_port + 2) @@ -323,6 +387,11 @@ async def main( mediation=mediation, wallet_type=wallet_type, arg_file=arg_file, + log_file=log_file, + log_handler_config=log_handler_config, + log_fmt_pattern=log_fmt_pattern, + log_json_fmt=log_json_fmt, + log_level=log_level, ) await faber.listen_webhooks(start_port + 5) await faber.register_did() @@ -682,6 +751,41 @@ async def check_received_pings(agent, issue_count, pb): metavar="", help="Specify a file containing additional aca-py parameters", ) + parser.add_argument( + "--log-file", + type=str, + metavar="", + help=("Output destination for the root logger."), + ) + parser.add_argument( + "--log-level", + type=str, + metavar="", + default=None, + help=( + "Specifies a custom logging level as one of: " + "('debug', 'info', 'warning', 'error', 'critical')" + ), + ) + parser.add_argument( + "--log-handler-config", + type=str, + metavar="", + help=( + "Specifies when, interval, backupCount for the TimedRotatingFileHandler." + ), + ) + parser.add_argument( + "--log-fmt-pattern", + type=str, + metavar="", + help=("Specifies logging formatter pattern as string."), + ) + parser.add_argument( + "--log-json-fmt", + action="store_true", + help=("JSON logging formatter."), + ) args = parser.parse_args() if args.did_exchange and args.mediation: @@ -720,6 +824,11 @@ async def check_received_pings(agent, issue_count, pb): args.batch, args.wallet_type, args.arg_file, + args.log_file, + args.log_handler_config, + args.log_fmt_pattern, + args.log_json_fmt, + args.log_level, ) ) except KeyboardInterrupt: diff --git a/demo/runners/support/agent.py b/demo/runners/support/agent.py index 26563fe6f5..2ee9d7b27d 100644 --- a/demo/runners/support/agent.py +++ b/demo/runners/support/agent.py @@ -138,6 +138,11 @@ def __init__( arg_file: str = None, endorser_role: str = None, extra_args=None, + log_file: str = None, + log_handler_config: str = None, + log_fmt_pattern: str = None, + log_json_fmt: bool = False, + log_level: str = None, **params, ): self.ident = ident @@ -169,6 +174,11 @@ def __init__( self.mediator_request_id = None self.aip = aip self.arg_file = arg_file + self.log_file = log_file + self.log_handler_config = log_handler_config + self.log_fmt_pattern = log_fmt_pattern + self.log_json_fmt = log_json_fmt + self.log_level = log_level self.admin_url = f"http://{self.internal_host}:{admin_port}" if AGENT_ENDPOINT: @@ -345,6 +355,32 @@ def get_agent_args(self): "--public-invites", # ("--log-level", "debug"), ] + if self.log_file: + result.extend( + [ + ("--log-file", self.log_file), + ] + ) + if self.log_handler_config: + result.extend( + [ + ("--log-handler-config", self.log_handler_config), + ] + ) + if self.log_fmt_pattern: + result.extend( + [ + ("--log-fmt-pattern", self.log_fmt_pattern), + ] + ) + if self.log_level: + result.extend( + [ + ("--log-level", self.log_level), + ] + ) + if self.log_json_fmt: + result.append("--log-json-fmt") if self.aip == 20: result.append("--emit-new-didcomm-prefix") if self.multitenant: From c87762ead0e62a24428d98408b8cba2450e7ea2f Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Thu, 24 Aug 2023 02:59:15 +0530 Subject: [PATCH 07/18] new logging optimization + cleanup Signed-off-by: Shaanjot Gill --- Logging.md | 2 +- aries_cloudagent/config/logging.py | 108 +++--------------- aries_cloudagent/config/tests/test_logging.py | 15 +-- aries_cloudagent/config/util.py | 8 +- 4 files changed, 22 insertions(+), 111 deletions(-) diff --git a/Logging.md b/Logging.md index c8f778a801..66373e56df 100644 --- a/Logging.md +++ b/Logging.md @@ -19,7 +19,7 @@ Other log levels fall back to `WARNING`. Example: ```sh -./bin/aca-py start --log-level debug --log-file acapy.log --log-handler-config "d;7;1" --log-fmt-pattern "%(asctime)s [%(did)s] %(filename)s %(lineno)d %(message)s" --log-json-fmt +./bin/aca-py start --log-level debug --log-file acapy.log --log-handler-config "d;7;1" --log-fmt-pattern "%(asctime)s %(wallet_id)s %(filename)s %(lineno)d %(message)s" --log-json-fmt ``` ## Environment Variables diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index e02449d8a1..e9599e4fd2 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -1,6 +1,5 @@ """Utilities related to logging.""" -import asyncio from datetime import datetime, timedelta from io import TextIOWrapper import logging @@ -11,7 +10,7 @@ import re import sys import time as mod_time -from typing import Optional, TextIO, Tuple, TYPE_CHECKING +from typing import TextIO, TYPE_CHECKING import pkg_resources from portalocker import LOCK_EX, lock, unlock @@ -19,7 +18,6 @@ from ..config.settings import Settings from ..version import __version__ -from ..wallet.base import BaseWallet, DIDInfo from .banner import Banner from .base import BaseSettings @@ -59,10 +57,6 @@ def configure( cls, logging_config_path: str = None, log_level: str = None, - log_file: str = None, - log_interval: int = None, - log_bak_count: int = None, - log_at_when: str = None, ): """Configure logger. @@ -83,15 +77,6 @@ def configure( else: logging.basicConfig(level=logging.WARNING) logging.root.warning(f"Logging config file not found: {config_path}") - - if log_file: - logging.root.handlers.clear() - timed_file_handler, std_out_handler = get_log_file_handlers( - log_file, log_interval, log_bak_count, log_at_when - ) - logging.root.handlers.append(timed_file_handler) - logging.root.handlers.append(std_out_handler) - if log_level: log_level = log_level.upper() logging.root.setLevel(log_level) @@ -507,25 +492,17 @@ def doRollover(self): LOG_FORMAT_FILE_ALIAS_PATTERN = ( - "%(asctime)s [%(did)s] %(levelname)s %(filename)s %(lineno)d %(message)s" + "%(asctime)s %(wallet_id)s %(levelname)s %(filename)s %(lineno)d %(message)s" ) -LOG_FORMAT_FILE_NO_ALIAS_PATTERN = ( - "%(asctime)s %(levelname)s %(filename)s %(lineno)d %(message)s" -) - -LOG_FORMAT_STREAM_PATTERN = ( - "%(asctime)s %(levelname)s %(filename)s %(lineno)d %(message)s" -) - -def get_log_file_handlers( +def get_log_file_handler( log_file_name: str, log_interval: int = None, log_bak_count: int = None, log_at_when: str = None, -) -> Tuple[TimedRotatingFileMultiProcessHandler, logging.StreamHandler]: - """Get TimedRotatingFileMultiProcessHandler and StreamHandler log handlers.""" +) -> TimedRotatingFileMultiProcessHandler: + """Get TimedRotatingFileMultiProcessHandler log handler.""" file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)).replace( "aries_cloudagent/config", "" @@ -538,8 +515,7 @@ def get_log_file_handlers( when=log_at_when or "d", backupCount=log_bak_count or 1, ) - std_out_handler = logging.StreamHandler(sys.stdout) - return (timed_file_handler, std_out_handler) + return timed_file_handler def clear_prev_handlers(logger: logging.Logger) -> logging.Logger: @@ -557,90 +533,42 @@ def get_logger_inst(profile: "Profile", logger_name) -> logging.Logger: if not profile.settings.get("log.file"): return logging.getLogger(logger_name) else: - did_ident = get_did_ident(profile) - if did_ident: - logger_name = f"{logger_name}_{did_ident}" + wallet_id = profile.settings.get("wallet.id") + logger_name = f"{logger_name}_{wallet_id}" return get_logger_with_handlers( settings=profile.settings, logger=logging.getLogger(logger_name), - did_ident=did_ident, + ident=wallet_id, interval=profile.settings.get("log.handler_interval") or 7, backup_count=profile.settings.get("log.handler_bakcount") or 1, at_when=profile.settings.get("log.handler_when") or "d", ) -def get_did_ident(profile: "Profile") -> Optional[str]: - """Get public did identifier for logging.""" - - async def _fetch_did() -> Optional[str]: - async with profile.session() as session: - wallet = session.inject(BaseWallet) - public_did_info: DIDInfo = await wallet.get_public_did() - req_did_info = None - _did = None - if not public_did_info: - local_did_info: DIDInfo = await wallet.get_local_dids() - if local_did_info: - req_did_info = local_did_info[0] - if req_did_info: - _did = req_did_info.did - return _did - - loop = asyncio.get_event_loop() - did_ident = loop.run_until_complete(_fetch_did()) - return did_ident - - def get_logger_with_handlers( settings: BaseSettings, logger: logging.Logger, + ident: str, at_when: str = None, interval: int = None, backup_count: int = None, - did_ident: str = None, ) -> logging.Logger: """Return logger instance with necessary handlers if required.""" # Clear handlers set previously for this logger instance logger = clear_prev_handlers(logger) # log file handler - file_handler, std_out_handler = get_log_file_handlers( + file_handler = get_log_file_handler( settings.get("log.file"), interval, backup_count, at_when ) - if did_ident: - if settings.get("log.json_fmt"): - file_handler.setFormatter( - jsonlogger.JsonFormatter( - settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_ALIAS_PATTERN - ) - ) - else: - file_handler.setFormatter( - logging.Formatter( - settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_ALIAS_PATTERN - ) - ) + file_handler_pattern = settings.get("log.fmt_pattern") + if not file_handler_pattern: + file_handler_pattern = LOG_FORMAT_FILE_ALIAS_PATTERN + if settings.get("log.json_fmt"): + file_handler.setFormatter(jsonlogger.JsonFormatter(file_handler_pattern)) else: - if settings.get("log.json_fmt"): - file_handler.setFormatter( - jsonlogger.JsonFormatter( - settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_NO_ALIAS_PATTERN - ) - ) - else: - file_handler.setFormatter( - logging.Formatter( - settings.get("log.fmt_pattern") or LOG_FORMAT_FILE_NO_ALIAS_PATTERN - ) - ) + file_handler.setFormatter(logging.Formatter(file_handler_pattern)) logger.addHandler(file_handler) - # stream console handler - std_out_handler.setFormatter( - logging.Formatter(settings.get("log.fmt_pattern") or LOG_FORMAT_STREAM_PATTERN) - ) - logger.addHandler(std_out_handler) - if did_ident: - logger = logging.LoggerAdapter(logger, {"did": did_ident}) + logger = logging.LoggerAdapter(logger, {"wallet_id": ident}) # set log level if settings.get("log.level"): logger_level = settings.get("log.level").upper() diff --git a/aries_cloudagent/config/tests/test_logging.py b/aries_cloudagent/config/tests/test_logging.py index 853b723692..978e155717 100644 --- a/aries_cloudagent/config/tests/test_logging.py +++ b/aries_cloudagent/config/tests/test_logging.py @@ -40,14 +40,11 @@ def test_configure_default_no_resource(self): test_module.LoggingConfigurator.configure() def test_configure_default_file(self): - log_file = NamedTemporaryFile() with async_mock.patch.object( test_module, "load_resource", async_mock.MagicMock() ) as mock_load: mock_load.return_value = None - test_module.LoggingConfigurator.configure( - log_level="ERROR", log_file=log_file.name - ) + test_module.LoggingConfigurator.configure(log_level="ERROR") @async_mock.patch.object(test_module, "load_resource", autospec=True) @async_mock.patch.object(test_module, "fileConfig", autospec=True) @@ -106,15 +103,7 @@ def test_get_logger_with_handlers(self): logger = test_module.get_logger_with_handlers( settings=profile.settings, logger=logger, - at_when="m", - interval=1, - backup_count=1, - ) - assert logger - logger = test_module.get_logger_with_handlers( - settings=profile.settings, - logger=logger, - did_ident="tenant_did_123", + ident="tenant_did_123", at_when="m", interval=1, backup_count=1, diff --git a/aries_cloudagent/config/util.py b/aries_cloudagent/config/util.py index 5376d014ba..f4472f92b3 100644 --- a/aries_cloudagent/config/util.py +++ b/aries_cloudagent/config/util.py @@ -14,13 +14,7 @@ def common_config(settings: Mapping[str, Any]): # Set up logging log_config = settings.get("log.config") log_level = settings.get("log.level") or os.getenv("LOG_LEVEL") - log_file = settings.get("log.file") - log_interval = settings.get("log.handler_interval") - log_at_when = settings.get("log.handler_when") - log_bak_count = settings.get("log.handler_bakcount") - LoggingConfigurator.configure( - log_config, log_level, log_file, log_interval, log_bak_count, log_at_when - ) + LoggingConfigurator.configure(log_config, log_level) class BoundedInt: From adda4e731c4aeedfa61a66e7e78f52fc17d45d8f Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Tue, 29 Aug 2023 13:34:34 +0530 Subject: [PATCH 08/18] rework based upon feedback Signed-off-by: Shaanjot Gill --- aries_cloudagent/config/ledger.py | 16 +- aries_cloudagent/config/logging.py | 140 +++++++++--------- aries_cloudagent/config/tests/test_logging.py | 105 +++++-------- aries_cloudagent/config/util.py | 20 ++- aries_cloudagent/connections/base_manager.py | 11 +- aries_cloudagent/core/conductor.py | 31 +--- aries_cloudagent/core/dispatcher.py | 6 +- aries_cloudagent/core/event_bus.py | 16 +- aries_cloudagent/core/oob_processor.py | 56 ++++--- aries_cloudagent/core/tests/test_event_bus.py | 120 ++++----------- aries_cloudagent/indy/credx/holder.py | 10 +- aries_cloudagent/indy/credx/issuer.py | 10 +- aries_cloudagent/indy/credx/verifier.py | 11 +- aries_cloudagent/indy/sdk/issuer.py | 11 +- aries_cloudagent/indy/sdk/verifier.py | 11 +- aries_cloudagent/indy/verifier.py | 9 +- aries_cloudagent/ledger/indy.py | 9 +- .../ledger/multiple_ledger/indy_manager.py | 11 +- .../multiple_ledger/indy_vdr_manager.py | 11 +- aries_cloudagent/ledger/routes.py | 12 +- aries_cloudagent/multitenant/base.py | 11 +- aries_cloudagent/multitenant/cache.py | 9 +- aries_cloudagent/multitenant/route_manager.py | 16 +- .../v1_0/handlers/menu_request_handler.py | 16 +- .../v1_0/handlers/perform_handler.py | 16 +- .../protocols/actionmenu/v1_0/routes.py | 20 ++- .../v1_0/handlers/basicmessage_handler.py | 16 +- .../handlers/connection_request_handler.py | 24 +-- .../handlers/connection_response_handler.py | 22 +-- .../protocols/connections/v1_0/manager.py | 11 +- .../v1_0/handlers/keylist_handler.py | 19 ++- .../v1_0/handlers/keylist_query_handler.py | 18 +-- .../v1_0/handlers/keylist_update_handler.py | 18 +-- .../keylist_update_response_handler.py | 25 ++-- .../v1_0/handlers/mediation_deny_handler.py | 18 +-- .../v1_0/handlers/mediation_grant_handler.py | 18 +-- .../handlers/mediation_request_handler.py | 16 +- .../tests/test_problem_report_handler.py | 6 + .../coordinate_mediation/v1_0/manager.py | 11 +- .../v1_0/route_manager.py | 18 ++- .../v1_0/tests/test_mediation_manager.py | 78 +++++----- .../v1_0/handlers/complete_handler.py | 18 +-- .../v1_0/handlers/request_handler.py | 23 +-- .../v1_0/handlers/response_handler.py | 21 +-- .../protocols/didexchange/v1_0/manager.py | 11 +- .../v1_0/handlers/disclose_handler.py | 15 +- .../discovery/v1_0/handlers/query_handler.py | 15 +- .../protocols/discovery/v1_0/manager.py | 11 +- .../v2_0/handlers/disclosures_handler.py | 15 +- .../v2_0/handlers/queries_handler.py | 15 +- .../protocols/discovery/v2_0/manager.py | 11 +- .../endorsed_transaction_response_handler.py | 18 +-- .../refused_transaction_response_handler.py | 16 +- ...t_endorsed_transaction_response_handler.py | 18 +++ ...st_refused_transaction_response_handler.py | 18 +++ ...est_transaction_acknowledgement_handler.py | 18 +++ .../tests/test_transaction_cancel_handler.py | 18 +++ .../test_transaction_job_to_send_handler.py | 12 ++ .../tests/test_transaction_request_handler.py | 18 +++ .../tests/test_transaction_resend_handler.py | 18 +++ .../transaction_acknowledgement_handler.py | 16 +- .../handlers/transaction_cancel_handler.py | 16 +- .../transaction_job_to_send_handler.py | 16 +- .../handlers/transaction_request_handler.py | 18 +-- .../handlers/transaction_resend_handler.py | 16 +- .../endorse_transaction/v1_0/routes.py | 11 +- .../introduction/v0_1/demo_service.py | 12 +- .../handlers/forward_invitation_handler.py | 17 +-- .../v0_1/handlers/invitation_handler.py | 15 +- .../handlers/invitation_request_handler.py | 15 +- .../tests/test_forward_invitation_handler.py | 18 +++ .../handlers/tests/test_invitation_handler.py | 19 ++- .../tests/test_invitation_request_handler.py | 19 ++- .../protocols/introduction/v0_1/routes.py | 12 +- .../v1_0/handlers/credential_ack_handler.py | 16 +- .../v1_0/handlers/credential_issue_handler.py | 19 ++- .../v1_0/handlers/credential_offer_handler.py | 19 ++- .../credential_problem_report_handler.py | 16 +- .../handlers/credential_proposal_handler.py | 19 ++- .../handlers/credential_request_handler.py | 21 ++- .../tests/test_credential_ack_handler.py | 18 +++ .../tests/test_credential_issue_handler.py | 36 ++++- .../tests/test_credential_offer_handler.py | 40 ++++- .../test_credential_problem_report_handler.py | 24 +++ .../tests/test_credential_proposal_handler.py | 40 ++++- .../tests/test_credential_request_handler.py | 46 +++++- .../issue_credential/v1_0/manager.py | 11 +- .../v1_0/models/credential_exchange.py | 12 +- .../models/tests/test_credential_exchange.py | 6 +- .../v1_0/tests/test_manager.py | 26 +--- .../issue_credential/v2_0/formats/handler.py | 10 +- .../v2_0/handlers/cred_ack_handler.py | 16 +- .../v2_0/handlers/cred_issue_handler.py | 18 +-- .../v2_0/handlers/cred_offer_handler.py | 19 ++- .../handlers/cred_problem_report_handler.py | 16 +- .../v2_0/handlers/cred_proposal_handler.py | 19 ++- .../v2_0/handlers/cred_request_handler.py | 19 ++- .../handlers/tests/test_cred_ack_handler.py | 18 +++ .../handlers/tests/test_cred_offer_handler.py | 16 +- .../tests/test_cred_problem_report_handler.py | 24 +++ .../tests/test_cred_proposal_handler.py | 16 +- .../tests/test_cred_request_handler.py | 40 ++++- .../issue_credential/v2_0/manager.py | 11 +- .../v2_0/models/cred_ex_record.py | 12 +- .../v2_0/models/tests/test_cred_ex_record.py | 15 +- .../protocols/issue_credential/v2_0/routes.py | 67 +++++---- .../v2_0/tests/test_manager.py | 26 ++-- .../v1_0/handlers/tests/test_ack_handler.py | 6 + .../v1_0/handlers/problem_report_handler.py | 19 +-- .../v1_0/handlers/reuse_accept_handler.py | 19 +-- .../v1_0/handlers/reuse_handler.py | 19 +-- .../tests/test_problem_report_handler.py | 28 ++-- .../tests/test_reuse_accept_handler.py | 12 ++ .../v1_0/handlers/tests/test_reuse_handler.py | 18 +++ .../protocols/out_of_band/v1_0/manager.py | 10 +- .../present_proof/dif/pres_exch_handler.py | 10 +- .../present_proof/indy/pres_exch_handler.py | 11 +- .../v1_0/handlers/presentation_ack_handler.py | 16 +- .../v1_0/handlers/presentation_handler.py | 19 ++- .../presentation_problem_report_handler.py | 16 +- .../handlers/presentation_proposal_handler.py | 21 +-- .../handlers/presentation_request_handler.py | 21 ++- .../tests/test_presentation_ack_handler.py | 18 +++ .../tests/test_presentation_handler.py | 30 ++-- ...est_presentation_problem_report_handler.py | 12 ++ .../test_presentation_proposal_handler.py | 42 ++++-- .../test_presentation_request_handler.py | 83 +++++++++-- .../protocols/present_proof/v1_0/manager.py | 11 +- .../v1_0/models/presentation_exchange.py | 12 +- .../v1_0/models/tests/test_record.py | 6 +- .../present_proof/v2_0/formats/handler.py | 10 +- .../v2_0/handlers/pres_ack_handler.py | 16 +- .../v2_0/handlers/pres_handler.py | 18 +-- .../handlers/pres_problem_report_handler.py | 16 +- .../v2_0/handlers/pres_proposal_handler.py | 19 ++- .../v2_0/handlers/pres_request_handler.py | 19 ++- .../handlers/tests/test_pres_ack_handler.py | 18 +++ .../v2_0/handlers/tests/test_pres_handler.py | 30 ++-- .../tests/test_pres_problem_report_handler.py | 12 ++ .../tests/test_pres_proposal_handler.py | 42 ++++-- .../tests/test_pres_request_handler.py | 78 ++++++++-- .../protocols/present_proof/v2_0/manager.py | 11 +- .../v2_0/models/pres_exchange.py | 12 +- .../v2_0/models/tests/test_record.py | 16 +- .../present_proof/v2_0/tests/test_manager.py | 18 +-- .../protocols/problem_report/v1_0/handler.py | 16 +- .../v1_0/handlers/revoke_handler.py | 14 +- .../revocation_notification/v1_0/routes.py | 11 +- .../v2_0/handlers/revoke_handler.py | 14 +- .../revocation_notification/v2_0/routes.py | 11 +- .../routing/v1_0/handlers/forward_handler.py | 21 +-- .../handlers/tests/test_forward_handler.py | 20 ++- .../protocols/routing/v1_0/manager.py | 11 +- .../trustping/v1_0/handlers/ping_handler.py | 20 +-- .../v1_0/handlers/ping_response_handler.py | 16 +- .../resolver/default/tests/test_universal.py | 16 +- .../resolver/default/universal.py | 10 +- aries_cloudagent/resolver/did_resolver.py | 6 +- .../resolver/tests/test_did_resolver.py | 68 ++------- aries_cloudagent/revocation/indy.py | 11 +- .../models/issuer_rev_reg_record.py | 24 +-- aries_cloudagent/wallet/routes.py | 11 +- 162 files changed, 2030 insertions(+), 1356 deletions(-) diff --git a/aries_cloudagent/config/ledger.py b/aries_cloudagent/config/ledger.py index 091fa9f02c..bce2985775 100644 --- a/aries_cloudagent/config/ledger.py +++ b/aries_cloudagent/config/ledger.py @@ -12,7 +12,7 @@ from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop from prompt_toolkit.formatted_text import HTML -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..config.settings import Settings from ..core.profile import Profile from ..ledger.base import BaseLedger @@ -129,9 +129,10 @@ async def ledger_config( """Perform Indy ledger configuration.""" session = await profile.session() - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) ledger = session.inject_or(BaseLedger) if not ledger: @@ -256,9 +257,10 @@ async def accept_taa( mechanisms = taa_info["aml_record"]["aml"] mechanism = None - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) taa_acceptance_mechanism = profile.settings.get("ledger.taa_acceptance_mechanism") taa_acceptance_version = profile.settings.get("ledger.taa_acceptance_version") diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index e9599e4fd2..ba369977c8 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -10,7 +10,7 @@ import re import sys import time as mod_time -from typing import TextIO, TYPE_CHECKING +from typing import Tuple, TextIO import pkg_resources from portalocker import LOCK_EX, lock, unlock @@ -19,13 +19,14 @@ from ..config.settings import Settings from ..version import __version__ from .banner import Banner -from .base import BaseSettings - -if TYPE_CHECKING: # To avoid circular import error - from ..core.profile import Profile - DEFAULT_LOGGING_CONFIG_PATH = "aries_cloudagent.config:default_logging_config.ini" +LOG_FORMAT_FILE_ALIAS_PATTERN = ( + "%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s" +) +LOG_FORMAT_STREAM_PATTERN = ( + "%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(message)s" +) def load_resource(path: str, encoding: str = None) -> TextIO: @@ -81,6 +82,59 @@ def configure( log_level = log_level.upper() logging.root.setLevel(log_level) + @classmethod + def configure_per_tenant( + cls, + logging_config_path: str = None, + log_level: str = None, + log_file: str = None, + log_interval: int = None, + log_bak_count: int = None, + log_at_when: str = None, + log_fmt_pattern: str = None, + log_json_fmt: bool = False, + ): + """ + Configure logger. + + :param logging_config_path: str: (Default value = None) Optional path to + custom logging config + + :param log_level: str: (Default value = None) + """ + if logging_config_path is not None: + config_path = logging_config_path + else: + config_path = DEFAULT_LOGGING_CONFIG_PATH + + log_config = load_resource(config_path, "utf-8") + if log_config: + with log_config: + fileConfig(log_config, disable_existing_loggers=False) + else: + logging.basicConfig(level=logging.WARNING) + logging.root.warning(f"Logging config file not found: {config_path}") + if log_file: + logging.root.handlers.clear() + timed_file_handler, std_out_handler = get_log_file_handlers( + log_file, log_interval, log_bak_count, log_at_when + ) + file_handler_pattern = log_fmt_pattern + if not file_handler_pattern: + file_handler_pattern = LOG_FORMAT_FILE_ALIAS_PATTERN + if log_json_fmt: + timed_file_handler.setFormatter( + jsonlogger.JsonFormatter(file_handler_pattern) + ) + else: + timed_file_handler.setFormatter(logging.Formatter(file_handler_pattern)) + std_out_handler.setFormatter(logging.Formatter(LOG_FORMAT_STREAM_PATTERN)) + logging.root.handlers.append(timed_file_handler) + logging.root.handlers.append(std_out_handler) + if log_level: + log_level = log_level.upper() + logging.root.setLevel(log_level) + @classmethod def print_banner( cls, @@ -491,17 +545,12 @@ def doRollover(self): self.release() -LOG_FORMAT_FILE_ALIAS_PATTERN = ( - "%(asctime)s %(wallet_id)s %(levelname)s %(filename)s %(lineno)d %(message)s" -) - - -def get_log_file_handler( +def get_log_file_handlers( log_file_name: str, log_interval: int = None, log_bak_count: int = None, log_at_when: str = None, -) -> TimedRotatingFileMultiProcessHandler: +) -> Tuple[TimedRotatingFileMultiProcessHandler, logging.StreamHandler]: """Get TimedRotatingFileMultiProcessHandler log handler.""" file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)).replace( @@ -515,62 +564,19 @@ def get_log_file_handler( when=log_at_when or "d", backupCount=log_bak_count or 1, ) - return timed_file_handler - - -def clear_prev_handlers(logger: logging.Logger) -> logging.Logger: - """Remove all handler classes associated with logger instance.""" - iter_count = 0 - num_handlers = len(logger.handlers) - while iter_count < num_handlers: - logger.removeHandler(logger.handlers[0]) - iter_count = iter_count + 1 - return logger + std_out_handler = logging.StreamHandler(sys.stdout) + return (timed_file_handler, std_out_handler) -def get_logger_inst(profile: "Profile", logger_name) -> logging.Logger: - """Return a logger instance with provided name and handlers.""" - if not profile.settings.get("log.file"): - return logging.getLogger(logger_name) - else: - wallet_id = profile.settings.get("wallet.id") - logger_name = f"{logger_name}_{wallet_id}" - return get_logger_with_handlers( - settings=profile.settings, - logger=logging.getLogger(logger_name), - ident=wallet_id, - interval=profile.settings.get("log.handler_interval") or 7, - backup_count=profile.settings.get("log.handler_bakcount") or 1, - at_when=profile.settings.get("log.handler_when") or "d", - ) - - -def get_logger_with_handlers( - settings: BaseSettings, +def get_adapted_logger_inst( logger: logging.Logger, - ident: str, - at_when: str = None, - interval: int = None, - backup_count: int = None, + log_file: str = None, + wallet_id: str = None, ) -> logging.Logger: - """Return logger instance with necessary handlers if required.""" - # Clear handlers set previously for this logger instance - logger = clear_prev_handlers(logger) - # log file handler - file_handler = get_log_file_handler( - settings.get("log.file"), interval, backup_count, at_when - ) - file_handler_pattern = settings.get("log.fmt_pattern") - if not file_handler_pattern: - file_handler_pattern = LOG_FORMAT_FILE_ALIAS_PATTERN - if settings.get("log.json_fmt"): - file_handler.setFormatter(jsonlogger.JsonFormatter(file_handler_pattern)) + """Get adapted logger instance, if applicable.""" + _logger = None + if log_file and wallet_id: + _logger = logging.LoggerAdapter(logger, {"wallet_id": wallet_id}) else: - file_handler.setFormatter(logging.Formatter(file_handler_pattern)) - logger.addHandler(file_handler) - logger = logging.LoggerAdapter(logger, {"wallet_id": ident}) - # set log level - if settings.get("log.level"): - logger_level = settings.get("log.level").upper() - logger.setLevel(logger_level) - return logger + _logger = logger + return _logger diff --git a/aries_cloudagent/config/tests/test_logging.py b/aries_cloudagent/config/tests/test_logging.py index 978e155717..53509fa260 100644 --- a/aries_cloudagent/config/tests/test_logging.py +++ b/aries_cloudagent/config/tests/test_logging.py @@ -46,6 +46,29 @@ def test_configure_default_file(self): mock_load.return_value = None test_module.LoggingConfigurator.configure(log_level="ERROR") + def test_configure_per_tenant(self): + mock_log_handlers = ( + async_mock.MagicMock(setFormatter=async_mock.MagicMock()), + async_mock.MagicMock(setFormatter=async_mock.MagicMock()), + ) + with async_mock.patch.object( + test_module, "logging", autospec=True + ), async_mock.patch.object( + test_module, "load_resource", async_mock.MagicMock() + ) as mock_load, async_mock.patch.object( + test_module, + "get_log_file_handlers", + async_mock.MagicMock(return_value=mock_log_handlers), + ): + mock_load.return_value = None + test_module.LoggingConfigurator.configure_per_tenant( + log_level="ERROR", + log_file="test.log", + log_interval=1, + log_json_fmt=True, + log_at_when="m", + ) + @async_mock.patch.object(test_module, "load_resource", autospec=True) @async_mock.patch.object(test_module, "fileConfig", autospec=True) def test_configure_path(self, mock_file_config, mock_load_resource): @@ -96,76 +119,14 @@ def test_load_resource(self): ) as mock_res_stream: test_module.load_resource("abc:def", encoding=None) - def test_get_logger_with_handlers(self): - profile = InMemoryProfile.test_profile() - profile.settings["log.file"] = "test_file.log" - logger = logging.getLogger(__name__) - logger = test_module.get_logger_with_handlers( - settings=profile.settings, - logger=logger, - ident="tenant_did_123", - at_when="m", - interval=1, - backup_count=1, - ) - assert logger - - async def test_get_logger_inst(self): - profile = InMemoryProfile.test_profile() - logger = test_module.get_logger_inst( - profile=profile, - logger_name=__name__, - ) - assert logger - # public did - profile.settings["log.file"] = "test_file.log" - profile.context.injector.bind_instance(DIDMethods, DIDMethods()) - async with profile.session() as session: - wallet: BaseWallet = session.inject_or(BaseWallet) - await wallet.create_local_did( - SOV, - ED25519, - did="DJGEjaMunDtFtBVrn1qJMT", - ) - await wallet.set_public_did("DJGEjaMunDtFtBVrn1qJMT") - logger = test_module.get_logger_inst( - profile=profile, - logger_name=__name__, - ) - # public did, json_fmt, pattern - profile.settings["log.file"] = "test_file.log" - profile.settings["log.json_fmt"] = True - profile.settings[ - "log.fmt_pattern" - ] = "%(asctime)s [%(did)s] %(lineno)d %(message)s" - logger = test_module.get_logger_inst( - profile=profile, - logger_name=__name__, - ) - assert logger - # not public did - profile = InMemoryProfile.test_profile() - profile.settings["log.file"] = "test_file.log" - profile.settings["log.json_fmt"] = False - profile.context.injector.bind_instance(DIDMethods, DIDMethods()) - async with profile.session() as session: - wallet: BaseWallet = session.inject_or(BaseWallet) - await wallet.create_local_did( - SOV, - ED25519, - did="DJGEjaMunDtFtBVrn1qJMT", + def test_get_log_file_handlers(self): + with async_mock.patch.object( + test_module, "TimedRotatingFileMultiProcessHandler", async_mock.MagicMock() + ) as mock_file_handler, async_mock.patch.object( + test_module.logging, "StreamHandler", async_mock.MagicMock() + ) as mock_stream_handler: + ret_file_handler, ret_stream_handler = test_module.get_log_file_handlers( + "test.log", 1, 1, "m" ) - logger = test_module.get_logger_inst( - profile=profile, - logger_name=__name__, - ) - assert logger - # not public did, json_fmt, pattern - profile.settings["log.file"] = "test_file.log" - profile.settings["log.json_fmt"] = True - profile.settings["log.fmt_pattern"] = "%(asctime)s %(lineno)d %(message)s" - logger = test_module.get_logger_inst( - profile=profile, - logger_name=__name__, - ) - assert logger + assert ret_file_handler + assert ret_stream_handler diff --git a/aries_cloudagent/config/util.py b/aries_cloudagent/config/util.py index f4472f92b3..4d79a30497 100644 --- a/aries_cloudagent/config/util.py +++ b/aries_cloudagent/config/util.py @@ -14,7 +14,25 @@ def common_config(settings: Mapping[str, Any]): # Set up logging log_config = settings.get("log.config") log_level = settings.get("log.level") or os.getenv("LOG_LEVEL") - LoggingConfigurator.configure(log_config, log_level) + log_file = settings.get("log.file") + log_interval = settings.get("log.handler_interval") + log_bak_count = settings.get("log.handler_bakcount") + log_at_when = settings.get("log.handler_when") + log_fmt_pattern = settings.get("log.fmt_pattern") + log_json_fmt = settings.get("log.json_fmt") + if not log_file: + LoggingConfigurator.configure(log_config, log_level) + else: + LoggingConfigurator.configure_per_tenant( + log_config, + log_level, + log_file, + log_interval, + log_bak_count, + log_at_when, + log_fmt_pattern, + log_json_fmt, + ) class BoundedInt: diff --git a/aries_cloudagent/connections/base_manager.py b/aries_cloudagent/connections/base_manager.py index f1d2ce9fa8..5a4aa708da 100644 --- a/aries_cloudagent/connections/base_manager.py +++ b/aries_cloudagent/connections/base_manager.py @@ -20,7 +20,7 @@ ) from ..cache.base import BaseCache from ..config.base import InjectionError -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..core.error import BaseError from ..core.profile import Profile from ..did.did_key import DIDKey @@ -52,6 +52,8 @@ from .models.connection_target import ConnectionTarget from .models.diddoc import DIDDoc, PublicKey, PublicKeyType, Service +LOGGER = logging.getLogger(__name__) + class BaseConnectionManagerError(BaseError): """BaseConnectionManager error.""" @@ -71,9 +73,10 @@ def __init__(self, profile: Profile): """ self._profile = profile self._route_manager = profile.inject(RouteManager) - self._logger: logging.Logger = get_logger_inst( - profile=self._profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) async def create_did_document( diff --git a/aries_cloudagent/core/conductor.py b/aries_cloudagent/core/conductor.py index 3eb8151f26..5e4887930f 100644 --- a/aries_cloudagent/core/conductor.py +++ b/aries_cloudagent/core/conductor.py @@ -24,7 +24,7 @@ ledger_config, load_multiple_genesis_transactions_from_config, ) -from ..config.logging import LoggingConfigurator, get_logger_inst +from ..config.logging import LoggingConfigurator from ..config.provider import ClassProvider from ..config.wallet import wallet_config from ..commands.upgrade import ( @@ -551,12 +551,9 @@ def inbound_message_router( can_respond: If the session supports return routing """ - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, - ) + if message.receipt.direct_response_requested and not can_respond: - _logger.warning( + LOGGER.warning( "Direct response requested, but not supported by transport: %s", message.transport_type, ) @@ -572,7 +569,7 @@ def inbound_message_router( lambda completed: self.dispatch_complete(message, completed), ) except (LedgerConfigError, LedgerTransactionError) as e: - _logger.error("Shutdown on ledger error %s", str(e)) + LOGGER.error("Shutdown on ledger error %s", str(e)) if self.admin_server: self.admin_server.notify_fatal_error() raise @@ -663,14 +660,10 @@ async def _outbound_message_router( def handle_not_returned(self, profile: Profile, outbound: OutboundMessage): """Handle a message that failed delivery via an inbound session.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, - ) try: self.dispatcher.run_task(self.queue_outbound(profile, outbound)) except (LedgerConfigError, LedgerTransactionError) as e: - _logger.error("Shutdown on ledger error %s", str(e)) + LOGGER.error("Shutdown on ledger error %s", str(e)) if self.admin_server: self.admin_server.notify_fatal_error() raise @@ -688,10 +681,6 @@ async def queue_outbound( message: An outbound message to be sent inbound: The inbound message that produced this response, if available """ - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, - ) has_target = outbound.target or outbound.target_list # populate connection target(s) @@ -704,10 +693,10 @@ async def queue_outbound( ) ) except ConnectionManagerError: - _logger.exception("Error preparing outbound message for transmission") + LOGGER.exception("Error preparing outbound message for transmission") return OutboundSendStatus.UNDELIVERABLE except (LedgerConfigError, LedgerTransactionError) as e: - _logger.error("Shutdown on ledger error %s", str(e)) + LOGGER.error("Shutdown on ledger error %s", str(e)) if self.admin_server: self.admin_server.notify_fatal_error() raise @@ -727,15 +716,11 @@ async def _queue_message( self, profile: Profile, outbound: OutboundMessage ) -> OutboundSendStatus: """Save the message to an internal outbound queue.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, - ) try: await self.outbound_transport_manager.enqueue_message(profile, outbound) return OutboundSendStatus.QUEUED_FOR_DELIVERY except OutboundDeliveryError: - _logger.warning("Cannot queue message for delivery, no supported transport") + LOGGER.warning("Cannot queue message for delivery, no supported transport") return self.handle_not_delivered(profile, outbound) def handle_not_delivered( diff --git a/aries_cloudagent/core/dispatcher.py b/aries_cloudagent/core/dispatcher.py index 66664474fe..b8660ab568 100644 --- a/aries_cloudagent/core/dispatcher.py +++ b/aries_cloudagent/core/dispatcher.py @@ -13,7 +13,6 @@ from aiohttp.web import HTTPException -from ..config.logging import get_logger_inst from ..connections.base_manager import BaseConnectionManager from ..connections.models.conn_record import ConnRecord from ..core.profile import Profile @@ -52,10 +51,7 @@ def __init__(self, profile: Profile): self.collector: Collector = None self.profile = profile self.task_queue: TaskQueue = None - self.logger: logging.Logger = get_logger_inst( - profile=self.profile, - logger_name=__name__, - ) + self.logger: logging.Logger = logging.getLogger(__name__) async def setup(self): """Perform async instance setup.""" diff --git a/aries_cloudagent/core/event_bus.py b/aries_cloudagent/core/event_bus.py index 85c0c50ac0..3d76252bb4 100644 --- a/aries_cloudagent/core/event_bus.py +++ b/aries_cloudagent/core/event_bus.py @@ -19,7 +19,7 @@ ) from functools import partial -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst if TYPE_CHECKING: # To avoid circular import error from .profile import Profile @@ -99,9 +99,10 @@ async def notify(self, profile: "Profile", event: Event): # TODO don't block notifier until subscribers have all been called? # TODO trigger each processor but don't await? # TODO log errors but otherwise ignore? - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.debug("Notifying subscribers: %s", event) @@ -173,9 +174,10 @@ def wait_for_event( async def _handle_single_event(profile, event): """Handle the single event.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.debug( "wait_for_event event listener with event %s and profile %s", diff --git a/aries_cloudagent/core/oob_processor.py b/aries_cloudagent/core/oob_processor.py index ccecc1a606..9d8b97b0f0 100644 --- a/aries_cloudagent/core/oob_processor.py +++ b/aries_cloudagent/core/oob_processor.py @@ -5,7 +5,7 @@ from typing import Any, Callable, Dict, List, Optional, cast from ..messaging.agent_message import AgentMessage -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..connections.models.conn_record import ConnRecord from ..connections.models.connection_target import ConnectionTarget from ..messaging.decorators.service_decorator import ServiceDecorator @@ -23,6 +23,8 @@ from .error import BaseError from .profile import Profile +LOGGER = logging.getLogger(__name__) + class OobMessageProcessorError(BaseError): """Base error for OobMessageProcessor.""" @@ -70,9 +72,10 @@ async def find_oob_target_for_outbound_message( self, profile: Profile, outbound_message: OutboundMessage ) -> Optional[ConnectionTarget]: """Find connection target for the outbound message.""" - logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) try: async with profile.session() as session: @@ -81,7 +84,7 @@ async def find_oob_target_for_outbound_message( session, {"attach_thread_id": outbound_message.reply_thread_id} ) - logger.debug( + _logger.debug( "extracting their service from oob record %s", oob_record.their_service, ) @@ -91,7 +94,7 @@ async def find_oob_target_for_outbound_message( # Attach ~service decorator so other message can respond message = json.loads(outbound_message.payload) if not message.get("~service"): - logger.debug( + _logger.debug( "Setting our service on the message ~service %s", oob_record.our_service, ) @@ -104,7 +107,9 @@ async def find_oob_target_for_outbound_message( outbound_message.payload = json.dumps(message) - logger.debug("Sending oob message payload %s", outbound_message.payload) + _logger.debug( + "Sending oob message payload %s", outbound_message.payload + ) return ConnectionTarget( endpoint=their_service.endpoint, @@ -121,15 +126,17 @@ async def find_oob_record_for_inbound_message( """Find oob record for inbound message.""" message_type = context.message._type oob_record = None - logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) async with context.profile.session() as session: # First try to find the oob record based on the associated pthid if context.message_receipt.parent_thread_id: try: - logger.debug( + _logger.debug( "Retrieving OOB record using pthid " f"{context.message_receipt.parent_thread_id} " f"for message type {message_type}" @@ -153,7 +160,7 @@ async def find_oob_record_for_inbound_message( and context.message_receipt.recipient_verkey ): try: - logger.debug( + _logger.debug( "Retrieving OOB record using thid " f"{context.message_receipt.thread_id} and recipient verkey" f" {context.message_receipt.recipient_verkey} for " @@ -174,7 +181,7 @@ async def find_oob_record_for_inbound_message( if not oob_record: return None - logger.debug( + _logger.debug( f"Found out of band record for inbound message with type {message_type}" f": {oob_record.oob_id}" ) @@ -190,14 +197,14 @@ async def find_oob_record_for_inbound_message( and context.connection_record and context.connection_record.connection_id != oob_record.connection_id ): - logger.debug( + _logger.debug( f"Oob record connection id {oob_record.connection_id} is different from" f" inbound message connection {context.connection_record.connection_id}", ) # Mismatch in connection id's in only allowed in state await response # (connection id can change bc of reuse) if oob_record.state != OobRecord.STATE_AWAIT_RESPONSE: - logger.debug( + _logger.debug( "Inbound message has incorrect connection_id " f"{context.connection_record.connection_id}. Oob record " f"{oob_record.oob_id} associated with connection id " @@ -212,7 +219,7 @@ async def find_oob_record_for_inbound_message( oob_record.invitation.requests_attach and oob_record.state == OobRecord.STATE_AWAIT_RESPONSE ): - logger.debug( + _logger.debug( f"Removing stale connection {oob_record.connection_id} due " "to connection reuse" ) @@ -237,7 +244,7 @@ async def find_oob_record_for_inbound_message( ] if context.message_receipt.thread_id not in allowed_thread_ids: - logger.debug( + _logger.debug( "Inbound message is for not allowed thread " f"{context.message_receipt.thread_id}. Allowed " f"threads are {allowed_thread_ids}" @@ -249,7 +256,7 @@ async def find_oob_record_for_inbound_message( oob_record.attach_thread_id and context.message_receipt.thread_id != oob_record.attach_thread_id ): - logger.debug( + _logger.debug( f"Inbound message thread id {context.message_receipt.thread_id} does not" f" match oob record thread id {oob_record.attach_thread_id}" ) @@ -276,7 +283,7 @@ async def find_oob_record_for_inbound_message( ) ) ): - logger.debug( + _logger.debug( "Inbound message sender verkey does not match stored service on oob" " record" ) @@ -285,7 +292,7 @@ async def find_oob_record_for_inbound_message( # If the message has a ~service decorator we save it in the oob record so we # can reply to this message if context._message._service: - logger.debug( + _logger.debug( "Storing service decorator in oob record %s", context.message._service.serialize(), ) @@ -313,9 +320,10 @@ async def handle_message( their_service: Optional[ServiceDecorator] = None, ): """Message handler for inbound messages.""" - logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) supported_types = [ @@ -357,7 +365,7 @@ async def handle_message( if not oob_record.connection_id: oob_record.attach_thread_id = self.get_thread_id(message) if their_service: - logger.debug( + _logger.debug( "Storing their service in oob record %s", their_service ) oob_record.their_service = their_service.serialize() diff --git a/aries_cloudagent/core/tests/test_event_bus.py b/aries_cloudagent/core/tests/test_event_bus.py index 5380f3d372..26ce28dacf 100644 --- a/aries_cloudagent/core/tests/test_event_bus.py +++ b/aries_cloudagent/core/tests/test_event_bus.py @@ -85,14 +85,7 @@ def test_unsub_unsubbed_processor(event_bus: EventBus, processor): async def test_sub_notify(event_bus: EventBus, profile, event, processor): """Test subscriber receives event.""" event_bus.subscribe(re.compile(".*"), processor) - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), - ), - ): - await event_bus.notify(profile, event) + await event_bus.notify(profile, event) assert processor.profile == profile assert processor.event == event @@ -113,14 +106,7 @@ def _raise_exception(profile, event): event_bus.subscribe(re.compile(".*"), bad_processor) event_bus.subscribe(re.compile(".*"), processor) with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock( - debug=async_mock.MagicMock(), - exception=async_mock.MagicMock(), - ), - ), + test_module.LOGGER, "exception", async_mock.MagicMock() ) as mock_log_exc: await event_bus.notify(profile, event) @@ -142,87 +128,53 @@ async def test_sub_notify_regex_filtering( event_bus: EventBus, profile, processor, pattern, topic ): """Test events are filtered correctly.""" - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), - ), - ): - event = Event(topic) - event_bus.subscribe(re.compile(pattern), processor) - await event_bus.notify(profile, event) - assert processor.profile == profile - assert processor.event == event + event = Event(topic) + event_bus.subscribe(re.compile(pattern), processor) + await event_bus.notify(profile, event) + assert processor.profile == profile + assert processor.event == event @pytest.mark.asyncio async def test_sub_notify_no_match(event_bus: EventBus, profile, event, processor): """Test event not given to processor when pattern doesn't match.""" - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), - ), - ): - event_bus.subscribe(re.compile("^$"), processor) - await event_bus.notify(profile, event) - assert processor.profile is None - assert processor.event is None + event_bus.subscribe(re.compile("^$"), processor) + await event_bus.notify(profile, event) + assert processor.profile is None + assert processor.event is None @pytest.mark.asyncio async def test_sub_notify_only_one(event_bus: EventBus, profile, event, processor): """Test only one subscriber is called when pattern matches only one.""" - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), - ), - ): - processor1 = MockProcessor() - event_bus.subscribe(re.compile(".*"), processor) - event_bus.subscribe(re.compile("^$"), processor1) - await event_bus.notify(profile, event) - assert processor.profile == profile - assert processor.event == event - assert processor1.profile is None - assert processor1.event is None + processor1 = MockProcessor() + event_bus.subscribe(re.compile(".*"), processor) + event_bus.subscribe(re.compile("^$"), processor1) + await event_bus.notify(profile, event) + assert processor.profile == profile + assert processor.event == event + assert processor1.profile is None + assert processor1.event is None @pytest.mark.asyncio async def test_sub_notify_both(event_bus: EventBus, profile, event, processor): """Test both subscribers are called when pattern matches both.""" - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), - ), - ): - processor1 = MockProcessor() - event_bus.subscribe(re.compile(".*"), processor) - event_bus.subscribe(re.compile("anything"), processor1) - await event_bus.notify(profile, event) - assert processor.profile == profile - assert processor.event == event - assert processor1.profile == profile - assert processor1.event == event + processor1 = MockProcessor() + event_bus.subscribe(re.compile(".*"), processor) + event_bus.subscribe(re.compile("anything"), processor1) + await event_bus.notify(profile, event) + assert processor.profile == profile + assert processor.event == event + assert processor1.profile == profile + assert processor1.event == event @pytest.mark.asyncio async def test_wait_for_event_multiple_do_not_collide(event_bus: EventBus, profile): """Test multiple wait_for_event calls don't collide.""" pattern = re.compile(".*") - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), - ), - ), event_bus.wait_for_event(profile, pattern) as event1: + with event_bus.wait_for_event(profile, pattern) as event1: with event_bus.wait_for_event(profile, pattern) as event2: assert len(event_bus.topic_patterns_to_subscribers) == 1 assert len(event_bus.topic_patterns_to_subscribers[pattern]) == 2 @@ -234,13 +186,7 @@ async def test_wait_for_event_multiple_do_not_collide(event_bus: EventBus, profi @pytest.mark.asyncio async def test_wait_for_event(event_bus: EventBus, profile, event): - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), - ), - ), event_bus.wait_for_event(profile, re.compile(".*")) as returned_event: + with event_bus.wait_for_event(profile, re.compile(".*")) as returned_event: await event_bus.notify(profile, event) assert await returned_event == event @@ -249,13 +195,7 @@ async def test_wait_for_event(event_bus: EventBus, profile, event): async def test_wait_for_event_condition(event_bus: EventBus, profile, event): with event_bus.wait_for_event( profile, re.compile(".*"), lambda e: e.payload == "asdf" - ) as returned_event, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(debug=async_mock.MagicMock()), - ), - ): + ) as returned_event: # This shouldn't trigger our condition because payload == "payload" await event_bus.notify(profile, event) assert not returned_event.done() diff --git a/aries_cloudagent/indy/credx/holder.py b/aries_cloudagent/indy/credx/holder.py index 2bfe3bc4ba..fa16598304 100644 --- a/aries_cloudagent/indy/credx/holder.py +++ b/aries_cloudagent/indy/credx/holder.py @@ -20,12 +20,13 @@ ) from ...askar.profile import AskarProfile -from ...config.logging import get_logger_inst +from ...config.logging import get_adapted_logger_inst from ...ledger.base import BaseLedger from ...wallet.error import WalletNotFoundError from ..holder import IndyHolder, IndyHolderError +LOGGER = logging.getLogger(__name__) CATEGORY_CREDENTIAL = "credential" CATEGORY_LINK_SECRET = "master_secret" @@ -60,9 +61,10 @@ def __init__(self, profile: AskarProfile): """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/indy/credx/issuer.py b/aries_cloudagent/indy/credx/issuer.py index 91972501b2..a383425bc1 100644 --- a/aries_cloudagent/indy/credx/issuer.py +++ b/aries_cloudagent/indy/credx/issuer.py @@ -21,7 +21,7 @@ ) from ...askar.profile import AskarProfile -from ...config.logging import get_logger_inst +from ...config.logging import get_adapted_logger_inst from ..issuer import ( IndyIssuer, @@ -31,6 +31,7 @@ DEFAULT_SIGNATURE_TYPE, ) +LOGGER = logging.getLogger(__name__) CATEGORY_CRED_DEF = "credential_def" CATEGORY_CRED_DEF_PRIVATE = "credential_def_private" CATEGORY_CRED_DEF_KEY_PROOF = "credential_def_key_proof" @@ -53,9 +54,10 @@ def __init__(self, profile: AskarProfile): """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/indy/credx/verifier.py b/aries_cloudagent/indy/credx/verifier.py index 16b4e830a9..a641096b31 100644 --- a/aries_cloudagent/indy/credx/verifier.py +++ b/aries_cloudagent/indy/credx/verifier.py @@ -7,11 +7,13 @@ from indy_credx import CredxError, Presentation -from ...config.logging import get_logger_inst from ...core.profile import Profile +from ...config.logging import get_adapted_logger_inst from ..verifier import IndyVerifier, PresVerifyMsg +LOGGER = logging.getLogger(__name__) + class IndyCredxVerifier(IndyVerifier): """Indy-Credx verifier class.""" @@ -24,9 +26,10 @@ def __init__(self, profile: Profile): """ self.profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self.profile.settings.get("log.file"), + wallet_id=self.profile.settings.get("wallet.id"), ) async def verify_presentation( diff --git a/aries_cloudagent/indy/sdk/issuer.py b/aries_cloudagent/indy/sdk/issuer.py index 539aed49cb..56891cbc4f 100644 --- a/aries_cloudagent/indy/sdk/issuer.py +++ b/aries_cloudagent/indy/sdk/issuer.py @@ -8,7 +8,7 @@ import indy.blob_storage from indy.error import AnoncredsRevocationRegistryFullError, IndyError, ErrorCode -from ...config.logging import get_logger_inst +from ...config.logging import get_adapted_logger_inst from ...indy.sdk.profile import IndySdkProfile from ...messaging.util import encode from ...storage.error import StorageError @@ -24,6 +24,8 @@ from .error import IndyErrorHandler from .util import create_tails_reader, create_tails_writer +LOGGER = logging.getLogger(__name__) + class IndySdkIssuer(IndyIssuer): """Indy-SDK issuer implementation.""" @@ -36,9 +38,10 @@ def __init__(self, profile: IndySdkProfile): """ self.profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self.profile.settings.get("log.file"), + wallet_id=self.profile.settings.get("wallet.id"), ) async def create_schema( diff --git a/aries_cloudagent/indy/sdk/verifier.py b/aries_cloudagent/indy/sdk/verifier.py index 7a9317b300..59c3815f43 100644 --- a/aries_cloudagent/indy/sdk/verifier.py +++ b/aries_cloudagent/indy/sdk/verifier.py @@ -8,11 +8,13 @@ import indy.anoncreds from indy.error import IndyError -from ...config.logging import get_logger_inst from ...core.profile import Profile +from ...config.logging import get_adapted_logger_inst from ..verifier import IndyVerifier, PresVerifyMsg +LOGGER = logging.getLogger(__name__) + class IndySdkVerifier(IndyVerifier): """Indy-SDK verifier implementation.""" @@ -25,9 +27,10 @@ def __init__(self, profile: Profile): """ self.profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self.profile.settings.get("log.file"), + wallet_id=self.profile.settings.get("wallet.id"), ) async def verify_presentation( diff --git a/aries_cloudagent/indy/verifier.py b/aries_cloudagent/indy/verifier.py index 1d46a9d4fd..1da88f8c17 100644 --- a/aries_cloudagent/indy/verifier.py +++ b/aries_cloudagent/indy/verifier.py @@ -7,7 +7,7 @@ from time import time from typing import Mapping, Tuple -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..core.profile import Profile from ..ledger.multiple_ledger.ledger_requests_executor import ( GET_CRED_DEF, @@ -124,9 +124,10 @@ async def check_timestamps( pres: indy proof request rev_reg_defs: rev reg defs by rev reg id, augmented with transaction times """ - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) msgs = [] now = int(time()) diff --git a/aries_cloudagent/ledger/indy.py b/aries_cloudagent/ledger/indy.py index 056b5a80d3..c66d4edf12 100644 --- a/aries_cloudagent/ledger/indy.py +++ b/aries_cloudagent/ledger/indy.py @@ -16,7 +16,7 @@ from ..cache.base import BaseCache from ..config.base import BaseInjector, BaseProvider, BaseSettings -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..indy.sdk.error import IndyErrorHandler from ..storage.base import StorageRecord from ..storage.indy import IndySdkStorage @@ -277,9 +277,10 @@ def __init__( """ self.pool = pool self.profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self.profile.settings.get("log.file"), + wallet_id=self.profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/ledger/multiple_ledger/indy_manager.py b/aries_cloudagent/ledger/multiple_ledger/indy_manager.py index edd3889e5c..df25db9b78 100644 --- a/aries_cloudagent/ledger/multiple_ledger/indy_manager.py +++ b/aries_cloudagent/ledger/multiple_ledger/indy_manager.py @@ -9,8 +9,8 @@ from typing import Optional, Tuple, Mapping, List from ...cache.base import BaseCache -from ...config.logging import get_logger_inst from ...core.profile import Profile +from ...config.logging import get_adapted_logger_inst from ...ledger.base import BaseLedger from ...ledger.error import LedgerError from ...wallet.crypto import did_is_self_certified @@ -24,6 +24,8 @@ from .base_manager import BaseMultipleLedgerManager, MultipleLedgerManagerError +LOGGER = logging.getLogger(__name__) + class MultiIndyLedgerManager(BaseMultipleLedgerManager): """Multiple Indy SDK Ledger Manager.""" @@ -53,9 +55,10 @@ def __init__( self.endorser_map = endorser_map self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=5) self.cache_ttl = cache_ttl - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self.profile.settings.get("log.file"), + wallet_id=self.profile.settings.get("wallet.id"), ) async def get_write_ledgers(self) -> List[str]: diff --git a/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py b/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py index 10cc2b4d35..5c8a51e61b 100644 --- a/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py +++ b/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py @@ -8,8 +8,8 @@ from typing import Optional, Tuple, Mapping, List from ...cache.base import BaseCache -from ...config.logging import get_logger_inst from ...core.profile import Profile +from ...config.logging import get_adapted_logger_inst from ...ledger.base import BaseLedger from ...ledger.error import LedgerError from ...wallet.crypto import did_is_self_certified @@ -23,6 +23,8 @@ from .base_manager import BaseMultipleLedgerManager, MultipleLedgerManagerError +LOGGER = logging.getLogger(__name__) + class MultiIndyVDRLedgerManager(BaseMultipleLedgerManager): """Multiple Indy VDR Ledger Manager.""" @@ -52,9 +54,10 @@ def __init__( self.endorser_map = endorser_map self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=5) self.cache_ttl = cache_ttl - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self.profile.settings.get("log.file"), + wallet_id=self.profile.settings.get("wallet.id"), ) async def get_write_ledgers(self) -> List[str]: diff --git a/aries_cloudagent/ledger/routes.py b/aries_cloudagent/ledger/routes.py index 68c357be20..a45fc85a7f 100644 --- a/aries_cloudagent/ledger/routes.py +++ b/aries_cloudagent/ledger/routes.py @@ -15,7 +15,7 @@ from marshmallow import fields, validate from ..admin.request_context import AdminRequestContext -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..connections.models.conn_record import ConnRecord from ..messaging.models.base import BaseModelError from ..messaging.models.openapi import OpenAPISchema @@ -68,6 +68,8 @@ ) from .util import notify_register_did_event +LOGGER = logging.getLogger(__name__) + class LedgerModulesResultSchema(OpenAPISchema): """Schema for the modules endpoint.""" @@ -645,6 +647,7 @@ async def ledger_accept_taa(request: web.BaseRequest): """ context: AdminRequestContext = request["context"] + profile = context.profile async with context.profile.session() as session: ledger = session.inject_or(BaseLedger) if not ledger: @@ -654,9 +657,10 @@ async def ledger_accept_taa(request: web.BaseRequest): raise web.HTTPForbidden(reason=reason) accept_input = await request.json() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.info(">>> accepting TAA with: %s", accept_input) async with ledger: diff --git a/aries_cloudagent/multitenant/base.py b/aries_cloudagent/multitenant/base.py index 17ce19d636..40a59d3001 100644 --- a/aries_cloudagent/multitenant/base.py +++ b/aries_cloudagent/multitenant/base.py @@ -8,7 +8,7 @@ import jwt from ..config.injection_context import InjectionContext -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..core.error import BaseError from ..core.profile import Profile, ProfileSession from ..protocols.coordinate_mediation.v1_0.manager import ( @@ -24,6 +24,8 @@ from ..wallet.models.wallet_record import WalletRecord from .error import WalletKeyMissingError +LOGGER = logging.getLogger(__name__) + class MultitenantManagerError(BaseError): """Generic multitenant error.""" @@ -41,9 +43,10 @@ def __init__(self, profile: Profile): self._profile = profile if not profile: raise MultitenantManagerError("Missing profile") - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/multitenant/cache.py b/aries_cloudagent/multitenant/cache.py index ce9c75497c..f9b5625a1f 100644 --- a/aries_cloudagent/multitenant/cache.py +++ b/aries_cloudagent/multitenant/cache.py @@ -5,7 +5,7 @@ from typing import Optional from weakref import WeakValueDictionary -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..core.profile import Profile LOGGER = logging.getLogger(__name__) @@ -55,9 +55,10 @@ def get(self, key: str) -> Optional[Profile]: """ value = self.profiles.get(key) if value: - _logger: logging.Logger = get_logger_inst( - profile=value, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=value.settings.get("log.file"), + wallet_id=value.settings.get("wallet.id"), ) if key not in self._cache: _logger.debug( diff --git a/aries_cloudagent/multitenant/route_manager.py b/aries_cloudagent/multitenant/route_manager.py index c7b2e76078..c664eddfef 100644 --- a/aries_cloudagent/multitenant/route_manager.py +++ b/aries_cloudagent/multitenant/route_manager.py @@ -4,8 +4,8 @@ import logging from typing import List, Optional, Tuple +from ..config.logging import get_adapted_logger_inst from ..connections.models.conn_record import ConnRecord -from ..config.logging import get_logger_inst from ..core.profile import Profile from ..messaging.responder import BaseResponder from ..protocols.coordinate_mediation.v1_0.manager import MediationManager @@ -49,9 +49,10 @@ async def _route_for_key( skip_if_exists: bool = False, replace_key: Optional[str] = None, ): - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) wallet_id = profile.settings["wallet.id"] _logger.info( @@ -139,9 +140,10 @@ async def connection_from_recipient_key( for sub wallets, we check the sub wallet's connections before the base wallet. """ - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.debug("Retrieving connection for recipient key for multitenant wallet") manager = profile.inject(BaseMultitenantManager) diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py index 59387be24a..e7806ee596 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py @@ -1,8 +1,6 @@ """Action menu request message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -23,14 +21,16 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("MenuRequestHandler called with context %s", context) + self._logger.debug("MenuRequestHandler called with context %s", context) assert isinstance(context.message, MenuRequest) - _logger.info("Received action menu request") + self._logger.info("Received action menu request") service: BaseMenuService = context.inject_or(BaseMenuService) if service: diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py index 21cb8a65ec..83f1dd2254 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py @@ -1,8 +1,6 @@ """Action menu perform request message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -23,14 +21,16 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("PerformHandler called with context %s", context) + self._logger.debug("PerformHandler called with context %s", context) assert isinstance(context.message, Perform) - _logger.info("Received action menu perform request") + self._logger.info("Received action menu perform request") service: BaseMenuService = context.inject_or(BaseMenuService) if service: diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/routes.py b/aries_cloudagent/protocols/actionmenu/v1_0/routes.py index 53dcd2a1cc..d2ebc1be04 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/routes.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/routes.py @@ -8,7 +8,7 @@ from marshmallow import fields from ....admin.request_context import AdminRequestContext -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord from ....messaging.models.base import BaseModelError from ....messaging.models.openapi import OpenAPISchema @@ -20,6 +20,8 @@ from .models.menu_option import MenuOptionSchema from .util import MENU_RECORD_TYPE, retrieve_connection_menu, save_connection_menu +LOGGER = logging.getLogger(__name__) + class ActionMenuModulesResultSchema(OpenAPISchema): """Schema for the modules endpoint.""" @@ -177,11 +179,13 @@ async def actionmenu_request(request: web.BaseRequest): """ context: AdminRequestContext = request["context"] + profile = context.profile connection_id = request.match_info["conn_id"] outbound_handler = request["outbound_message_router"] - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) try: async with context.profile.session() as session: @@ -210,12 +214,14 @@ async def actionmenu_send(request: web.BaseRequest): """ context: AdminRequestContext = request["context"] + profile = context.profile connection_id = request.match_info["conn_id"] outbound_handler = request["outbound_message_router"] menu_json = await request.json() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.debug("Received send-menu request: %s %s", connection_id, menu_json) try: diff --git a/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py b/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py index cbc167cde3..c84f218b20 100644 --- a/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py +++ b/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py @@ -1,8 +1,6 @@ """Basic message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -22,14 +20,16 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("BasicMessageHandler called with context %s", context) + self._logger.debug("BasicMessageHandler called with context %s", context) assert isinstance(context.message, BasicMessage) - _logger.info("Received basic message: %s", context.message.content) + self._logger.info("Received basic message: %s", context.message.content) body = context.message.content meta = {"content": body} diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py index 02514506af..d4ed484743 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py @@ -1,8 +1,6 @@ """Connection request handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....connections.models.conn_record import ConnRecord from .....messaging.base_handler import BaseHandler, BaseResponder, RequestContext from ....coordinate_mediation.v1_0.manager import MediationManager @@ -22,14 +20,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"ConnectionRequestHandler called with context {context}") + self._logger.debug(f"ConnectionRequestHandler called with context {context}") assert isinstance(context.message, ConnectionRequest) - - profile = context.profile mgr = ConnectionManager(profile) mediation_id = None @@ -54,9 +52,9 @@ async def handle(self, context: RequestContext, responder: BaseResponder): response, connection_id=connection.connection_id ) else: - _logger.debug("Connection request will await acceptance") + self._logger.debug("Connection request will await acceptance") except ConnectionManagerError as e: - _logger.exception("Error receiving connection request") + self._logger.exception("Error receiving connection request") if e.error_code: targets = None if context.message.connection and context.message.connection.did_doc: @@ -66,7 +64,9 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message_receipt.recipient_verkey, ) except ConnectionManagerError: - _logger.exception("Error parsing DIDDoc for problem report") + self._logger.exception( + "Error parsing DIDDoc for problem report" + ) await responder.send_reply( ConnectionProblemReport(problem_code=e.error_code, explain=str(e)), target_list=targets, diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py index 9215e5d4e3..c542a72a9f 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py @@ -1,8 +1,6 @@ """Connection response handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -25,21 +23,21 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"ConnectionResponseHandler called with context {context}") + self._logger.debug(f"ConnectionResponseHandler called with context {context}") assert isinstance(context.message, ConnectionResponse) - - profile = context.profile mgr = ConnectionManager(profile) try: connection = await mgr.accept_response( context.message, context.message_receipt ) except ConnectionManagerError as e: - _logger.exception("Error receiving connection response") + self._logger.exception("Error receiving connection response") if e.error_code: targets = None if context.message.connection and context.message.connection.did_doc: @@ -49,7 +47,9 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message_receipt.recipient_verkey, ) except ConnectionManagerError: - _logger.exception("Error parsing DIDDoc for problem report") + self._logger.exception( + "Error parsing DIDDoc for problem report" + ) await responder.send_reply( ConnectionProblemReport(problem_code=e.error_code, explain=str(e)), target_list=targets, diff --git a/aries_cloudagent/protocols/connections/v1_0/manager.py b/aries_cloudagent/protocols/connections/v1_0/manager.py index 8e30d81e8c..a05db729c1 100644 --- a/aries_cloudagent/protocols/connections/v1_0/manager.py +++ b/aries_cloudagent/protocols/connections/v1_0/manager.py @@ -5,7 +5,7 @@ from ....core.oob_processor import OobMessageProcessor -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....connections.base_manager import BaseConnectionManager from ....connections.models.conn_record import ConnRecord from ....core.error import BaseError @@ -26,6 +26,8 @@ from .messages.problem_report import ProblemReportReason from .models.connection_detail import ConnectionDetail +LOGGER = logging.getLogger(__name__) + class ConnectionManagerError(BaseError): """Connection error.""" @@ -41,9 +43,10 @@ def __init__(self, profile: Profile): profile: The profile for this connection manager """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) super().__init__(self._profile) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py index 6549d48a25..3567feeea0 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py @@ -1,7 +1,6 @@ """Handler for keylist message.""" -import logging -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -16,11 +15,15 @@ class KeylistHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist message.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + "%s called with context %s", self.__class__.__name__, context ) - _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, Keylist) if not context.connection_ready: @@ -32,11 +35,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): session, context.connection_record.connection_id ) except StorageNotFoundError as err: - _logger.warning( + self._logger.warning( "Received keylist from connection that is not acting as mediator: %s", err, ) return # TODO verify our keylist matches? - _logger.info("Keylist received: %s", context.message) + self._logger.info("Keylist received: %s", context.message) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py index dabb5a75a8..047af97ed7 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py @@ -1,8 +1,6 @@ """Handler for keylist-query message.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,17 +17,19 @@ class KeylistQueryHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist-query message.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + "%s called with context %s", self.__class__.__name__, context ) - _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, KeylistQuery) if not context.connection_ready: raise HandlerException("Invalid keylist query: no active connection") - - profile = context.profile mgr = MediationManager(profile) try: async with profile.session() as session: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py index 050924b926..37e7066682 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py @@ -1,8 +1,6 @@ """Handler for keylist-update messages.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,17 +17,19 @@ class KeylistUpdateHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist-update messages.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + "%s called with context %s", self.__class__.__name__, context ) - _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, KeylistUpdate) if not context.connection_ready: raise HandlerException("Cannot update routes: no active connection") - - profile = context.profile mgr = MediationManager(profile) try: async with profile.session() as session: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py index 95da6ea67a..f45cef4fba 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py @@ -1,8 +1,6 @@ """Handler for keylist-update-response message.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.profile import Profile from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -19,11 +17,15 @@ class KeylistUpdateResponseHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist-update-response message.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + "%s called with context %s", self.__class__.__name__, context ) - _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, KeylistUpdateResponse) if not context.connection_ready: @@ -41,12 +43,13 @@ async def notify_keylist_updated( self, profile: Profile, connection_id: str, response: KeylistUpdateResponse ): """Notify of keylist update response received.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) route_manager = profile.inject(RouteManager) - _logger.debug( + self._logger.debug( "Retrieving connection ID from route manager of type %s", type(route_manager).__name__, ) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py index ff8c686237..e0406195af 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py @@ -1,8 +1,6 @@ """Handler for mediate-deny message.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -18,17 +16,19 @@ class MediationDenyHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle mediate-deny message.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + "%s called with context %s", self.__class__.__name__, context ) - _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, MediationDeny) if not context.connection_ready: raise HandlerException("Received mediation deny from inactive connection") - - profile = context.profile mgr = MediationManager(profile) try: async with profile.session() as session: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py index 2d5abcaac0..af13775852 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py @@ -1,8 +1,6 @@ """Handler for mediate-grant message.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,17 +17,19 @@ class MediationGrantHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle mediate-grant message.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + "%s called with context %s", self.__class__.__name__, context ) - _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, MediationGrant) if not context.connection_ready: raise HandlerException("Received mediation grant from inactive connection") - - profile = context.profile mgr = MediationManager(profile) try: async with profile.session() as session: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py index 489c83ac29..2a017d9852 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py @@ -1,8 +1,6 @@ """Handler for mediate-request message.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -17,11 +15,15 @@ class MediationRequestHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle mediate-request message.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + "%s called with context %s", self.__class__.__name__, context ) - _logger.debug("%s called with context %s", self.__class__.__name__, context) assert isinstance(context.message, MediationRequest) if not context.connection_ready: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py index 7ec79632db..f9929ef518 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py @@ -42,5 +42,11 @@ async def test_cover(self, request_context, connection_record): } ) handler = test_module.CMProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(context=request_context, responder=responder) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py index a1834c9397..92cb5a0bac 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py @@ -3,9 +3,9 @@ import logging from typing import Dict, Optional, Sequence, Tuple -from ....config.logging import get_logger_inst from ....core.error import BaseError from ....core.profile import Profile, ProfileSession +from ....config.logging import get_adapted_logger_inst from ....storage.base import BaseStorage from ....storage.error import StorageNotFoundError from ....storage.record import StorageRecord @@ -29,6 +29,8 @@ from .models.mediation_record import MediationRecord from .normalization import normalize_from_did_key +LOGGER = logging.getLogger(__name__) + class MediationManagerError(BaseError): """Generic Mediation error.""" @@ -66,9 +68,10 @@ def __init__(self, profile: Profile): self._profile = profile if not profile: raise MediationManagerError("Missing profile") - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) # Role: Server {{{ diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py index 1915fe58e6..84e7ce05a0 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py @@ -8,7 +8,7 @@ import logging from typing import List, Optional, Tuple -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -23,6 +23,8 @@ from .models.mediation_record import MediationRecord from .normalization import normalize_from_did_key +LOGGER = logging.getLogger(__name__) + class RouteManagerError(Exception): """Raised on error from route manager.""" @@ -127,9 +129,10 @@ async def route_connection_as_invitee( mediation_record: Optional[MediationRecord] = None, ) -> Optional[KeylistUpdate]: """Set up routing for a new connection when we are the invitee.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.debug("Routing connection as invitee") my_info = await self.get_or_create_my_did(profile, conn_record) @@ -144,9 +147,10 @@ async def route_connection_as_inviter( mediation_record: Optional[MediationRecord] = None, ) -> Optional[KeylistUpdate]: """Set up routing for a new connection when we are the inviter.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.debug("Routing connection as inviter") my_info = await self.get_or_create_my_did(profile, conn_record) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py index 9c1c14bb85..4ca42c8e04 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py @@ -375,10 +375,12 @@ async def test_add_remove_key_mix(self, manager): async def test_store_update_results( self, session: ProfileSession, - manager: MediationManager, - profile: Profile, ): """test_store_update_results.""" + profile = session.profile + profile.settings["log.file"] = "test.log" + profile.settings["wallet.id"] = "test123" + mock_logger = async_mock.MagicMock(error=async_mock.MagicMock()) await RouteRecord( role=RouteRecord.ROLE_CLIENT, connection_id=TEST_CONN_ID, @@ -396,55 +398,49 @@ async def test_store_update_results( result=KeylistUpdated.RESULT_SUCCESS, ), ] - await manager.store_update_results(TEST_CONN_ID, results) - routes = await RouteRecord.query(session) - - assert len(routes) == 1 - assert routes[0].recipient_key == TEST_ROUTE_VERKEY - - results = [ - KeylistUpdated( - recipient_key=TEST_VERKEY, - action=KeylistUpdateRule.RULE_REMOVE, - result=KeylistUpdated.RESULT_SUCCESS, - ), - ] - with async_mock.patch.object( - RouteRecord, "query", async_mock.CoroutineMock() - ) as mock_route_rec_query, async_mock.patch.object( test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock( - error=async_mock.MagicMock(), + "get_adapted_logger_inst", + async_mock.MagicMock(return_value=mock_logger), + ): + manager = MediationManager(profile) + await manager.store_update_results(TEST_CONN_ID, results) + routes = await RouteRecord.query(session) + + assert len(routes) == 1 + assert routes[0].recipient_key == TEST_ROUTE_VERKEY + + results = [ + KeylistUpdated( + recipient_key=TEST_VERKEY, + action=KeylistUpdateRule.RULE_REMOVE, + result=KeylistUpdated.RESULT_SUCCESS, ), - ), - ) as mock_logger_error: - _manager_with_mock_logger = MediationManager(profile) - mock_route_rec_query.side_effect = StorageNotFoundError("no record") - - await _manager_with_mock_logger.store_update_results(TEST_CONN_ID, results) - mock_logger_error.assert_called_once() - + ] + + with async_mock.patch.object( + RouteRecord, "query", async_mock.CoroutineMock() + ) as mock_route_rec_query: + mock_route_rec_query.side_effect = StorageNotFoundError("no record") + await manager.store_update_results(TEST_CONN_ID, results) + assert mock_logger.error.call_count == 1 + + del profile.settings["log.file"] + del profile.settings["wallet.id"] + mock_logger = async_mock.MagicMock(error=async_mock.MagicMock()) with async_mock.patch.object( RouteRecord, "query", async_mock.CoroutineMock() ) as mock_route_rec_query, async_mock.patch.object( test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock( - error=async_mock.MagicMock(), - ), - ), - ) as mock_logger_error: - _manager_with_mock_logger = MediationManager(profile) + "get_adapted_logger_inst", + async_mock.MagicMock(return_value=mock_logger), + ): mock_route_rec_query.return_value = [ async_mock.MagicMock(delete_record=async_mock.CoroutineMock()) ] * 2 - - await _manager_with_mock_logger.store_update_results(TEST_CONN_ID, results) - mock_logger_error.assert_called_once() + manager = MediationManager(profile) + await manager.store_update_results(TEST_CONN_ID, results) + assert mock_logger.error.call_count == 1 async def test_store_update_results_exists_relay(self, session, manager): """test_store_update_results_record_exists_relay.""" diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py index 754064f1b2..0af0452e43 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py @@ -1,8 +1,6 @@ """Connection complete handler under RFC 23 (DID exchange).""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -23,17 +21,17 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"DIDXCompleteHandler called with context {context}") + self._logger.debug(f"DIDXCompleteHandler called with context {context}") assert isinstance(context.message, DIDXComplete) - - profile = context.profile mgr = DIDXManager(profile) try: await mgr.accept_complete(context.message, context.message_receipt) except DIDXManagerError: # no corresponding request: no targets to send problem report; log and quit - _logger.exception("Error receiving connection complete") + self._logger.exception("Error receiving connection complete") diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py index ee8b8b29cc..faf7131224 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py @@ -3,9 +3,8 @@ from aries_cloudagent.protocols.didexchange.v1_0.messages.problem_report import ( DIDXProblemReport, ) -import logging -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....connections.models.conn_record import ConnRecord from .....messaging.base_handler import BaseHandler, BaseResponder, RequestContext from ....coordinate_mediation.v1_0.manager import MediationManager @@ -23,14 +22,14 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"DIDXRequestHandler called with context {context}") + self._logger.debug(f"DIDXRequestHandler called with context {context}") assert isinstance(context.message, DIDXRequest) - - profile = context.profile mgr = DIDXManager(profile) mediation_id = None @@ -65,10 +64,10 @@ async def handle(self, context: RequestContext, responder: BaseResponder): async with context.session() as session: await conn_rec.save(session, reason="Sent connection response") else: - _logger.debug("DID exchange request will await acceptance") + self._logger.debug("DID exchange request will await acceptance") except DIDXManagerError as e: - _logger.exception("Error receiving RFC 23 connection request") + self._logger.exception("Error receiving RFC 23 connection request") if e.error_code: targets = None if context.message.did_doc_attach: @@ -78,7 +77,9 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message_receipt.recipient_verkey, ) except DIDXManagerError: - _logger.exception("Error parsing DIDDoc for problem report") + self._logger.exception( + "Error parsing DIDDoc for problem report" + ) await responder.send_reply( DIDXProblemReport( description={"en": e.message, "code": e.error_code} diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py index 73f3f84f8b..0efbd0ec34 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py @@ -3,9 +3,8 @@ from aries_cloudagent.protocols.didexchange.v1_0.messages.problem_report import ( DIDXProblemReport, ) -import logging -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -28,21 +27,21 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"DIDXResponseHandler called with context {context}") + self._logger.debug(f"DIDXResponseHandler called with context {context}") assert isinstance(context.message, DIDXResponse) - - profile = context.profile mgr = DIDXManager(profile) try: conn_rec = await mgr.accept_response( context.message, context.message_receipt ) except DIDXManagerError as e: - _logger.exception("Error receiving DID exchange response") + self._logger.exception("Error receiving DID exchange response") if e.error_code: targets = None if context.message.did_doc_attach: @@ -52,7 +51,9 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message_receipt.recipient_verkey, ) except DIDXManagerError: - _logger.exception("Error parsing DIDDoc for problem report") + self._logger.exception( + "Error parsing DIDDoc for problem report" + ) await responder.send_reply( DIDXProblemReport( description={"en": e.message, "code": e.error_code} diff --git a/aries_cloudagent/protocols/didexchange/v1_0/manager.py b/aries_cloudagent/protocols/didexchange/v1_0/manager.py index 2aefdd5dca..a1440940dc 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/manager.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/manager.py @@ -8,7 +8,7 @@ from pydid import BaseDIDDocument as ResolvedDocument from pydid import DIDCommService -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....connections.base_manager import BaseConnectionManager from ....connections.models.conn_record import ConnRecord from ....connections.models.diddoc import DIDDoc @@ -40,6 +40,8 @@ from .messages.request import DIDXRequest from .messages.response import DIDXResponse +LOGGER = logging.getLogger(__name__) + class DIDXManagerError(BaseError): """Connection error.""" @@ -55,9 +57,10 @@ def __init__(self, profile: Profile): profile: The profile for this did exchange manager """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) super().__init__(self._profile) diff --git a/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py b/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py index b7c2dc662e..c547ab1096 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py +++ b/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py @@ -1,8 +1,6 @@ """Handler for incoming disclose messages.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -19,17 +17,18 @@ class DiscloseHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("DiscloseHandler called with context %s", context) + self._logger.debug("DiscloseHandler called with context %s", context) assert isinstance(context.message, Disclose) if not context.connection_ready: raise HandlerException( "Received disclosures message from inactive connection" ) - profile = context.profile mgr = V10DiscoveryMgr(profile) await mgr.receive_disclose( context.message, connection_id=context.connection_record.connection_id diff --git a/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py b/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py index 02f53f31f0..0defd19c6a 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py +++ b/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py @@ -1,8 +1,6 @@ """Handler for incoming query messages.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -18,13 +16,14 @@ class QueryHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("QueryHandler called with context %s", context) + self._logger.debug("QueryHandler called with context %s", context) assert isinstance(context.message, Query) - profile = context.profile mgr = V10DiscoveryMgr(profile) reply = await mgr.receive_query(context.message) reply.assign_thread_from(context.message) diff --git a/aries_cloudagent/protocols/discovery/v1_0/manager.py b/aries_cloudagent/protocols/discovery/v1_0/manager.py index 632d4f8565..f90c0f94e5 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/manager.py +++ b/aries_cloudagent/protocols/discovery/v1_0/manager.py @@ -5,7 +5,7 @@ from typing import Optional -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....core.protocol_registry import ProtocolRegistry @@ -16,6 +16,8 @@ from .messages.query import Query from .models.discovery_record import V10DiscoveryExchangeRecord +LOGGER = logging.getLogger(__name__) + class V10DiscoveryMgrError(BaseError): """Discover feature v1_0 error.""" @@ -31,9 +33,10 @@ def __init__(self, profile: Profile): profile: The profile for this manager """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py b/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py index e3822f82d1..e3a59f0519 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py +++ b/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py @@ -1,8 +1,6 @@ """Handler for incoming disclose messages.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -19,17 +17,18 @@ class DisclosuresHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("DiscloseHandler called with context %s", context) + self._logger.debug("DiscloseHandler called with context %s", context) assert isinstance(context.message, Disclosures) if not context.connection_ready: raise HandlerException( "Received disclosures message from inactive connection" ) - profile = context.profile mgr = V20DiscoveryMgr(profile) await mgr.receive_disclose( context.message, connection_id=context.connection_record.connection_id diff --git a/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py b/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py index 1636246800..4c843c7d7e 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py +++ b/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py @@ -1,8 +1,6 @@ """Handler for incoming queries messages.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -18,13 +16,14 @@ class QueriesHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("QueryHandler called with context %s", context) + self._logger.debug("QueryHandler called with context %s", context) assert isinstance(context.message, Queries) - profile = context.profile mgr = V20DiscoveryMgr(profile) reply = await mgr.receive_query(context.message) reply.assign_thread_from(context.message) diff --git a/aries_cloudagent/protocols/discovery/v2_0/manager.py b/aries_cloudagent/protocols/discovery/v2_0/manager.py index 7c71c4489f..7ee18f6efd 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/manager.py +++ b/aries_cloudagent/protocols/discovery/v2_0/manager.py @@ -5,11 +5,11 @@ from typing import Tuple, Optional, Sequence -from ....config.logging import get_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....core.protocol_registry import ProtocolRegistry from ....core.goal_code_registry import GoalCodeRegistry +from ....config.logging import get_adapted_logger_inst from ....storage.error import StorageNotFoundError from ....messaging.responder import BaseResponder @@ -17,6 +17,8 @@ from .messages.queries import QueryItem, Queries from .models.discovery_record import V20DiscoveryExchangeRecord +LOGGER = logging.getLogger(__name__) + class V20DiscoveryMgrError(BaseError): """Discover feature v2_0 error.""" @@ -32,9 +34,10 @@ def __init__(self, profile: Profile): profile: The profile for this manager """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py index 0d5865e140..d3910e5291 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py @@ -1,8 +1,6 @@ """Endorsed transaction response handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -25,11 +23,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( f"EndorsedTransactionResponseHandler called with context {context}" ) assert isinstance(context.message, EndorsedTransactionResponse) @@ -42,7 +42,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): try: transaction = await mgr.receive_endorse_response(context.message) except TransactionManagerError: - _logger.exception("Error receiving endorsed transaction response") + self._logger.exception("Error receiving endorsed transaction response") # Automatically write transaction if flag is set if context.settings.get("endorser.auto_write"): @@ -57,4 +57,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): connection_id=transaction.connection_id, ) except (StorageError, TransactionManagerError) as err: - _logger.exception(err) + self._logger.exception(err) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py index ff8229fd44..b327557566 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py @@ -1,8 +1,6 @@ """Refused transaction response handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -24,11 +22,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( f"RefusedTransactionResponseHandler called with context {context}" ) assert isinstance(context.message, RefusedTransactionResponse) @@ -40,4 +40,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): try: await mgr.receive_refuse_response(context.message) except TransactionManagerError: - _logger.exception("Error receiving refused transaction response") + self._logger.exception("Error receiving refused transaction response") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_endorsed_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_endorsed_transaction_response_handler.py index d6f8fe5ca6..66e55325db 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_endorsed_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_endorsed_transaction_response_handler.py @@ -26,6 +26,12 @@ async def test_called(self): request_context.message = EndorsedTransactionResponse() request_context.connection_ready = True handler = test_module.EndorsedTransactionResponseHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -48,6 +54,12 @@ async def test_called_not_ready(self): request_context.message = EndorsedTransactionResponse() request_context.connection_ready = False handler = test_module.EndorsedTransactionResponseHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -70,6 +82,12 @@ async def test_called_x(self): request_context.message = EndorsedTransactionResponse() request_context.connection_ready = True handler = test_module.EndorsedTransactionResponseHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_refused_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_refused_transaction_response_handler.py index 33f00c5da5..167458ac6a 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_refused_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_refused_transaction_response_handler.py @@ -26,6 +26,12 @@ async def test_called(self): request_context.message = RefusedTransactionResponse() request_context.connection_ready = True handler = test_module.RefusedTransactionResponseHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -48,6 +54,12 @@ async def test_called_not_ready(self): request_context.message = RefusedTransactionResponse() request_context.connection_ready = False handler = test_module.RefusedTransactionResponseHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -70,6 +82,12 @@ async def test_called_x(self): request_context.message = RefusedTransactionResponse() request_context.connection_ready = True handler = test_module.RefusedTransactionResponseHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_acknowledgement_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_acknowledgement_handler.py index ed4a864727..6b480cc1e4 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_acknowledgement_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_acknowledgement_handler.py @@ -29,6 +29,12 @@ async def test_called(self): ) request_context.connection_ready = True handler = test_module.TransactionAcknowledgementHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -51,6 +57,12 @@ async def test_called_not_ready(self): request_context.message = TransactionAcknowledgement() request_context.connection_ready = False handler = test_module.TransactionAcknowledgementHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -75,6 +87,12 @@ async def test_called_x(self): ) request_context.connection_ready = True handler = test_module.TransactionAcknowledgementHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_cancel_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_cancel_handler.py index bc144c16d6..e9992ffc0e 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_cancel_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_cancel_handler.py @@ -29,6 +29,12 @@ async def test_called(self): ) request_context.connection_ready = True handler = test_module.TransactionCancelHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -51,6 +57,12 @@ async def test_called_not_ready(self): request_context.message = CancelTransaction() request_context.connection_ready = False handler = test_module.TransactionCancelHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -75,6 +87,12 @@ async def test_called_x(self): ) request_context.connection_ready = True handler = test_module.TransactionCancelHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_job_to_send_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_job_to_send_handler.py index 41c66d4a78..a51cdecf02 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_job_to_send_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_job_to_send_handler.py @@ -26,6 +26,12 @@ async def test_called(self): request_context.message = TransactionJobToSend() request_context.connection_ready = True handler = test_module.TransactionJobToSendHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -50,6 +56,12 @@ async def test_called_x(self): request_context.message = TransactionJobToSend() request_context.connection_ready = True handler = test_module.TransactionJobToSendHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_request_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_request_handler.py index 61c525e5f5..b6a70557e7 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_request_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_request_handler.py @@ -27,6 +27,12 @@ async def test_called(self): ) request_context.connection_ready = True handler = test_module.TransactionRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -47,6 +53,12 @@ async def test_called_not_ready(self): request_context.message = TransactionRequest() request_context.connection_ready = False handler = test_module.TransactionRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -69,6 +81,12 @@ async def test_called_x(self): ) request_context.connection_ready = True handler = test_module.TransactionRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_resend_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_resend_handler.py index e0e9ccbcde..8c87cdf195 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_resend_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_resend_handler.py @@ -29,6 +29,12 @@ async def test_called(self): ) request_context.connection_ready = True handler = test_module.TransactionResendHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -51,6 +57,12 @@ async def test_called_not_ready(self): request_context.message = TransactionResend() request_context.connection_ready = False handler = test_module.TransactionResendHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -75,6 +87,12 @@ async def test_called_x(self): ) request_context.connection_ready = True handler = test_module.TransactionResendHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py index 51d9d7f7c9..1294ef710f 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py @@ -1,8 +1,6 @@ """Transaction acknowledgement message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -24,11 +22,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( f"TransactionAcknowledgementHandler called with context {context}" ) assert isinstance(context.message, TransactionAcknowledgement) @@ -42,4 +42,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.connection_record.connection_id ) except TransactionManagerError: - _logger.exception("Error receiving transaction acknowledgement") + self._logger.exception("Error receiving transaction acknowledgement") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py index 7a18f25313..e194cf710e 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py @@ -1,8 +1,6 @@ """Cancel transaction request handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -24,11 +22,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"TransactionCancelHandler called with context {context}") + self._logger.debug(f"TransactionCancelHandler called with context {context}") assert isinstance(context.message, CancelTransaction) if not context.connection_ready: @@ -40,4 +40,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.connection_record.connection_id ) except TransactionManagerError: - _logger.exception("Error receiving cancel transaction request") + self._logger.exception("Error receiving cancel transaction request") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py index 97b90c3797..3a95958e1c 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py @@ -1,8 +1,6 @@ """Transaction Job to send handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -23,11 +21,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"TransactionJobToSendHandler called with context {context}") + self._logger.debug(f"TransactionJobToSendHandler called with context {context}") assert isinstance(context.message, TransactionJobToSend) mgr = TransactionManager(context.profile) @@ -36,4 +36,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.message_receipt ) except TransactionManagerError: - _logger.exception("Error receiving transaction jobs") + self._logger.exception("Error receiving transaction jobs") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py index bf2f6740fa..66da217863 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py @@ -1,8 +1,6 @@ """Transaction request handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -27,11 +25,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"TransactionRequestHandler called with context {context}") + self._logger.debug(f"TransactionRequestHandler called with context {context}") assert isinstance(context.message, TransactionRequest) if not context.connection_ready: @@ -43,7 +43,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.connection_record.connection_id ) except TransactionManagerError as err: - _logger.exception(err) + self._logger.exception(err) return # Automatically endorse transaction if flag is set @@ -62,4 +62,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): connection_id=transaction.connection_id, ) except (StorageError, TransactionManagerError) as err: - _logger.exception(err) + self._logger.exception(err) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py index a2bc62b22d..1fe373b793 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py @@ -1,8 +1,6 @@ """Transaction resend handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -24,11 +22,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"TransactionResendHandler called with context {context}") + self._logger.debug(f"TransactionResendHandler called with context {context}") assert isinstance(context.message, TransactionResend) if not context.connection_ready: @@ -40,4 +40,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.message, context.connection_record.connection_id ) except TransactionManagerError: - _logger.exception("Error receiving resend transaction request") + self._logger.exception("Error receiving resend transaction request") diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py index 56b4ac157c..5a349232b4 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py @@ -15,8 +15,8 @@ from marshmallow import fields, validate from ....admin.request_context import AdminRequestContext +from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord -from ....config.logging import get_logger_inst from ....core.event_bus import Event, EventBus from ....core.profile import Profile from ....core.util import SHUTDOWN_EVENT_PATTERN, STARTUP_EVENT_PATTERN @@ -37,6 +37,8 @@ from .transaction_jobs import TransactionJob from .util import get_endorser_connection_id, is_author_role +LOGGER = logging.getLogger(__name__) + class TransactionListSchema(OpenAPISchema): """Result schema for transaction list.""" @@ -718,9 +720,10 @@ def register_events(event_bus: EventBus): async def on_startup_event(profile: Profile, event: Event): """Handle any events we need to support.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) # auto setup is only for authors if not is_author_role(profile): diff --git a/aries_cloudagent/protocols/introduction/v0_1/demo_service.py b/aries_cloudagent/protocols/introduction/v0_1/demo_service.py index 916c2fbe23..95a0e9b09a 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/demo_service.py +++ b/aries_cloudagent/protocols/introduction/v0_1/demo_service.py @@ -3,7 +3,7 @@ import json import logging -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.profile import ProfileSession from ....storage.base import ( @@ -17,6 +17,8 @@ from .messages.invitation import Invitation as IntroInvitation from .messages.invitation_request import InvitationRequest as IntroInvitationRequest +LOGGER = logging.getLogger(__name__) + class DemoIntroductionService(BaseIntroductionService): """Service handler for allowing connections to exchange invitations.""" @@ -109,9 +111,11 @@ async def return_invitation( outbound_handler: The outbound handler coroutine for sending a message """ thread_id = invitation._thread_id - _logger: logging.Logger = get_logger_inst( - profile=session.profile, - logger_name=__name__, + profile = session.profile + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) tag_filter = {"target_connection_id": target_connection_id} storage = session.inject(BaseStorage) diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py index 35d0264ca5..99a02c3006 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py @@ -1,8 +1,6 @@ """Handler for incoming forward invitation messages.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,11 +19,13 @@ class ForwardInvitationHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("ForwardInvitationHandler called with context %s", context) + self._logger.debug("ForwardInvitationHandler called with context %s", context) assert isinstance(context.message, ForwardInvitation) if not context.connection_ready: @@ -34,13 +34,12 @@ async def handle(self, context: RequestContext, responder: BaseResponder): ) # Store invitation - profile = context.profile connection_mgr = ConnectionManager(profile) try: await connection_mgr.receive_invitation(context.message.invitation) except ConnectionManagerError as e: - _logger.exception("Error receiving forward connection invitation") + self._logger.exception("Error receiving forward connection invitation") await responder.send_reply( ProblemReport( description={ diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py index cff6cc9c44..bf69f9a9fe 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py @@ -1,9 +1,8 @@ """Handler for incoming invitation messages.""" -import logging - -from .....config.logging import get_logger_inst from typing import Optional + +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -20,11 +19,13 @@ class InvitationHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("InvitationHandler called with context %s", context) + self._logger.debug("InvitationHandler called with context %s", context) assert isinstance(context.message, IntroInvitation) if not context.connection_ready: diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py index 0e1658b0a0..508e082d85 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py @@ -1,8 +1,6 @@ """Handler for incoming invitation request messages.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,11 +19,13 @@ class InvitationRequestHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("InvitationRequestHandler called with context %s", context) + self._logger.debug("InvitationRequestHandler called with context %s", context) assert isinstance(context.message, IntroInvitationRequest) if not context.connection_ready: @@ -37,7 +37,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): if context.settings.get("auto_accept_intro_invitation_requests"): # Create a new connection invitation and send it back in an IntroInvitation - profile = context.profile connection_mgr = ConnectionManager(profile) _connection, invite = await connection_mgr.create_invitation() response = IntroInvitation( diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_forward_invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_forward_invitation_handler.py index bb19cea6de..b846d01c16 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_forward_invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_forward_invitation_handler.py @@ -40,6 +40,12 @@ async def setUp(self): async def test_handle(self): handler = test_module.ForwardInvitationHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( @@ -54,6 +60,12 @@ async def test_handle(self): async def test_handle_x(self): handler = test_module.ForwardInvitationHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( @@ -71,6 +83,12 @@ async def test_handle_x(self): async def test_handle_not_ready(self): handler = test_module.ForwardInvitationHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) self.context.connection_ready = False with self.assertRaises(HandlerException): diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py index 7e92953531..a0a75761ad 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py @@ -39,7 +39,12 @@ async def setUp(self): async def test_handle(self): handler = test_module.InvitationHandler() - + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) mock_conn_rec = async_mock.MagicMock(connection_id="dummy") responder = MockResponder() @@ -60,12 +65,24 @@ async def test_handle(self): async def test_handle_no_service(self): handler = test_module.InvitationHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) with self.assertRaises(HandlerException): await handler.handle(self.context, None) async def test_handle_not_ready(self): handler = test_module.InvitationHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) self.context.connection_ready = False with self.assertRaises(HandlerException): diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_request_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_request_handler.py index 3bf7fe259d..170a1e15f0 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_request_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_request_handler.py @@ -33,7 +33,12 @@ async def setUp(self): async def test_handle(self): handler = test_module.InvitationRequestHandler() - + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() inv_req = InvitationRequest(responder=responder, message="Hello") @@ -44,6 +49,12 @@ async def test_handle(self): async def test_handle_auto_accept(self): handler = test_module.InvitationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) self.context.update_settings({"auto_accept_intro_invitation_requests": True}) conn_invitation = ConnectionInvitation( @@ -75,6 +86,12 @@ async def test_handle_auto_accept(self): async def test_handle_not_ready(self): handler = test_module.InvitationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) self.context.connection_ready = False with self.assertRaises(HandlerException): diff --git a/aries_cloudagent/protocols/introduction/v0_1/routes.py b/aries_cloudagent/protocols/introduction/v0_1/routes.py index 7bea8dc82f..6a670e4422 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/routes.py +++ b/aries_cloudagent/protocols/introduction/v0_1/routes.py @@ -9,12 +9,14 @@ from marshmallow import fields from ....admin.request_context import AdminRequestContext -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....messaging.models.openapi import OpenAPISchema from ....messaging.valid import UUID4_EXAMPLE from ....storage.error import StorageError from .base_service import BaseIntroductionService, IntroductionError +LOGGER = logging.getLogger(__name__) + class IntroModuleResponseSchema(OpenAPISchema): """Response schema for Introduction Module.""" @@ -60,9 +62,11 @@ async def introduction_start(request: web.BaseRequest): """ context: AdminRequestContext = request["context"] - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.info("Introduction requested") outbound_handler = request["outbound_message_router"] diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py index ed7f310394..9a4da7c1a8 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py @@ -1,8 +1,6 @@ """Credential ack message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -24,13 +22,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("CredentialAckHandler called with context %s", context) + self._logger.debug("CredentialAckHandler called with context %s", context) assert isinstance(context.message, CredentialAck) - _logger.info( + self._logger.info( "Received credential ack message: %s", context.message.serialize(as_string=True), ) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py index 801ff9d640..3a3a005677 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py @@ -1,8 +1,6 @@ """Credential issue message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError from .....messaging.base_handler import BaseHandler, HandlerException @@ -30,14 +28,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, - ) profile = context.profile - _logger.debug("CredentialHandler called with context %s", context) + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug("CredentialHandler called with context %s", context) assert isinstance(context.message, CredentialIssue) - _logger.info( + self._logger.info( "Received credential message: %s", context.message.serialize(as_string=True) ) @@ -83,7 +82,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, ) as err: # treat failure to store as mangled on receipt hence protocol error - _logger.exception("Error storing issued credential") + self._logger.exception("Error storing issued credential") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py index 79261b4739..2719813057 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py @@ -1,8 +1,6 @@ """Credential offer message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....wallet.util import default_did_from_verkey from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError @@ -32,14 +30,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, - ) profile = context.profile - _logger.debug("CredentialOfferHandler called with context %s", context) + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug("CredentialOfferHandler called with context %s", context) assert isinstance(context.message, CredentialOffer) - _logger.info( + self._logger.info( "Received credential offer message: %s", context.message.serialize(as_string=True), ) @@ -104,7 +103,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): LedgerError, StorageError, ) as err: - _logger.exception("Error responding to credential offer") + self._logger.exception("Error responding to credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py index ba3b7104c1..6a23734851 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py @@ -1,8 +1,6 @@ """Credential problem report message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -22,11 +20,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( "Issue-credential v1.0 problem report handler called with context %s", context, ) @@ -49,6 +49,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.connection_record.connection_id, ) except (StorageError, StorageNotFoundError): - _logger.exception( + self._logger.exception( "Error processing issue-credential v1.0 problem report message" ) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py index 5f015e3cf5..c1c355ecfd 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py @@ -1,8 +1,6 @@ """Credential proposal message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -30,15 +28,16 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, - ) profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) - _logger.debug("CredentialProposalHandler called with context %s", context) + self._logger.debug("CredentialProposalHandler called with context %s", context) assert isinstance(context.message, CredentialProposal) - _logger.info( + self._logger.info( "Received credential proposal message: %s", context.message.serialize(as_string=True), ) @@ -83,7 +82,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): LedgerError, StorageError, ) as err: - _logger.exception("Error responding to credential proposal") + self._logger.exception("Error responding to credential proposal") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py index 239a899586..6cbaa247bc 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py @@ -1,8 +1,6 @@ """Credential request message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError @@ -31,14 +29,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, - ) profile = context.profile - _logger.debug("CredentialRequestHandler called with context %s", context) + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug("CredentialRequestHandler called with context %s", context) assert isinstance(context.message, CredentialRequest) - _logger.info( + self._logger.info( "Received credential request message: %s", context.message.serialize(as_string=True), ) @@ -94,7 +93,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): LedgerError, StorageError, ) as err: - _logger.exception("Error responding to credential request") + self._logger.exception("Error responding to credential request") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( @@ -115,7 +114,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): perf_counter=r_time, ) else: - _logger.warning( + self._logger.warning( "Operation set for auto-issue but credential exchange record " f"{cred_ex_record.credential_exchange_id} " "has no attribute values" diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_ack_handler.py index ae0c31f0e6..e1c357877f 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_ack_handler.py @@ -34,6 +34,12 @@ async def test_called(self): request_context.message = CredentialAck() request_context.connection_ready = True handler = test_module.CredentialAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -60,6 +66,12 @@ async def test_called_not_ready(self): request_context.message = CredentialAck() request_context.connection_ready = False handler = test_module.CredentialAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -88,6 +100,12 @@ async def test_called_no_connection_no_oob(self): request_context.message = CredentialAck() request_context.connection_ready = False handler = test_module.CredentialAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py index ae5fe7e4a5..90fb3fa00b 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py @@ -31,6 +31,12 @@ async def test_called(self): request_context.message = CredentialIssue() request_context.connection_ready = True handler = test_module.CredentialIssueHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -72,6 +78,12 @@ async def test_called_auto_store(self): request_context.message = CredentialIssue() request_context.connection_ready = True handler = test_module.CredentialIssueHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -120,16 +132,18 @@ async def test_called_auto_store_x(self): request_context.message = CredentialIssue() request_context.connection_ready = True handler = test_module.CredentialIssueHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() ) as mock_send_reply, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), + handler._logger, "exception", async_mock.MagicMock() ) as mock_log_exc: await handler.handle(request_context, responder) mock_log_exc.assert_called_once() @@ -146,6 +160,12 @@ async def test_called_not_ready(self): request_context.message = CredentialIssue() request_context.connection_ready = False handler = test_module.CredentialIssueHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -171,6 +191,12 @@ async def test_called_no_connection_no_oob(self): mock_cred_mgr.return_value.receive_credential = async_mock.CoroutineMock() request_context.message = CredentialIssue() handler = test_module.CredentialIssueHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py index 52d39fc296..f11ef8b374 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py @@ -31,6 +31,12 @@ async def test_called(self): request_context.message = CredentialOffer() request_context.connection_ready = True handler = test_module.CredentialOfferHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -67,6 +73,12 @@ async def test_called_auto_request(self): request_context.message = CredentialOffer() request_context.connection_ready = True handler = test_module.CredentialOfferHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -112,19 +124,19 @@ async def test_called_auto_request_x(self): request_context.message = CredentialOffer() request_context.connection_ready = True handler = test_module.CredentialOfferHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: + ) as mock_send_reply: await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + assert handler._logger.exception.call_count == 1 async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -138,6 +150,12 @@ async def test_called_not_ready(self): request_context.message = CredentialOffer() request_context.connection_ready = False handler = test_module.CredentialOfferHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -167,6 +185,12 @@ async def test_no_conn_no_oob(self): request_context.message = CredentialOffer() request_context.connection_ready = False handler = test_module.CredentialOfferHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_problem_report_handler.py index 2187e6258c..f675111fe9 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_problem_report_handler.py @@ -32,6 +32,12 @@ async def test_called(self): } ) handler = test_module.CredentialProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -62,6 +68,12 @@ async def test_called_x(self): } ) handler = test_module.CredentialProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -84,6 +96,12 @@ async def test_called_not_ready(self): } ) handler = test_module.CredentialProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: @@ -105,6 +123,12 @@ async def test_called_no_connection(self): } ) handler = test_module.CredentialProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py index 20b26fb8b3..5682fbf6ee 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py @@ -25,6 +25,12 @@ async def test_called(self): request_context.message = CredentialProposal() request_context.connection_ready = True handler = test_module.CredentialProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -52,6 +58,12 @@ async def test_called_auto_offer(self): request_context.message = CredentialProposal() request_context.connection_ready = True handler = test_module.CredentialProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -86,19 +98,19 @@ async def test_called_auto_offer_x(self): request_context.message = CredentialProposal() request_context.connection_ready = True handler = test_module.CredentialProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: + ) as mock_send_reply: await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + assert handler._logger.exception.call_count == 1 async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -112,6 +124,12 @@ async def test_called_not_ready(self): request_context.message = CredentialProposal() request_context.connection_ready = False handler = test_module.CredentialProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -128,6 +146,12 @@ async def test_called_no_connection(self): request_context.message = CredentialProposal() handler = test_module.CredentialProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py index fd702fbece..2a4741ecbb 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py @@ -38,6 +38,12 @@ async def test_called(self): request_context.message = CredentialRequest() request_context.connection_ready = True handler = test_module.CredentialRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -86,6 +92,12 @@ async def test_called_auto_issue(self): request_context.message = CredentialRequest() request_context.connection_ready = True handler = test_module.CredentialRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_cred_mgr.return_value.issue_credential.assert_called_once_with( @@ -144,19 +156,19 @@ async def test_called_auto_issue_x(self): request_context.message = CredentialRequest() request_context.connection_ready = True handler = test_module.CredentialRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: + ) as mock_send_reply: await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + assert handler._logger.exception.call_count == 1 async def test_called_auto_issue_no_preview(self): request_context = RequestContext.test_context() @@ -189,6 +201,12 @@ async def test_called_auto_issue_no_preview(self): request_context.message = CredentialRequest() request_context.connection_ready = True handler = test_module.CredentialRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_cred_mgr.return_value.issue_credential.assert_not_called() @@ -214,6 +232,12 @@ async def test_called_not_ready(self): request_context.message = CredentialRequest() request_context.connection_ready = False handler = test_module.CredentialRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -242,6 +266,12 @@ async def test_called_no_connection_no_oob(self): mock_cred_mgr.return_value.receive_request = async_mock.CoroutineMock() request_context.message = CredentialRequest() handler = test_module.CredentialRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/manager.py b/aries_cloudagent/protocols/issue_credential/v1_0/manager.py index 53a6b5e555..fc3ba0a366 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/manager.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/manager.py @@ -7,8 +7,8 @@ from typing import Mapping, Optional, Tuple from ....cache.base import BaseCache -from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord +from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....indy.holder import IndyHolder, IndyHolderError @@ -45,6 +45,8 @@ V10CredentialExchange, ) +LOGGER = logging.getLogger(__name__) + class CredentialManagerError(BaseError): """Credential error.""" @@ -60,9 +62,10 @@ def __init__(self, profile: Profile): profile: The profile instance for this credential manager """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py b/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py index d2d2804093..4d2cf0ab95 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py @@ -5,7 +5,7 @@ from marshmallow import fields, validate -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.profile import ProfileSession from .....indy.models.cred import IndyCredential, IndyCredentialSchema from .....indy.models.cred_abstract import IndyCredAbstract, IndyCredAbstractSchema @@ -25,6 +25,8 @@ from ..messages.credential_proposal import CredentialProposal, CredentialProposalSchema from . import UNENCRYPTED_TAGS +LOGGER = logging.getLogger(__name__) + class V10CredentialExchange(BaseExchangeRecord): """Represents an Aries#0036 credential exchange.""" @@ -205,9 +207,11 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - _logger: logging.Logger = get_logger_inst( - profile=session.profile, - logger_name=__name__, + profile = session.profile + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) if self._last_state == state: # already done return diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/models/tests/test_credential_exchange.py b/aries_cloudagent/protocols/issue_credential/v1_0/models/tests/test_credential_exchange.py index 130bb30300..d1df7d7f71 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/models/tests/test_credential_exchange.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/models/tests/test_credential_exchange.py @@ -80,11 +80,7 @@ async def test_save_error_state(self): with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), + test_module.LOGGER, "exception", async_mock.MagicMock() ) as mock_log_exc: mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="test") diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py index 8159c5f07b..0d6f7d4b74 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py @@ -1546,36 +1546,26 @@ async def test_send_credential_ack(self): new_with_id=True, ) await stored_exchange.save(self.session) - mock_logger_inst = async_mock.MagicMock( - exception=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - ) with async_mock.patch.object( V10CredentialExchange, "save", autospec=True ) as mock_save_ex, async_mock.patch.object( V10CredentialExchange, "delete_record", autospec=True ) as mock_delete_ex, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=mock_logger_inst, - ), - ) as mock_logger: - _manager = CredentialManager(self.profile) + self.manager._logger, "exception", async_mock.MagicMock() + ) as mock_log_exception, async_mock.patch.object( + self.manager._logger, "warning", async_mock.MagicMock() + ) as mock_log_warning: mock_delete_ex.side_effect = test_module.StorageError() - (exch, ack) = await _manager.send_credential_ack(stored_exchange) + (exch, ack) = await self.manager.send_credential_ack(stored_exchange) assert ack._thread - mock_logger.assert_called_once() - assert ( - mock_logger_inst.exception.call_count == 1 - ) # cover exception log-and-continue - assert mock_logger_inst.warning.call_count == 1 # no BaseResponder + mock_log_exception.assert_called_once() # cover exception log-and-continue + mock_log_warning.assert_called_once() # no BaseResponder assert exch.state == V10CredentialExchange.STATE_ACKED mock_responder = MockResponder() # cover with responder self.context.injector.bind_instance(BaseResponder, mock_responder) - (exch, ack) = await _manager.send_credential_ack(stored_exchange) + (exch, ack) = await self.manager.send_credential_ack(stored_exchange) assert ack._thread assert exch.state == V10CredentialExchange.STATE_ACKED diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py index 33df21616e..ee56a933d9 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py @@ -5,9 +5,9 @@ from typing import Mapping, Tuple -from .....config.logging import get_logger_inst from .....core.error import BaseError from .....core.profile import Profile +from .....config.logging import get_adapted_logger_inst from .....messaging.decorators.attach_decorator import AttachDecorator from ..messages.cred_format import V20CredFormat @@ -17,6 +17,7 @@ from ..messages.cred_issue import V20CredIssue from ..models.cred_ex_record import V20CredExRecord +LOGGER = logging.getLogger(__name__) CredFormatAttachment = Tuple[V20CredFormat, AttachDecorator] @@ -34,9 +35,10 @@ def __init__(self, profile: Profile): super().__init__() self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py index 53914b1d6d..7912644363 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py @@ -1,8 +1,6 @@ """Credential ack message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -24,13 +22,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("V20CredAckHandler called with context %s", context) + self._logger.debug("V20CredAckHandler called with context %s", context) assert isinstance(context.message, V20CredAck) - _logger.info( + self._logger.info( "Received v2.0 credential ack message: %s", context.message.serialize(as_string=True), ) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py index 7b6a4dbb37..47de99eb69 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py @@ -1,8 +1,6 @@ """Credential issue message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError from .....messaging.base_handler import BaseHandler, HandlerException @@ -30,13 +28,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("V20CredIssueHandler called with context %s", context) + self._logger.debug("V20CredIssueHandler called with context %s", context) assert isinstance(context.message, V20CredIssue) - _logger.info( + self._logger.info( "Received v2.0 credential issue message: %s", context.message.serialize(as_string=True), ) @@ -81,7 +81,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): V20CredManagerError, ) as err: # treat failure to store as mangled on receipt hence protocol error - _logger.exception("Error storing issued credential") + self._logger.exception("Error storing issued credential") if cred_ex_record: async with context.profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py index 9d6d30c172..dcc4a0e965 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py @@ -1,8 +1,6 @@ """Credential offer message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....wallet.util import default_did_from_verkey from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError @@ -32,13 +30,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("V20CredOfferHandler called with context %s", context) + self._logger.debug("V20CredOfferHandler called with context %s", context) assert isinstance(context.message, V20CredOffer) - _logger.info( + self._logger.info( "Received v2.0 credential offer message: %s", context.message.serialize(as_string=True), ) @@ -64,7 +64,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): else None ) - profile = context.profile cred_manager = V20CredManager(profile) cred_ex_record = await cred_manager.receive_offer( context.message, connection_id @@ -99,7 +98,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, V20CredManagerError, ) as err: - _logger.exception("Error responding to credential offer") + self._logger.exception("Error responding to credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py index 400f42988c..b3078298ba 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py @@ -1,8 +1,6 @@ """Credential problem report message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -22,11 +20,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( "Issue-credential v2.0 problem report handler called with context %s", context, ) @@ -49,6 +49,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.connection_record.connection_id, ) except (StorageError, StorageNotFoundError): - _logger.exception( + self._logger.exception( "Error processing issue-credential v2.0 problem report message" ) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py index d1f55e4046..f95a562518 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py @@ -1,8 +1,6 @@ """Credential proposal message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -30,13 +28,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("V20CredProposalHandler called with context %s", context) + self._logger.debug("V20CredProposalHandler called with context %s", context) assert isinstance(context.message, V20CredProposal) - _logger.info( + self._logger.info( "Received v2.0 credential proposal message: %s", context.message.serialize(as_string=True), ) @@ -49,7 +49,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): "Connectionless not supported for credential proposal" ) - profile = context.profile cred_manager = V20CredManager(profile) cred_ex_record = await cred_manager.receive_proposal( context.message, context.connection_record.connection_id @@ -79,7 +78,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, V20CredManagerError, ) as err: - _logger.exception("Error responding to credential proposal") + self._logger.exception("Error responding to credential proposal") async with profile.session() as session: await cred_ex_record.save_error_state( session, diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py index 3fb43d54d9..4df7e55905 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py @@ -1,8 +1,6 @@ """Credential request message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError @@ -31,13 +29,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("V20CredRequestHandler called with context %s", context) + self._logger.debug("V20CredRequestHandler called with context %s", context) assert isinstance(context.message, V20CredRequest) - _logger.info( + self._logger.info( "Received v2.0 credential request message: %s", context.message.serialize(as_string=True), ) @@ -58,7 +58,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): " request" ) - profile = context.profile cred_manager = V20CredManager(profile) cred_ex_record = await cred_manager.receive_request( context.message, context.connection_record, oob_record @@ -90,7 +89,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, V20CredManagerError, ) as err: - _logger.exception(err) + self._logger.exception(err) async with profile.session() as session: await cred_ex_record.save_error_state( session, diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_ack_handler.py index f4283168fa..4712b9200b 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_ack_handler.py @@ -32,6 +32,12 @@ async def test_called(self): request_context.message = V20CredAck() request_context.connection_ready = True handler = test_module.V20CredAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -57,6 +63,12 @@ async def test_called_not_ready(self): request_context.message = V20CredAck() request_context.connection_ready = False handler = test_module.V20CredAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -80,6 +92,12 @@ async def test_called_no_connection_no_oob(self): request_context.message = V20CredAck() handler = test_module.V20CredAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py index 34409dff11..5a385563e4 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py @@ -112,19 +112,19 @@ async def test_called_auto_request_x(self): request_context.message = V20CredOffer() request_context.connection_ready = True handler = test_module.V20CredOfferHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: + ) as mock_send_reply: await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + assert handler._logger.exception.call_count == 1 async def test_called_not_ready(self): request_context = RequestContext.test_context() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_problem_report_handler.py index fa5195fce9..ebf70ad1fa 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_problem_report_handler.py @@ -29,6 +29,12 @@ async def test_called(self): } ) handler = test_module.CredProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -59,6 +65,12 @@ async def test_called_x(self): } ) handler = test_module.CredProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -81,6 +93,12 @@ async def test_called_not_ready(self): } ) handler = test_module.CredProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: @@ -102,6 +120,12 @@ async def test_called_no_connection(self): } ) handler = test_module.CredProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py index d9d7ae9acc..e8ac4b98d3 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py @@ -86,19 +86,19 @@ async def test_called_auto_offer_x(self): request_context.message = V20CredProposal() request_context.connection_ready = True handler = test_module.V20CredProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: + ) as mock_send_reply: await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + assert handler._logger.exception.call_count == 1 async def test_called_not_ready(self): request_context = RequestContext.test_context() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py index 80fc118bf0..9f815b59ea 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py @@ -37,6 +37,12 @@ async def test_called(self): request_context.message = V20CredRequest() request_context.connection_ready = True handler = test_module.V20CredRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -74,6 +80,12 @@ async def test_called_auto_issue(self): request_context.message = V20CredRequest() request_context.connection_ready = True handler = test_module.V20CredRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_cred_mgr.return_value.issue_credential.assert_called_once_with( @@ -121,19 +133,19 @@ async def test_called_auto_issue_x(self): request_context.message = V20CredRequest() request_context.connection_ready = True handler = test_module.V20CredRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: + ) as mock_send_reply: await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + assert handler._logger.exception.call_count == 1 async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -147,6 +159,12 @@ async def test_called_not_ready(self): request_context.message = V20CredRequest() request_context.connection_ready = False handler = test_module.V20CredRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -171,6 +189,12 @@ async def test_called_no_connection_no_oob(self): request_context.message = V20CredRequest() handler = test_module.V20CredRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/manager.py b/aries_cloudagent/protocols/issue_credential/v2_0/manager.py index ddcb0b0c9a..d699d66592 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/manager.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/manager.py @@ -4,8 +4,8 @@ from typing import Mapping, Optional, Tuple -from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord +from ....config.logging import get_adapted_logger_inst from ....core.oob_processor import OobRecord from ....core.error import BaseError from ....core.profile import Profile @@ -22,6 +22,8 @@ from .messages.inner.cred_preview import V20CredPreview from .models.cred_ex_record import V20CredExRecord +LOGGER = logging.getLogger(__name__) + class V20CredManagerError(BaseError): """Credential manager error under issue-credential protocol v2.0.""" @@ -37,9 +39,10 @@ def __init__(self, profile: Profile): profile: The profile instance for this credential manager """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py b/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py index 741d19e368..8fa2a8557a 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py @@ -5,7 +5,7 @@ from marshmallow import Schema, fields, validate -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.profile import ProfileSession from .....messaging.models.base_record import BaseExchangeRecord, BaseExchangeSchema from .....messaging.valid import UUID4_EXAMPLE @@ -19,6 +19,8 @@ from ..messages.inner.cred_preview import V20CredPreviewSchema from . import UNENCRYPTED_TAGS +LOGGER = logging.getLogger(__name__) + class V20CredExRecord(BaseExchangeRecord): """Represents an Aries#0036 credential exchange.""" @@ -161,9 +163,11 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - _logger: logging.Logger = get_logger_inst( - profile=session.profile, - logger_name=__name__, + profile = session.profile + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) if self._last_state == state: # already done return diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py b/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py index ff41602295..2a6c3efdd4 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py @@ -118,22 +118,23 @@ def test_serde(self): async def test_save_error_state(self): session = InMemoryProfile.test_session() + profile = session.profile + profile.settings["log.file"] = "test_file.log" + profile.settings["wallet.id"] = "test123" record = V20CredExRecord(state=None) assert record._last_state is None await record.save_error_state(session) # cover short circuit record.state = V20CredExRecord.STATE_PROPOSAL_RECEIVED await record.save(session) - + mock_logger = async_mock.MagicMock(exception=async_mock.MagicMock()) with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: + "get_adapted_logger_inst", + async_mock.MagicMock(return_value=mock_logger), + ): mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="test") - mock_log_exc.assert_called_once() + assert mock_logger.exception.call_count == 1 diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/routes.py b/aries_cloudagent/protocols/issue_credential/v2_0/routes.py index ca653106c7..2a63a366e9 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/routes.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/routes.py @@ -16,7 +16,7 @@ from marshmallow import ValidationError, fields, validate, validates_schema from ....admin.request_context import AdminRequestContext -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.profile import Profile from ....indy.holder import IndyHolderError @@ -55,6 +55,8 @@ from .models.detail.indy import V20CredExRecordIndySchema from .models.detail.ld_proof import V20CredExRecordLDProofSchema +LOGGER = logging.getLogger(__name__) + class V20IssueCredentialModuleResponseSchema(OpenAPISchema): """Response schema for v2.0 Issue Credential Module.""" @@ -679,9 +681,10 @@ async def credential_exchange_send(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) outbound_handler = request["outbound_message_router"] @@ -793,9 +796,10 @@ async def credential_exchange_send_proposal(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) outbound_handler = request["outbound_message_router"] @@ -929,9 +933,10 @@ async def credential_exchange_create_free_offer(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) body = await request.json() @@ -1002,9 +1007,10 @@ async def credential_exchange_send_free_offer(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) outbound_handler = request["outbound_message_router"] @@ -1100,9 +1106,10 @@ async def credential_exchange_send_bound_offer(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) outbound_handler = request["outbound_message_router"] @@ -1211,9 +1218,10 @@ async def credential_exchange_send_free_request(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) outbound_handler = request["outbound_message_router"] @@ -1315,9 +1323,10 @@ async def credential_exchange_send_bound_request(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) outbound_handler = request["outbound_message_router"] @@ -1437,9 +1446,10 @@ async def credential_exchange_issue(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) outbound_handler = request["outbound_message_router"] @@ -1534,9 +1544,10 @@ async def credential_exchange_store(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) outbound_handler = request["outbound_message_router"] diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py index 727f7d9d3a..0c76972f94 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py @@ -1280,29 +1280,33 @@ async def test_send_cred_ack(self): trace=False, auto_remove=True, ) - mock_logger_inst = async_mock.MagicMock( - exception=async_mock.MagicMock(), + mock_logger = async_mock.MagicMock( warning=async_mock.MagicMock(), + exception=async_mock.MagicMock(), ) + self.profile.settings["log.file"] = "test.log" + self.profile.settings["wallet.id"] = "test123" with async_mock.patch.object( V20CredExRecord, "save", autospec=True ) as mock_save_ex, async_mock.patch.object( V20CredExRecord, "delete_record", autospec=True ) as mock_delete_ex, async_mock.patch.object( test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=mock_logger_inst, - ), - ) as mock_logger: + "get_adapted_logger_inst", + async_mock.MagicMock(return_value=mock_logger), + ): mock_delete_ex.side_effect = test_module.StorageError() - (_, ack) = await self.manager.send_cred_ack(stored_exchange) + manager = V20CredManager(self.profile) + (_, ack) = await manager.send_cred_ack(stored_exchange) assert ack._thread - mock_logger_inst.exception.call_count == 1 # cover exception log-and-continue - mock_logger_inst.warning.call_count == 1 # no BaseResponder + assert ( + mock_logger.exception.call_count == 1 + ) # cover exception log-and-continue + assert mock_logger.warning.call_count == 1 # no BaseResponder + mock_responder = MockResponder() # cover with responder self.context.injector.bind_instance(BaseResponder, mock_responder) - (cx_rec, ack) = await self.manager.send_cred_ack(stored_exchange) + (cx_rec, ack) = await manager.send_cred_ack(stored_exchange) assert ack._thread assert cx_rec.state == V20CredExRecord.STATE_DONE diff --git a/aries_cloudagent/protocols/notification/v1_0/handlers/tests/test_ack_handler.py b/aries_cloudagent/protocols/notification/v1_0/handlers/tests/test_ack_handler.py index eb63e04b37..1c4f4fcb4a 100644 --- a/aries_cloudagent/protocols/notification/v1_0/handlers/tests/test_ack_handler.py +++ b/aries_cloudagent/protocols/notification/v1_0/handlers/tests/test_ack_handler.py @@ -17,5 +17,11 @@ async def test_called(self): request_context.message = V10Ack(status="OK") handler = test_module.V10AckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py index 7044cde893..cfb2da0309 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py @@ -1,8 +1,6 @@ """OOB Problem Report Message Handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -24,14 +22,17 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + f"OOBProblemReportMessageHandler called with context {context}" ) - _logger.debug(f"OOBProblemReportMessageHandler called with context {context}") assert isinstance(context.message, OOBProblemReport) - profile = context.profile mgr = OutOfBandManager(profile) try: await mgr.receive_problem_report( @@ -40,4 +41,4 @@ async def handle(self, context: RequestContext, responder: BaseResponder): conn_record=context.connection_record, ) except OutOfBandManagerError: - _logger.exception("Error processing OOB Problem Report message") + self._logger.exception("Error processing OOB Problem Report message") diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py index 34911efc7e..9e29ceec38 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py @@ -1,8 +1,6 @@ """Handshake Reuse Accepted Message Handler under RFC 0434.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -21,16 +19,17 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( f"HandshakeReuseAcceptMessageHandler called with context {context}" ) assert isinstance(context.message, HandshakeReuseAccept) - profile = context.profile mgr = OutOfBandManager(profile) try: await mgr.receive_reuse_accepted_message( @@ -39,4 +38,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): conn_record=context.connection_record, ) except OutOfBandManagerError as e: - _logger.exception(f"Error processing Handshake Reuse Accept message, {e}") + self._logger.exception( + f"Error processing Handshake Reuse Accept message, {e}" + ) diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py index a2889305cb..db558cd061 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py @@ -1,8 +1,6 @@ """Handshake Reuse Message Handler under RFC 0434.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -21,18 +19,21 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + f"HandshakeReuseMessageHandler called with context {context}" ) - _logger.debug(f"HandshakeReuseMessageHandler called with context {context}") assert isinstance(context.message, HandshakeReuse) - profile = context.profile mgr = OutOfBandManager(profile) try: await mgr.receive_reuse_message( context.message, context.message_receipt, context.connection_record ) except OutOfBandManagerError as e: - _logger.exception(f"Error processing Handshake Reuse message, {e}") + self._logger.exception(f"Error processing Handshake Reuse message, {e}") diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py index 594ef505db..240efa213c 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py @@ -13,8 +13,6 @@ from ...manager import OutOfBandManagerError from ...messages.problem_report import OOBProblemReport, ProblemReportReason -from .. import problem_report_handler as test_module - @pytest.fixture() async def request_context() -> RequestContext: @@ -48,6 +46,12 @@ async def test_called(self, mock_oob_mgr, request_context, connection_record): } ) handler = test_module.OOBProblemReportMessageHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(context=request_context, responder=responder) mock_oob_mgr.return_value.receive_problem_report.assert_called_once_with( @@ -70,14 +74,12 @@ async def test_exception(self, mock_oob_mgr, request_context, connection_record) } ) handler = test_module.OOBProblemReportMessageHandler() - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_exc_logger: - responder = MockResponder() - await handler.handle(context=request_context, responder=responder) - - assert mock_exc_logger.called_once() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) + responder = MockResponder() + await handler.handle(context=request_context, responder=responder) + assert handler._logger.exception.call_count == 1 diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py index f403a1ce17..147a9c901b 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py @@ -43,6 +43,12 @@ async def test_called(self, mock_oob_mgr, request_context, connection_record): ) request_context.message = HandshakeReuseAccept() handler = test_module.HandshakeReuseAcceptMessageHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(context=request_context, responder=responder) mock_oob_mgr.return_value.receive_reuse_accepted_message.assert_called_once_with( @@ -62,6 +68,12 @@ async def test_exception(self, mock_oob_mgr, request_context, connection_record) ) request_context.message = HandshakeReuseAccept() handler = test_module.HandshakeReuseAcceptMessageHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(context=request_context, responder=responder) assert mock_oob_mgr.return_value._logger.exception.called_once_("error") diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py index d4d94f546c..b130a5493d 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py @@ -34,6 +34,12 @@ async def test_called(self, mock_oob_mgr, request_context): mock_oob_mgr.return_value.receive_reuse_message = async_mock.CoroutineMock() request_context.message = HandshakeReuse() handler = test_module.HandshakeReuseMessageHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) request_context.connection_record = ConnRecord() responder = MockResponder() await handler.handle(request_context, responder) @@ -51,6 +57,12 @@ async def test_reuse_accepted(self, mock_oob_mgr, request_context): mock_oob_mgr.return_value.receive_reuse_message.return_value = reuse_accepted request_context.message = HandshakeReuse() handler = test_module.HandshakeReuseMessageHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) request_context.connection_record = ConnRecord() responder = MockResponder() await handler.handle(request_context, responder) @@ -69,6 +81,12 @@ async def test_exception(self, mock_oob_mgr, request_context): ) request_context.message = HandshakeReuse() handler = test_module.HandshakeReuseMessageHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) request_context.connection_record = ConnRecord() responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/manager.py b/aries_cloudagent/protocols/out_of_band/v1_0/manager.py index 9aa54c480c..b59cb6df8f 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/manager.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/manager.py @@ -7,11 +7,11 @@ import uuid from ....messaging.decorators.service_decorator import ServiceDecorator -from ....config.logging import get_logger_inst from ....core.event_bus import EventBus from ....core.util import get_version_from_message from ....connections.base_manager import BaseConnectionManager from ....connections.models.conn_record import ConnRecord +from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.oob_processor import OobMessageProcessor from ....core.profile import Profile @@ -40,6 +40,7 @@ from .messages.service import Service from .message_types import DEFAULT_VERSION +LOGGER = logging.getLogger(__name__) REUSE_WEBHOOK_TOPIC = "acapy::webhook::connection_reuse" REUSE_ACCEPTED_WEBHOOK_TOPIC = "acapy::webhook::connection_reuse_accepted" @@ -62,9 +63,10 @@ def __init__(self, profile: Profile): profile: The profile for this out of band manager """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) super().__init__(self._profile) diff --git a/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py b/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py index 0011cc7862..4a98d73fa7 100644 --- a/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py +++ b/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py @@ -21,9 +21,9 @@ from unflatten import unflatten from uuid import uuid4 -from ....config.logging import get_logger_inst from ....core.error import BaseError from ....core.profile import Profile +from ....config.logging import get_adapted_logger_inst from ....storage.vc_holder.vc_record import VCRecord from ....vc.ld_proofs import ( Ed25519Signature2018, @@ -59,6 +59,7 @@ PresentationSubmission, ) +LOGGER = logging.getLogger(__name__) PRESENTATION_SUBMISSION_JSONLD_CONTEXT = ( "https://identity.foundation/presentation-exchange/submission/v1" ) @@ -111,9 +112,10 @@ def __init__( self.proof_type = proof_type self.is_holder = False self.reveal_doc_frame = reveal_doc - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self.profile.settings.get("log.file"), + wallet_id=self.profile.settings.get("wallet.id"), ) async def _get_issue_suite( diff --git a/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py b/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py index 3170135e6d..c21fc57f0f 100644 --- a/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py +++ b/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py @@ -5,7 +5,7 @@ from typing import Union, Tuple -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....indy.holder import IndyHolder, IndyHolderError @@ -22,6 +22,8 @@ from ..v2_0.messages.pres_format import V20PresFormat from ..v2_0.models.pres_exchange import V20PresExRecord +LOGGER = logging.getLogger(__name__) + class IndyPresExchHandlerError(BaseError): """Base class for Indy Presentation Exchange related errors.""" @@ -37,9 +39,10 @@ def __init__( """Initialize PresExchange Handler.""" super().__init__() self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) async def return_presentation( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py index f8dc5868b5..cb08a48828 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py @@ -1,8 +1,6 @@ """Presentation ack message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -24,13 +22,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("PresentationAckHandler called with context %s", context) + self._logger.debug("PresentationAckHandler called with context %s", context) assert isinstance(context.message, PresentationAck) - _logger.info( + self._logger.info( "Received presentation ack message: %s", context.message.serialize(as_string=True), ) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py index b666ae3209..270c9b0b1b 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py @@ -1,8 +1,6 @@ """Presentation message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -30,14 +28,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, - ) profile = context.profile - _logger.debug("PresentationHandler called with context %s", context) + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug("PresentationHandler called with context %s", context) assert isinstance(context.message, Presentation) - _logger.info( + self._logger.info( "Received presentation message: %s", context.message.serialize(as_string=True), ) @@ -80,7 +79,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): presentation_exchange_record, responder ) except (BaseModelError, LedgerError, StorageError) as err: - _logger.exception(err) + self._logger.exception(err) if presentation_exchange_record: async with profile.session() as session: await presentation_exchange_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py index aeb5e91cec..b49651d8fc 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py @@ -1,8 +1,6 @@ """Presentation problem report message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -22,11 +20,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( "Present-proof v1.0 problem report handler called with context %s", context, ) @@ -49,6 +49,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.connection_record.connection_id, ) except (StorageError, StorageNotFoundError): - _logger.exception( + self._logger.exception( "Error processing present-proof v1.0 problem report message" ) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py index 19ac38fb94..c202c9dd70 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py @@ -1,8 +1,6 @@ """Presentation proposal message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.models.base import BaseModelError @@ -29,14 +27,17 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, - ) profile = context.profile - _logger.debug("PresentationProposalHandler called with context %s", context) + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) + self._logger.debug( + "PresentationProposalHandler called with context %s", context + ) assert isinstance(context.message, PresentationProposal) - _logger.info( + self._logger.info( "Received presentation proposal message: %s", context.message.serialize(as_string=True), ) @@ -76,7 +77,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): ) await responder.send_reply(presentation_request_message) except (BaseModelError, LedgerError, StorageError) as err: - _logger.exception(err) + self._logger.exception(err) if presentation_exchange_record: async with profile.session() as session: await presentation_exchange_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py index 4030d70098..f08fc385f7 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py @@ -1,8 +1,6 @@ """Presentation request message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolder, IndyHolderError from .....indy.models.xform import indy_proof_req_preview2indy_requested_creds @@ -34,15 +32,16 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, - ) profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), + ) - _logger.debug("PresentationRequestHandler called with context %s", context) + self._logger.debug("PresentationRequestHandler called with context %s", context) assert isinstance(context.message, PresentationRequest) - _logger.info( + self._logger.info( "Received presentation request message: %s", context.message.serialize(as_string=True), ) @@ -132,7 +131,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): holder=context.inject(IndyHolder), ) except ValueError as err: - _logger.warning(f"{err}") + self._logger.warning(f"{err}") return # not a protocol error: prover could still build proof manually presentation_message = None @@ -155,7 +154,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): StorageError, WalletNotFoundError, ) as err: - _logger.exception(err) + self._logger.exception(err) if presentation_exchange_record: async with profile.session() as session: await presentation_exchange_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_ack_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_ack_handler.py index db233adc17..ba0eee77fc 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_ack_handler.py @@ -33,6 +33,12 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -56,6 +62,12 @@ async def test_called_not_ready(self): request_context.message = PresentationAck() request_context.connection_ready = False handler = test_module.PresentationAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -77,6 +89,12 @@ async def test_called_no_connection_no_oob(self): request_context.message = PresentationAck() handler = test_module.PresentationAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py index 6253d2d141..0df8e8aef1 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py @@ -32,6 +32,12 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -63,6 +69,12 @@ async def test_called_auto_verify(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -103,14 +115,12 @@ async def test_called_auto_verify_x(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() - - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: - await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + await handler.handle(request_context, responder) + assert handler._logger.exception.call_count == 1 diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_problem_report_handler.py index a726dc349c..887e4630ea 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_problem_report_handler.py @@ -32,6 +32,12 @@ async def test_called(self): } ) handler = test_module.PresentationProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -62,6 +68,12 @@ async def test_called_x(self): } ) handler = test_module.PresentationProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py index 3144cb5945..773640d3d9 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py @@ -26,6 +26,12 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -58,6 +64,12 @@ async def test_called_auto_request(self): request_context.message = PresentationProposal() request_context.connection_ready = True handler = test_module.PresentationProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -97,17 +109,15 @@ async def test_called_auto_request_x(self): request_context.message = PresentationProposal() request_context.connection_ready = True handler = test_module.PresentationProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() - - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: - await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + await handler.handle(request_context, responder) + assert handler._logger.exception.call_count == 1 async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -121,6 +131,12 @@ async def test_called_not_ready(self): request_context.message = PresentationProposal() request_context.connection_ready = False handler = test_module.PresentationProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -137,6 +153,12 @@ async def test_called_no_connection(self): request_context.message = PresentationProposal() handler = test_module.PresentationProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py index d40bc9c1a4..658f551629 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py @@ -113,6 +113,12 @@ async def test_called(self): request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -174,6 +180,12 @@ async def test_called_not_found(self): request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -256,6 +268,12 @@ async def test_called_auto_present(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -347,17 +365,16 @@ async def test_called_auto_present_x(self): request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: - await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + await handler.handle(request_context, responder) + assert handler._logger.exception.call_count == 1 async def test_called_auto_present_no_preview(self): request_context = RequestContext.test_context() @@ -429,6 +446,12 @@ async def test_called_auto_present_no_preview(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -504,6 +527,12 @@ async def test_called_auto_present_pred_no_match(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_not_called() @@ -577,6 +606,12 @@ async def test_called_auto_present_pred_single_match(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -657,6 +692,12 @@ async def test_called_auto_present_pred_multi_match(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -788,6 +829,12 @@ async def test_called_auto_present_multi_cred_match_reft(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -901,6 +948,12 @@ async def test_called_auto_present_bait_and_switch(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -926,6 +979,12 @@ async def test_called_not_ready(self): request_context.message = PresentationRequest() request_context.connection_ready = False handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -950,6 +1009,12 @@ async def test_no_conn_no_oob(self): request_context.message = PresentationRequest() handler = test_module.PresentationRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/manager.py b/aries_cloudagent/protocols/present_proof/v1_0/manager.py index 7198fe6a0c..a58ea8787a 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/manager.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/manager.py @@ -4,8 +4,8 @@ import logging from typing import Optional -from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord +from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....indy.verifier import IndyVerifier @@ -28,6 +28,8 @@ from .message_types import ATTACH_DECO_IDS, PRESENTATION, PRESENTATION_REQUEST from .models.presentation_exchange import V10PresentationExchange +LOGGER = logging.getLogger(__name__) + class PresentationManagerError(BaseError): """Presentation error.""" @@ -44,9 +46,10 @@ def __init__(self, profile: Profile): """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) async def create_exchange_for_proposal( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py b/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py index 324a6e3bf3..6d3858c27b 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py @@ -5,7 +5,7 @@ from marshmallow import fields, validate -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.profile import ProfileSession from .....indy.models.proof import IndyProof, IndyProofSchema from .....indy.models.proof_request import IndyProofRequest, IndyProofRequestSchema @@ -23,6 +23,8 @@ from ..messages.presentation_webhook import V10PresentationExchangeWebhook from . import UNENCRYPTED_TAGS +LOGGER = logging.getLogger(__name__) + class V10PresentationExchange(BaseExchangeRecord): """Represents an Aries#0037 v1.0 presentation exchange.""" @@ -175,9 +177,11 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - _logger: logging.Logger = get_logger_inst( - profile=session.profile, - logger_name=__name__, + profile = session.profile + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) if self._last_state == state: # already done return diff --git a/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py b/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py index 8ca486bc11..0498a89a8e 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/models/tests/test_record.py @@ -132,11 +132,7 @@ async def test_save_error_state(self): with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), + test_module.LOGGER, "exception", async_mock.MagicMock() ) as mock_log_exc: mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="testing") diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py index 766a984b42..6adbbaa2cf 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py @@ -4,15 +4,16 @@ from typing import Tuple +from .....config.logging import get_adapted_logger_inst from .....core.error import BaseError from .....core.profile import Profile -from .....config.logging import get_logger_inst from .....messaging.decorators.attach_decorator import AttachDecorator from ..messages.pres import V20Pres from ..messages.pres_format import V20PresFormat from ..models.pres_exchange import V20PresExRecord +LOGGER = logging.getLogger(__name__) PresFormatAttachment = Tuple[V20PresFormat, AttachDecorator] @@ -29,9 +30,10 @@ def __init__(self, profile: Profile): """Initialize PresExchange Handler.""" super().__init__() self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) @property diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py index 79cd6522ec..ad71766dfc 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py @@ -1,8 +1,6 @@ """Presentation ack message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -24,13 +22,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("V20PresAckHandler called with context %s", context) + self._logger.debug("V20PresAckHandler called with context %s", context) assert isinstance(context.message, V20PresAck) - _logger.info( + self._logger.info( "Received v2.0 presentation ack message: %s", context.message.serialize(as_string=True), ) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py index 957587c1ef..2ee7682ae5 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py @@ -1,8 +1,6 @@ """Presentation message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -30,13 +28,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("V20PresHandler called with context %s", context) + self._logger.debug("V20PresHandler called with context %s", context) assert isinstance(context.message, V20Pres) - _logger.info( + self._logger.info( "Received presentation message: %s", context.message.serialize(as_string=True), ) @@ -77,7 +77,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): try: await pres_manager.verify_pres(pres_ex_record, responder) except (BaseModelError, LedgerError, StorageError) as err: - _logger.exception(err) + self._logger.exception(err) if pres_ex_record: async with context.profile.session() as session: await pres_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py index 5f8436cee8..2e2f150d5f 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py @@ -1,8 +1,6 @@ """Presentation problem report message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -22,11 +20,13 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( "Present-proof v2.0 problem report handler called with context %s", context, ) @@ -39,6 +39,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context.connection_record.connection_id, ) except (StorageError, StorageNotFoundError): - _logger.exception( + self._logger.exception( "Error processing present-proof v2.0 problem report message" ) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py index 328fa5a730..bdd2fa6f8b 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py @@ -1,8 +1,6 @@ """Presentation proposal message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.models.base import BaseModelError @@ -29,13 +27,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("V20PresProposalHandler called with context %s", context) + self._logger.debug("V20PresProposalHandler called with context %s", context) assert isinstance(context.message, V20PresProposal) - _logger.info( + self._logger.info( "Received v2.0 presentation proposal message: %s", context.message.serialize(as_string=True), ) @@ -50,7 +50,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): "Connection used for presentation proposal not ready" ) - profile = context.profile pres_manager = V20PresManager(profile) pres_ex_record = await pres_manager.receive_pres_proposal( context.message, context.connection_record @@ -76,7 +75,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): ) await responder.send_reply(pres_request_message) except (BaseModelError, LedgerError, StorageError) as err: - _logger.exception(err) + self._logger.exception(err) if pres_ex_record: async with profile.session() as session: await pres_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py index 4cec97aca9..22902a9c26 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py @@ -1,8 +1,6 @@ """Presentation request message handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError from .....ledger.error import LedgerError @@ -34,13 +32,15 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("V20PresRequestHandler called with context %s", context) + self._logger.debug("V20PresRequestHandler called with context %s", context) assert isinstance(context.message, V20PresRequest) - _logger.info( + self._logger.info( "Received v2.0 presentation request message: %s", context.message.serialize(as_string=True), ) @@ -66,7 +66,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): else None ) - profile = context.profile pres_manager = V20PresManager(profile) # Get pres ex record (holder initiated via proposal) @@ -128,7 +127,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): WalletNotFoundError, V20PresFormatHandlerError, ) as err: - _logger.exception(err) + self._logger.exception(err) if pres_ex_record: async with profile.session() as session: await pres_ex_record.save_error_state( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_ack_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_ack_handler.py index 928a2df6be..e246637fff 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_ack_handler.py @@ -31,6 +31,12 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -52,6 +58,12 @@ async def test_called_not_ready(self): request_context.message = V20PresAck() request_context.connection_ready = False handler = test_module.V20PresAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -73,6 +85,12 @@ async def test_called_no_connection_no_oob(self): request_context.message = V20PresAck() handler = test_module.V20PresAckHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py index 16bfb2e7ff..ed4a3eb201 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py @@ -32,6 +32,12 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -63,6 +69,12 @@ async def test_called_auto_verify(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -103,14 +115,12 @@ async def test_called_auto_verify_x(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() - - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: - await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + await handler.handle(request_context, responder) + assert handler._logger.exception.call_count == 1 diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_problem_report_handler.py index 170a826e14..ac42f98499 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_problem_report_handler.py @@ -28,6 +28,12 @@ async def test_called(self): } ) handler = test_module.V20PresProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -57,6 +63,12 @@ async def test_called_x(self): } ) handler = test_module.V20PresProblemReportHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py index 51649836cb..afaab2f3d6 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py @@ -26,6 +26,12 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -58,6 +64,12 @@ async def test_called_auto_request(self): request_context.message = V20PresProposal() request_context.connection_ready = True handler = test_module.V20PresProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -97,17 +109,15 @@ async def test_called_auto_request_x(self): request_context.message = V20PresProposal() request_context.connection_ready = True handler = test_module.V20PresProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() - - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: - await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + await handler.handle(request_context, responder) + assert handler._logger.exception.call_count == 1 async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -123,6 +133,12 @@ async def test_called_not_ready(self): request_context.message = V20PresProposal() request_context.connection_ready = False handler = test_module.V20PresProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -139,6 +155,12 @@ async def test_called_no_connection(self): request_context.message = V20PresProposal() handler = test_module.V20PresProposalHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py index cb2f8671e7..bc43f02860 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py @@ -228,6 +228,12 @@ async def test_called(self): request_context.connection_ready = True handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -288,6 +294,12 @@ async def test_called_not_found(self): request_context.connection_ready = True handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -360,17 +372,15 @@ async def test_called_auto_present_x(self): request_context.connection_ready = True handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() - - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: - await handler.handle(request_context, responder) - mock_log_exc.assert_called_once() + await handler.handle(request_context, responder) + assert handler._logger.exception.call_count == 1 async def test_called_auto_present_indy(self): request_context = RequestContext.test_context() @@ -433,6 +443,12 @@ async def test_called_auto_present_indy(self): request_context.connection_ready = True handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -576,6 +592,12 @@ async def test_called_auto_present_no_preview(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_pres.assert_called_once() @@ -650,6 +672,12 @@ async def test_called_auto_present_pred_no_match(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) @@ -714,6 +742,12 @@ async def test_called_auto_present_pred_single_match(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_pres.assert_called_once() @@ -785,6 +819,12 @@ async def test_called_auto_present_pred_multi_match(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_pres.assert_called_once() @@ -901,6 +941,12 @@ async def test_called_auto_present_multi_cred_match_reft(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_pres.assert_called_once() @@ -929,6 +975,12 @@ async def test_called_not_ready(self): request_context.message = V20PresRequest() request_context.connection_ready = False handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -953,6 +1005,12 @@ async def test_no_conn_no_oob(self): request_context.message = V20PresRequest() handler = test_module.V20PresRequestHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/manager.py b/aries_cloudagent/protocols/present_proof/v2_0/manager.py index 063a841460..43dafbbec4 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/manager.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/manager.py @@ -4,8 +4,8 @@ from typing import Optional, Tuple -from ....config.logging import get_logger_inst from ....connections.models.conn_record import ConnRecord +from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -20,6 +20,8 @@ from .messages.pres_request import V20PresRequest from .models.pres_exchange import V20PresExRecord +LOGGER = logging.getLogger(__name__) + class V20PresManagerError(BaseError): """Presentation error.""" @@ -36,9 +38,10 @@ def __init__(self, profile: Profile): """ self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) async def create_exchange_for_proposal( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py b/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py index 80c10a46f0..ae429f35a4 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py @@ -5,7 +5,7 @@ from marshmallow import Schema, fields, validate -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....core.profile import ProfileSession from .....messaging.models.base_record import BaseExchangeRecord, BaseExchangeSchema from .....messaging.valid import UUID4_EXAMPLE @@ -17,6 +17,8 @@ from ..messages.pres_webhook import V20PresExRecordWebhook from . import UNENCRYPTED_TAGS +LOGGER = logging.getLogger(__name__) + class V20PresExRecord(BaseExchangeRecord): """Represents a v2.0 presentation exchange.""" @@ -161,9 +163,11 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - _logger: logging.Logger = get_logger_inst( - profile=session.profile, - logger_name=__name__, + profile = session.profile + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) if self._last_state == state: # already done return diff --git a/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py b/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py index 809b1bb6bc..3d506447df 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py @@ -120,21 +120,21 @@ async def test_record(self): async def test_save_error_state(self): session = InMemoryProfile.test_session() record = V20PresExRecord(state=None) + profile = session.profile + profile.settings["log.file"] = "test_file.log" + profile.settings["wallet.id"] = "test123" assert record._last_state is None await record.save_error_state(session) # cover short circuit - record.state = V20PresExRecord.STATE_PROPOSAL_RECEIVED await record.save(session) - + mock_logger = async_mock.MagicMock(exception=async_mock.MagicMock()) with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(exception=async_mock.MagicMock()), - ), - ) as mock_log_exc: + "get_adapted_logger_inst", + async_mock.MagicMock(return_value=mock_logger), + ): mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="testing") - mock_log_exc.assert_called_once() + assert mock_logger.exception.call_count == 1 diff --git a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py index b017e1d858..1858dcadd2 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py @@ -27,7 +27,7 @@ from ...indy import pres_exch_handler as test_indy_util_module from .. import manager as test_module -from ..formats.handler import V20PresFormatHandlerError +from ..formats.handler import V20PresFormatHandler, V20PresFormatHandlerError from ..formats.dif.handler import DIFPresFormatHandler from ..formats.dif.tests.test_handler import ( DIF_PRES_REQUEST_B as DIF_PRES_REQ, @@ -1040,18 +1040,13 @@ async def test_create_pres_no_revocation(self): ) self.holder.create_presentation = async_mock.CoroutineMock(return_value="{}") self.profile.context.injector.bind_instance(IndyHolder, self.holder) - mock_logger = async_mock.MagicMock(info=async_mock.MagicMock()) with async_mock.patch.object( V20PresExRecord, "save", autospec=True ) as save_ex, async_mock.patch.object( test_indy_handler, "AttachDecorator", autospec=True ) as mock_attach_decorator, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=mock_logger, - ), - ): + test_indy_util_module.LOGGER, "info", async_mock.MagicMock() + ) as mock_log_info: mock_attach_decorator.data_base64 = async_mock.MagicMock( return_value=mock_attach_decorator ) @@ -1084,6 +1079,7 @@ async def test_create_pres_no_revocation(self): } } await self.manager.create_pres(px_rec_in, request_data) + mock_log_info.assert_called_once() async def test_create_pres_bad_revoc_state(self): pres_request = V20PresRequest( @@ -1147,11 +1143,7 @@ async def test_create_pres_bad_revoc_state(self): ) as mock_attach_decorator, async_mock.patch.object( test_indy_util_module, "RevocationRegistry", autospec=True ) as mock_rr, async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ), + self.manager._logger, "error", async_mock.MagicMock() ) as mock_log_error: mock_rr.from_definition = async_mock.MagicMock(return_value=more_magic_rr) diff --git a/aries_cloudagent/protocols/problem_report/v1_0/handler.py b/aries_cloudagent/protocols/problem_report/v1_0/handler.py index 0cded7bb1f..9949c5170c 100644 --- a/aries_cloudagent/protocols/problem_report/v1_0/handler.py +++ b/aries_cloudagent/protocols/problem_report/v1_0/handler.py @@ -1,8 +1,6 @@ """Generic problem report handler.""" -import logging - -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -23,14 +21,16 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: Responder used to reply """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("ProblemReportHandler called with context %s", context) + self._logger.debug("ProblemReportHandler called with context %s", context) assert isinstance(context.message, ProblemReport) - _logger.info( + self._logger.info( "Received problem report from: %s, %r", context.message_receipt.sender_did, context.message, diff --git a/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py b/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py index 91aed2c656..cf0e1733ec 100644 --- a/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py +++ b/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py @@ -1,8 +1,6 @@ """Handler for revoke message.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,11 +17,13 @@ class RevokeHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle revoke message.""" assert isinstance(context.message, Revoke) - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( "Received notification of revocation for cred issued in thread %s " "with comment: %s", context.message.thread_id, diff --git a/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py b/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py index fa194271f8..f3a2d820d2 100644 --- a/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py +++ b/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py @@ -2,7 +2,7 @@ import logging import re -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....core.event_bus import Event, EventBus from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -14,6 +14,8 @@ from ....storage.error import StorageError, StorageNotFoundError from .models.rev_notification_record import RevNotificationRecord +LOGGER = logging.getLogger(__name__) + def register_events(event_bus: EventBus): """Register to handle events.""" @@ -29,9 +31,10 @@ def register_events(event_bus: EventBus): async def on_revocation_published(profile: Profile, event: Event): """Handle issuer revoke event.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.debug("Sending notification of revocation to recipient: %s", event.payload) diff --git a/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py b/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py index c953a1ca6a..188530affd 100644 --- a/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py +++ b/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py @@ -1,8 +1,6 @@ """Handler for revoke message.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,11 +17,13 @@ class RevokeHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle revoke message.""" assert isinstance(context.message, Revoke) - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug( + self._logger.debug( "Received notification of revocation for %s cred %s with comment: %s", context.message.revocation_format, context.message.credential_id, diff --git a/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py b/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py index cc05851c9d..7604528e7c 100644 --- a/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py +++ b/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py @@ -2,7 +2,7 @@ import logging import re -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....core.event_bus import Event, EventBus from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -14,6 +14,8 @@ from ....storage.error import StorageError, StorageNotFoundError from .models.rev_notification_record import RevNotificationRecord +LOGGER = logging.getLogger(__name__) + def register_events(event_bus: EventBus): """Register to handle events.""" @@ -29,9 +31,10 @@ def register_events(event_bus: EventBus): async def on_revocation_published(profile: Profile, event: Event): """Handle issuer revoke event.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) _logger.debug("Sending notification of revocation to recipient: %s", event.payload) diff --git a/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py b/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py index 5a1fa431c3..91852a3369 100644 --- a/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py +++ b/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py @@ -1,9 +1,8 @@ """Handler for incoming forward messages.""" -import logging import json -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -20,16 +19,18 @@ class ForwardHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("ForwardHandler called with context %s", context) + self._logger.debug("ForwardHandler called with context %s", context) assert isinstance(context.message, Forward) if not context.message_receipt.recipient_verkey: raise HandlerException("Cannot forward message: unknown recipient") - _logger.info( + self._logger.info( "Received forward for: %s", context.message_receipt.recipient_verkey ) @@ -41,7 +42,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): try: recipient = await rt_mgr.get_recipient(target) except RoutingManagerError: - _logger.exception("Error resolving recipient for forwarded message") + self._logger.exception("Error resolving recipient for forwarded message") return # load connection @@ -53,7 +54,9 @@ async def handle(self, context: RequestContext, responder: BaseResponder): connection_verkey = connection_targets[0].recipient_keys[0] # Note: not currently vetting the state of the connection here - _logger.info(f"Forwarding message to connection: {recipient.connection_id}") + self._logger.info( + f"Forwarding message to connection: {recipient.connection_id}" + ) send_status = await responder.send( packed, diff --git a/aries_cloudagent/protocols/routing/v1_0/handlers/tests/test_forward_handler.py b/aries_cloudagent/protocols/routing/v1_0/handlers/tests/test_forward_handler.py index 03e3b2993e..5010773668 100644 --- a/aries_cloudagent/protocols/routing/v1_0/handlers/tests/test_forward_handler.py +++ b/aries_cloudagent/protocols/routing/v1_0/handlers/tests/test_forward_handler.py @@ -27,7 +27,12 @@ async def setUp(self): async def test_handle(self): self.context.message_receipt = MessageReceipt(recipient_verkey=TEST_VERKEY) handler = test_module.ForwardHandler() - + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( test_module, "RoutingManager", autospec=True @@ -69,13 +74,24 @@ async def test_handle(self): async def test_handle_receipt_no_recipient_verkey(self): self.context.message_receipt = MessageReceipt() handler = test_module.ForwardHandler() + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) with self.assertRaises(HandlerException): await handler.handle(self.context, None) async def test_handle_cannot_resolve_recipient(self): self.context.message_receipt = MessageReceipt(recipient_verkey=TEST_VERKEY) handler = test_module.ForwardHandler() - + handler._logger = async_mock.MagicMock( + error=async_mock.MagicMock(), + info=async_mock.MagicMock(), + warning=async_mock.MagicMock(), + debug=async_mock.MagicMock(), + ) responder = MockResponder() with async_mock.patch.object( test_module, "RoutingManager", autospec=True diff --git a/aries_cloudagent/protocols/routing/v1_0/manager.py b/aries_cloudagent/protocols/routing/v1_0/manager.py index fd4aaf5dc3..cafa757e87 100644 --- a/aries_cloudagent/protocols/routing/v1_0/manager.py +++ b/aries_cloudagent/protocols/routing/v1_0/manager.py @@ -4,7 +4,7 @@ import logging from typing import Sequence -from ....config.logging import get_logger_inst +from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....storage.error import ( @@ -14,7 +14,7 @@ from .models.route_record import RouteRecord - +LOGGER = logging.getLogger(__name__) RECIP_ROUTE_PAUSE = 0.1 RECIP_ROUTE_RETRY = 10 @@ -41,9 +41,10 @@ def __init__(self, profile: Profile): self._profile = profile if not profile: raise RoutingManagerError("Missing profile") - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) async def get_recipient(self, recip_verkey: str) -> RouteRecord: diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py index 9253ef874a..0828c8bb2a 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py @@ -1,8 +1,6 @@ """Ping handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -24,17 +22,21 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: Responder used to reply """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug(f"PingHandler called with context {context}") + self._logger.debug(f"PingHandler called with context {context}") assert isinstance(context.message, Ping) - _logger.info("Received trust ping from: %s", context.message_receipt.sender_did) + self._logger.info( + "Received trust ping from: %s", context.message_receipt.sender_did + ) if not context.connection_ready: - _logger.info( + self._logger.info( "Connection not active, skipping ping response: %s", context.message_receipt.sender_did, ) diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py index 9a1e0d1806..e002c08ca8 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py @@ -1,8 +1,6 @@ """Ping response handler.""" -import logging - -from .....config.logging import get_logger_inst +from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -23,14 +21,16 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: Responder used to reply """ - _logger: logging.Logger = get_logger_inst( - profile=context.profile, - logger_name=__name__, + profile = context.profile + self._logger = get_adapted_logger_inst( + logger=self._logger, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) - _logger.debug("PingResponseHandler called with context: %s", context) + self._logger.debug("PingResponseHandler called with context: %s", context) assert isinstance(context.message, PingResponse) - _logger.info( + self._logger.info( "Received trust ping response from: %s", context.message_receipt.sender_did ) diff --git a/aries_cloudagent/resolver/default/tests/test_universal.py b/aries_cloudagent/resolver/default/tests/test_universal.py index 51bdde6f9f..96e5d0827f 100644 --- a/aries_cloudagent/resolver/default/tests/test_universal.py +++ b/aries_cloudagent/resolver/default/tests/test_universal.py @@ -17,19 +17,9 @@ @pytest.fixture async def resolver(): """Resolver fixture.""" - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock( - debug=async_mock.MagicMock(), - ), - ), - ): - yield UniversalResolver( - endpoint="https://example.com", - supported_did_regex=re.compile("^did:sov:.*$"), - ) + yield UniversalResolver( + endpoint="https://example.com", supported_did_regex=re.compile("^did:sov:.*$") + ) @pytest.fixture diff --git a/aries_cloudagent/resolver/default/universal.py b/aries_cloudagent/resolver/default/universal.py index 63620afb42..19b77a8fba 100644 --- a/aries_cloudagent/resolver/default/universal.py +++ b/aries_cloudagent/resolver/default/universal.py @@ -7,11 +7,12 @@ import aiohttp from ...config.injection_context import InjectionContext -from ...config.logging import get_logger_inst +from ...config.logging import get_adapted_logger_inst from ...core.profile import Profile from ..base import BaseDIDResolver, DIDNotFound, ResolverError, ResolverType DEFAULT_ENDPOINT = "https://dev.uniresolver.io/1.0" +LOGGER = logging.getLogger(__name__) def _compile_supported_did_regex(patterns: Iterable[Union[str, Pattern]]): @@ -84,9 +85,10 @@ async def _resolve( service_accept: Optional[Sequence[Text]] = None, ) -> dict: """Resolve DID through remote universal resolver.""" - _logger: logging.Logger = get_logger_inst( - profile=_profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=_profile.settings.get("log.file"), + wallet_id=_profile.settings.get("wallet.id"), ) async with aiohttp.ClientSession(headers=self.__default_headers) as session: async with session.get(f"{self._endpoint}/identifiers/{did}") as resp: diff --git a/aries_cloudagent/resolver/did_resolver.py b/aries_cloudagent/resolver/did_resolver.py index 382ebaa348..a25576254c 100644 --- a/aries_cloudagent/resolver/did_resolver.py +++ b/aries_cloudagent/resolver/did_resolver.py @@ -115,11 +115,7 @@ async def _match_did_to_resolver( for resolver in self.resolvers if await resolver.supports(profile, did) ] - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, - ) - _logger.debug("Valid resolvers for DID %s: %s", did, valid_resolvers) + LOGGER.debug("Valid resolvers for DID %s: %s", did, valid_resolvers) native_resolvers = filter(lambda resolver: resolver.native, valid_resolvers) non_native_resolvers = filter( lambda resolver: not resolver.native, valid_resolvers diff --git a/aries_cloudagent/resolver/tests/test_did_resolver.py b/aries_cloudagent/resolver/tests/test_did_resolver.py index a1ffe8d8a3..a881c8b924 100644 --- a/aries_cloudagent/resolver/tests/test_did_resolver.py +++ b/aries_cloudagent/resolver/tests/test_did_resolver.py @@ -18,7 +18,6 @@ ResolverType, ) from ..did_resolver import DIDResolver -from .. import did_resolver as test_module from . import DOC @@ -90,20 +89,11 @@ async def _resolve(self, profile, did, accept): @pytest.fixture def resolver(): - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock( - debug=async_mock.MagicMock(), - ), - ), - ): - did_resolver_registry = [] - for method in TEST_DID_METHODS: - resolver = MockResolver([method], DIDDocument.deserialize(DOC)) - did_resolver_registry.append(resolver) - yield DIDResolver(did_resolver_registry) + did_resolver_registry = [] + for method in TEST_DID_METHODS: + resolver = MockResolver([method], DIDDocument.deserialize(DOC)) + did_resolver_registry.append(resolver) + return DIDResolver(did_resolver_registry) @pytest.fixture @@ -123,7 +113,7 @@ async def test_match_did_to_resolver(profile, resolver, did, method): @pytest.mark.asyncio -async def test_match_did_to_resolver_x_not_supported(resolver): +async def test_match_did_to_resolver_x_not_supported(profile, resolver): with pytest.raises(DIDMethodNotSupported): await resolver._match_did_to_resolver( profile, "did:cowsay:EiDahaOGH-liLLdDtTxEAdc8i-cfCz-WUcQdRJheMVNn3A" @@ -136,18 +126,9 @@ async def test_match_did_to_resolver_native_priority(profile): non_native = MockResolver(["sov"], native=False) registry = [non_native, native] resolver = DIDResolver(registry) - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock( - debug=async_mock.MagicMock(), - ), - ), - ): - assert [native, non_native] == await resolver._match_did_to_resolver( - profile, TEST_DID0 - ) + assert [native, non_native] == await resolver._match_did_to_resolver( + profile, TEST_DID0 + ) @pytest.mark.asyncio @@ -158,21 +139,12 @@ async def test_match_did_to_resolver_registration_order(profile): native4 = MockResolver(["sov"], native=True) registry = [native1, native2, non_native3, native4] resolver = DIDResolver(registry) - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock( - debug=async_mock.MagicMock(), - ), - ), - ): - assert [ - native1, - native2, - native4, - non_native3, - ] == await resolver._match_did_to_resolver(profile, TEST_DID0) + assert [ + native1, + native2, + native4, + non_native3, + ] == await resolver._match_did_to_resolver(profile, TEST_DID0) @pytest.mark.asyncio @@ -235,13 +207,5 @@ async def test_resolve_did_x_not_found(profile): py_did = DID("did:cowsay:EiDahaOGH-liLLdDtTxEAdc8i-cfCz-WUcQdRJheMVNn3A") cowsay_resolver_not_found = MockResolver(["cowsay"], resolved=DIDNotFound()) resolver = DIDResolver([cowsay_resolver_not_found]) - with async_mock.patch.object( - test_module, - "get_logger_inst", - async_mock.MagicMock( - return_value=async_mock.MagicMock( - debug=async_mock.MagicMock(), - ), - ), - ), pytest.raises(DIDNotFound): + with pytest.raises(DIDNotFound): await resolver.resolve(profile, py_did) diff --git a/aries_cloudagent/revocation/indy.py b/aries_cloudagent/revocation/indy.py index beb59d86f3..6b571ae3b9 100644 --- a/aries_cloudagent/revocation/indy.py +++ b/aries_cloudagent/revocation/indy.py @@ -3,7 +3,7 @@ from typing import Optional, Sequence, Tuple from uuid import uuid4 -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..core.profile import Profile from ..ledger.base import BaseLedger from ..ledger.multiple_ledger.ledger_requests_executor import ( @@ -28,6 +28,8 @@ from .models.revocation_registry import RevocationRegistry from .util import notify_revocation_reg_init_event +LOGGER = logging.getLogger(__name__) + class IndyRevocation: """Class for managing Indy credential revocation.""" @@ -37,9 +39,10 @@ class IndyRevocation: def __init__(self, profile: Profile): """Initialize the IndyRevocation instance.""" self._profile = profile - self._logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + self._logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=self._profile.settings.get("log.file"), + wallet_id=self._profile.settings.get("wallet.id"), ) async def init_issuer_registry( diff --git a/aries_cloudagent/revocation/models/issuer_rev_reg_record.py b/aries_cloudagent/revocation/models/issuer_rev_reg_record.py index e973d16b77..541e0daf49 100644 --- a/aries_cloudagent/revocation/models/issuer_rev_reg_record.py +++ b/aries_cloudagent/revocation/models/issuer_rev_reg_record.py @@ -12,7 +12,7 @@ from marshmallow import fields, validate -from ...config.logging import get_logger_inst +from ...config.logging import get_adapted_logger_inst from ...core.profile import Profile, ProfileSession from ...indy.issuer import IndyIssuer, IndyIssuerError from ...indy.models.revocation import ( @@ -43,6 +43,7 @@ from .revocation_registry import RevocationRegistry DEFAULT_REGISTRY_SIZE = 1000 +LOGGER = logging.getLogger(__name__) @total_ordering @@ -183,9 +184,10 @@ def _check_url(self, url) -> None: async def generate_registry(self, profile: Profile): """Create the revocation registry definition and tails file.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) if not self.tag: self.tag = self._id or str(uuid.uuid4()) @@ -288,9 +290,10 @@ async def send_entry( endorser_did: str = None, ) -> dict: """Send a registry entry to the ledger.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) if not ( self.revoc_reg_id @@ -371,9 +374,10 @@ async def fix_ledger_entry( ) -> Tuple[dict, dict, dict]: """Fix the ledger entry to match wallet-recorded credentials.""" # get rev reg delta (revocations published to ledger) - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) ledger = profile.inject(BaseLedger) async with ledger: diff --git a/aries_cloudagent/wallet/routes.py b/aries_cloudagent/wallet/routes.py index cc88c28cc3..2ca3a23306 100644 --- a/aries_cloudagent/wallet/routes.py +++ b/aries_cloudagent/wallet/routes.py @@ -10,7 +10,7 @@ from marshmallow import fields, validate from ..admin.request_context import AdminRequestContext -from ..config.logging import get_logger_inst +from ..config.logging import get_adapted_logger_inst from ..connections.models.conn_record import ConnRecord from ..core.event_bus import Event, EventBus from ..core.profile import Profile @@ -59,6 +59,8 @@ from .key_type import BLS12381G2, ED25519, KeyTypes from .util import EVENT_LISTENER_PATTERN +LOGGER = logging.getLogger(__name__) + class WalletModuleResponseSchema(OpenAPISchema): """Response schema for Wallet Module.""" @@ -1047,9 +1049,10 @@ def register_events(event_bus: EventBus): async def on_register_nym_event(profile: Profile, event: Event): """Handle any events we need to support.""" - _logger: logging.Logger = get_logger_inst( - profile=profile, - logger_name=__name__, + _logger = get_adapted_logger_inst( + logger=LOGGER, + log_file=profile.settings.get("log.file"), + wallet_id=profile.settings.get("wallet.id"), ) # after the nym record is written, promote to wallet public DID if is_author_role(profile) and profile.context.settings.get_value( From 9a6e9b74225a3cd02ffc3430c42254aa0f98bb2d Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Tue, 29 Aug 2023 15:31:33 +0530 Subject: [PATCH 09/18] update logging functions docstring Signed-off-by: Shaanjot Gill --- aries_cloudagent/config/logging.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index ba369977c8..cb673a6581 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -95,12 +95,18 @@ def configure_per_tenant( log_json_fmt: bool = False, ): """ - Configure logger. + Configure logger with time rotated file and stream log handlers. :param logging_config_path: str: (Default value = None) Optional path to custom logging config :param log_level: str: (Default value = None) + :param log_file: str: (Default value = None) + :param log_interval: int: (Default value = None) + :param log_bak_count: int: (Default value = None) + :param log_at_when: str: (Default value = None) + :param log_fmt_pattern: str: (Default value = None) + :param log_json_fmt: bool: (Default value = None) """ if logging_config_path is not None: config_path = logging_config_path @@ -551,7 +557,7 @@ def get_log_file_handlers( log_bak_count: int = None, log_at_when: str = None, ) -> Tuple[TimedRotatingFileMultiProcessHandler, logging.StreamHandler]: - """Get TimedRotatingFileMultiProcessHandler log handler.""" + """Get TimedRotatingFileMultiProcessHandler and StreamHandler.""" file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)).replace( "aries_cloudagent/config", "" @@ -573,7 +579,7 @@ def get_adapted_logger_inst( log_file: str = None, wallet_id: str = None, ) -> logging.Logger: - """Get adapted logger instance, if applicable.""" + """Get adapted logger, formatted with wallet_id if applicable.""" _logger = None if log_file and wallet_id: _logger = logging.LoggerAdapter(logger, {"wallet_id": wallet_id}) From 8e9b0f2e96eb6f125278eb8e610a4fa82c2e8747 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Fri, 8 Sep 2023 04:14:00 +0530 Subject: [PATCH 10/18] WIP - rework with contextvar Signed-off-by: Shaanjot Gill --- Logging.md | 2 + aries_cloudagent/config/argparse.py | 63 ------- .../default_per_tenant_logging_config.ini | 27 +++ .../default_per_tenant_logging_config.yml | 23 +++ aries_cloudagent/config/ledger.py | 17 +- aries_cloudagent/config/logging.py | 177 ++++++++---------- .../config/tests/test_argparse.py | 33 ---- aries_cloudagent/config/tests/test_logging.py | 58 +++--- aries_cloudagent/config/util.py | 25 +-- aries_cloudagent/connections/base_manager.py | 32 ++-- aries_cloudagent/core/event_bus.py | 18 +- aries_cloudagent/core/oob_processor.py | 44 ++--- aries_cloudagent/indy/credx/holder.py | 9 +- aries_cloudagent/indy/credx/issuer.py | 15 +- aries_cloudagent/indy/credx/verifier.py | 10 +- aries_cloudagent/indy/sdk/issuer.py | 16 +- aries_cloudagent/indy/sdk/verifier.py | 18 +- aries_cloudagent/indy/verifier.py | 20 +- aries_cloudagent/ledger/indy.py | 10 +- .../ledger/multiple_ledger/indy_manager.py | 15 +- .../multiple_ledger/indy_vdr_manager.py | 14 +- aries_cloudagent/ledger/routes.py | 15 +- aries_cloudagent/multitenant/base.py | 14 +- aries_cloudagent/multitenant/cache.py | 8 +- aries_cloudagent/multitenant/route_manager.py | 15 +- .../v1_0/handlers/menu_request_handler.py | 7 - .../v1_0/handlers/perform_handler.py | 7 - .../protocols/actionmenu/v1_0/routes.py | 22 +-- .../v1_0/handlers/basicmessage_handler.py | 7 - .../handlers/connection_request_handler.py | 11 +- .../handlers/connection_response_handler.py | 9 +- .../protocols/connections/v1_0/manager.py | 9 +- .../v1_0/handlers/keylist_handler.py | 15 +- .../v1_0/handlers/keylist_query_handler.py | 9 +- .../v1_0/handlers/keylist_update_handler.py | 9 +- .../keylist_update_response_handler.py | 12 -- .../v1_0/handlers/mediation_deny_handler.py | 9 +- .../v1_0/handlers/mediation_grant_handler.py | 9 +- .../handlers/mediation_request_handler.py | 7 - .../coordinate_mediation/v1_0/manager.py | 12 +- .../v1_0/route_manager.py | 16 +- .../v1_0/tests/test_mediation_manager.py | 65 +++---- .../v1_0/handlers/complete_handler.py | 9 +- .../v1_0/handlers/request_handler.py | 11 +- .../v1_0/handlers/response_handler.py | 10 +- .../protocols/didexchange/v1_0/manager.py | 9 +- .../v1_0/handlers/disclose_handler.py | 8 +- .../discovery/v1_0/handlers/query_handler.py | 8 +- .../protocols/discovery/v1_0/manager.py | 9 +- .../v2_0/handlers/disclosures_handler.py | 8 +- .../v2_0/handlers/queries_handler.py | 8 +- .../protocols/discovery/v2_0/manager.py | 9 +- .../endorsed_transaction_response_handler.py | 8 +- .../refused_transaction_response_handler.py | 8 +- .../transaction_acknowledgement_handler.py | 8 +- .../handlers/transaction_cancel_handler.py | 8 +- .../transaction_job_to_send_handler.py | 8 +- .../handlers/transaction_request_handler.py | 8 +- .../handlers/transaction_resend_handler.py | 8 +- .../endorse_transaction/v1_0/routes.py | 8 +- .../introduction/v0_1/demo_service.py | 12 +- .../handlers/forward_invitation_handler.py | 8 +- .../v0_1/handlers/invitation_handler.py | 8 - .../handlers/invitation_request_handler.py | 8 +- .../protocols/introduction/v0_1/routes.py | 9 +- .../v1_0/handlers/credential_ack_handler.py | 8 +- .../v1_0/handlers/credential_issue_handler.py | 6 - .../v1_0/handlers/credential_offer_handler.py | 7 +- .../credential_problem_report_handler.py | 7 - .../handlers/credential_proposal_handler.py | 6 - .../handlers/credential_request_handler.py | 6 - .../issue_credential/v1_0/manager.py | 30 ++- .../v1_0/models/credential_exchange.py | 10 +- .../issue_credential/v2_0/formats/handler.py | 7 +- .../v2_0/handlers/cred_ack_handler.py | 8 +- .../v2_0/handlers/cred_issue_handler.py | 8 +- .../v2_0/handlers/cred_offer_handler.py | 9 +- .../handlers/cred_problem_report_handler.py | 7 - .../v2_0/handlers/cred_proposal_handler.py | 9 +- .../v2_0/handlers/cred_request_handler.py | 9 +- .../issue_credential/v2_0/manager.py | 10 +- .../v2_0/models/cred_ex_record.py | 10 +- .../v2_0/models/tests/test_cred_ex_record.py | 13 +- .../protocols/issue_credential/v2_0/routes.py | 65 +------ .../v2_0/tests/test_manager.py | 26 +-- .../v1_0/handlers/problem_report_handler.py | 8 +- .../v1_0/handlers/reuse_accept_handler.py | 8 +- .../v1_0/handlers/reuse_handler.py | 8 +- .../protocols/out_of_band/v1_0/manager.py | 41 ++-- .../present_proof/dif/pres_exch_handler.py | 16 +- .../present_proof/indy/pres_exch_handler.py | 10 +- .../v1_0/handlers/presentation_ack_handler.py | 8 +- .../v1_0/handlers/presentation_handler.py | 6 - .../presentation_problem_report_handler.py | 7 - .../handlers/presentation_proposal_handler.py | 6 - .../handlers/presentation_request_handler.py | 6 - .../protocols/present_proof/v1_0/manager.py | 14 +- .../v1_0/models/presentation_exchange.py | 10 +- .../present_proof/v2_0/formats/handler.py | 7 +- .../v2_0/handlers/pres_ack_handler.py | 8 +- .../v2_0/handlers/pres_handler.py | 8 +- .../handlers/pres_problem_report_handler.py | 7 - .../v2_0/handlers/pres_proposal_handler.py | 9 +- .../v2_0/handlers/pres_request_handler.py | 9 +- .../protocols/present_proof/v2_0/manager.py | 12 +- .../v2_0/models/pres_exchange.py | 10 +- .../v2_0/models/tests/test_record.py | 14 +- .../protocols/problem_report/v1_0/handler.py | 7 - .../v1_0/handlers/revoke_handler.py | 7 - .../revocation_notification/v1_0/routes.py | 12 +- .../v2_0/handlers/revoke_handler.py | 7 - .../revocation_notification/v2_0/routes.py | 12 +- .../routing/v1_0/handlers/forward_handler.py | 7 - .../protocols/routing/v1_0/manager.py | 28 +-- .../trustping/v1_0/handlers/ping_handler.py | 7 - .../v1_0/handlers/ping_response_handler.py | 8 +- .../resolver/default/universal.py | 11 +- aries_cloudagent/revocation/indy.py | 12 +- .../models/issuer_rev_reg_record.py | 41 ++-- aries_cloudagent/wallet/routes.py | 18 +- demo/runners/agent_container.py | 27 --- demo/runners/performance.py | 27 +-- demo/runners/support/agent.py | 14 -- demo/runners/support/utils.py | 6 +- 124 files changed, 479 insertions(+), 1396 deletions(-) create mode 100644 aries_cloudagent/config/default_per_tenant_logging_config.ini create mode 100644 aries_cloudagent/config/default_per_tenant_logging_config.yml diff --git a/Logging.md b/Logging.md index 66373e56df..7892409afc 100644 --- a/Logging.md +++ b/Logging.md @@ -12,6 +12,8 @@ Other log levels fall back to `WARNING`. * `--log-level` - The log level to log on std out. * `--log-file` - Path to a file to log to. + +## WIP - add config file details * `--log-handler-config` - Specifies `when`, `interval`, `backupCount` for the `TimedRotatingFileMultiProcessHandler`. These 3 attributes are passed as a `;` seperated string. For example, `when` of d (days), `interval` of 7 and `backupCount` of 1 will be passed as `D;7;1`. Note: `backupCount` of 0 will mean all backup log files will be retained and not deleted at all. More details about these attributes can be found [here](https://docs.python.org/3/library/logging.handlers.html#timedrotatingfilehandler). `TimedRotatingFileMultiProcessHandler` supports the ability to cleanup logs by time and mantain backup logs and a custom JSON formatter for logs. * `--log-fmt-pattern` - Specifies logging.Formatter pattern to override default patterns. * `--log-json-fmt` - Specifies whether to use JSON logging formatter or text logging formatter. Defaults to `False`. diff --git a/aries_cloudagent/config/argparse.py b/aries_cloudagent/config/argparse.py index ac38895254..143a521da6 100644 --- a/aries_cloudagent/config/argparse.py +++ b/aries_cloudagent/config/argparse.py @@ -1013,46 +1013,6 @@ def add_arguments(self, parser: ArgumentParser): "('debug', 'info', 'warning', 'error', 'critical')" ), ) - parser.add_argument( - "--log-handler-config", - dest="log_handler_config", - type=str, - metavar="", - default=None, - env_var="ACAPY_LOG_HANDLER_CONFIG", - help=( - "Specifies when, interval, backupCount for the " - "TimedRotatingFileHandler. These attributes are " - "passed as a ; seperated string. For example, " - "when of D (days), interval of 7 and backupCount " - "of 1 will be passed as 'D;7;1'. Note: " - "backupCount of 0 will mean all backup log files " - "will be retained and not deleted at all." - ), - ) - parser.add_argument( - "--log-fmt-pattern", - dest="log_fmt_pattern", - type=str, - metavar="", - default=None, - env_var="ACAPY_LOG_FMT_PATTERN", - help=( - "Specifies logging formatter pattern as string. Examples are included " - "in 'Logging.md'. For information regarding different attributes " - "supported in the pattern, please look at " - "https://docs.python.org/3/library/logging.html#logrecord-attributes." - ), - ) - parser.add_argument( - "--log-json-fmt", - action="store_true", - env_var="ACAPY_LOG_JSON_FMT", - help=( - "Specifies whether to use JSON logging formatter or " - "text logging formatter." - ), - ) def get_settings(self, args: Namespace) -> dict: """Extract logging settings.""" @@ -1063,29 +1023,6 @@ def get_settings(self, args: Namespace) -> dict: settings["log.file"] = args.log_file if args.log_level: settings["log.level"] = args.log_level - if args.log_handler_config: - try: - handler_config_attribs = (args.log_handler_config).split(";") - settings["log.handler_when"] = handler_config_attribs[0] - settings["log.handler_interval"] = int(handler_config_attribs[1]) - settings["log.handler_bakcount"] = int(handler_config_attribs[2]) - except IndexError: - raise ArgsParseError( - "With --log-handler-config, the provided argument must be " - "in 'when;interval;backupCount' format. Each of the 3 " - "attributes for TimedRotatingFileHandler must be specified." - ) - except ValueError: - raise ArgsParseError( - "With --log-handler-config, 'interval' and 'backupCount' " - "should be a number [int]" - ) - if args.log_fmt_pattern: - settings["log.fmt_pattern"] = args.log_fmt_pattern - if args.log_json_fmt: - settings["log.json_fmt"] = True - else: - settings["log.json_fmt"] = False return settings diff --git a/aries_cloudagent/config/default_per_tenant_logging_config.ini b/aries_cloudagent/config/default_per_tenant_logging_config.ini new file mode 100644 index 0000000000..8f207bb6a0 --- /dev/null +++ b/aries_cloudagent/config/default_per_tenant_logging_config.ini @@ -0,0 +1,27 @@ +[loggers] +keys=root + +[handlers] +keys=stream_handler, timed_file_handler + +[formatters] +keys=formatter + +[logger_root] +level=ERROR +handlers=stream_handler, timed_file_handler + +[handler_stream_handler] +class=StreamHandler +level=DEBUG +formatter=formatter +args=(sys.stderr,) + +[handler_timed_file_handler] +class=logging.handlers.TimedRotatingFileMultiProcessHandler +level=DEBUG +formatter=formatter +args=('acapy.log', 'd', 7, 1,) + +[formatter_formatter] +format=%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s \ No newline at end of file diff --git a/aries_cloudagent/config/default_per_tenant_logging_config.yml b/aries_cloudagent/config/default_per_tenant_logging_config.yml new file mode 100644 index 0000000000..3978766e48 --- /dev/null +++ b/aries_cloudagent/config/default_per_tenant_logging_config.yml @@ -0,0 +1,23 @@ +version: 1 +formatters: + default: + format: '%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s' +handlers: + console: + class: logging.StreamHandler + level: DEBUG + formatter: default + stream: ext://sys.stderr + rotating_file: + class: logging.handlers.TimedRotatingFileMultiProcessHandler + level: DEBUG + filename: 'acapy.log' + when: 'd' + interval: 7 + backupCount: 1 + formatter: default +root: + level: INFO + handlers: + - console + - rotating_file \ No newline at end of file diff --git a/aries_cloudagent/config/ledger.py b/aries_cloudagent/config/ledger.py index bce2985775..0007ecdba6 100644 --- a/aries_cloudagent/config/ledger.py +++ b/aries_cloudagent/config/ledger.py @@ -12,7 +12,6 @@ from prompt_toolkit.eventloop.defaults import use_asyncio_event_loop from prompt_toolkit.formatted_text import HTML -from ..config.logging import get_adapted_logger_inst from ..config.settings import Settings from ..core.profile import Profile from ..ledger.base import BaseLedger @@ -129,14 +128,9 @@ async def ledger_config( """Perform Indy ledger configuration.""" session = await profile.session() - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) ledger = session.inject_or(BaseLedger) if not ledger: - _logger.info("Ledger instance not provided") + LOGGER.info("Ledger instance not provided") return False async with ledger: @@ -257,11 +251,6 @@ async def accept_taa( mechanisms = taa_info["aml_record"]["aml"] mechanism = None - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) taa_acceptance_mechanism = profile.settings.get("ledger.taa_acceptance_mechanism") taa_acceptance_version = profile.settings.get("ledger.taa_acceptance_version") @@ -287,13 +276,13 @@ async def accept_taa( elif sys.stdout.isatty(): mechanism = await select_aml_tty(taa_info, provision) else: - _logger.warning( + LOGGER.warning( "Cannot accept TAA without interactive terminal or taa accept config" ) if not mechanism: return False - _logger.debug(f"Accepting the TAA using mechanism '{mechanism}'") + LOGGER.debug(f"Accepting the TAA using mechanism '{mechanism}'") await ledger.accept_txn_author_agreement(taa_info["taa_record"], mechanism) return True diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index cb673a6581..7dc6b9be96 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -1,16 +1,18 @@ """Utilities related to logging.""" +from contextvars import ContextVar from datetime import datetime, timedelta from io import TextIOWrapper import logging -from logging.config import fileConfig +from logging.config import fileConfig, dictConfig from logging.handlers import BaseRotatingHandler import os from random import randint import re import sys +import yaml import time as mod_time -from typing import Tuple, TextIO +from typing import TextIO import pkg_resources from portalocker import LOCK_EX, lock, unlock @@ -21,6 +23,7 @@ from .banner import Banner DEFAULT_LOGGING_CONFIG_PATH = "aries_cloudagent.config:default_logging_config.ini" +DEFAULT_PER_TENANT_LOGGING_CONFIG_PATH = "./aries_cloudagent/config/default_per_tenant_logging_config.yml" LOG_FORMAT_FILE_ALIAS_PATTERN = ( "%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s" ) @@ -28,6 +31,24 @@ "%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(message)s" ) +context_wallet_id: ContextVar[str] = ContextVar("context_wallet_id") + + +class ContextFilter(logging.Filter): + """Custom logging Filter to adapt logs with contextual wallet_id.""" + + def __init__(self): + super(ContextFilter, self).__init__() + + def filter(self, record): + try: + wallet_id = context_wallet_id.get() + record.wallet_id= wallet_id + return True + except LookupError: + record.wallet_id= None + return True + def load_resource(path: str, encoding: str = None) -> TextIO: """Open a resource file located in a python package or the local filesystem. @@ -58,6 +79,8 @@ def configure( cls, logging_config_path: str = None, log_level: str = None, + log_file: str = None, + multitenant: bool = False, ): """Configure logger. @@ -66,77 +89,70 @@ def configure( :param log_level: str: (Default value = None) """ + is_dict_config = False if logging_config_path is not None: config_path = logging_config_path else: config_path = DEFAULT_LOGGING_CONFIG_PATH - - log_config = load_resource(config_path, "utf-8") - if log_config: - with log_config: - fileConfig(log_config, disable_existing_loggers=False) + if ".yml" in config_path or ".yaml" in config_path: + is_dict_config = True + with open(config_path, "r") as stream: + log_config = yaml.safe_load(stream) else: - logging.basicConfig(level=logging.WARNING) - logging.root.warning(f"Logging config file not found: {config_path}") - if log_level: - log_level = log_level.upper() - logging.root.setLevel(log_level) - - @classmethod - def configure_per_tenant( - cls, - logging_config_path: str = None, - log_level: str = None, - log_file: str = None, - log_interval: int = None, - log_bak_count: int = None, - log_at_when: str = None, - log_fmt_pattern: str = None, - log_json_fmt: bool = False, - ): - """ - Configure logger with time rotated file and stream log handlers. - - :param logging_config_path: str: (Default value = None) Optional path to - custom logging config - - :param log_level: str: (Default value = None) - :param log_file: str: (Default value = None) - :param log_interval: int: (Default value = None) - :param log_bak_count: int: (Default value = None) - :param log_at_when: str: (Default value = None) - :param log_fmt_pattern: str: (Default value = None) - :param log_json_fmt: bool: (Default value = None) - """ - if logging_config_path is not None: - config_path = logging_config_path - else: - config_path = DEFAULT_LOGGING_CONFIG_PATH - - log_config = load_resource(config_path, "utf-8") + log_config = load_resource(config_path, "utf-8") if log_config: - with log_config: - fileConfig(log_config, disable_existing_loggers=False) + if is_dict_config: + dictConfig(log_config) + else: + with log_config: + fileConfig(log_config, disable_existing_loggers=False) else: logging.basicConfig(level=logging.WARNING) logging.root.warning(f"Logging config file not found: {config_path}") - if log_file: - logging.root.handlers.clear() - timed_file_handler, std_out_handler = get_log_file_handlers( - log_file, log_interval, log_bak_count, log_at_when - ) - file_handler_pattern = log_fmt_pattern - if not file_handler_pattern: - file_handler_pattern = LOG_FORMAT_FILE_ALIAS_PATTERN - if log_json_fmt: + if log_file and multitenant: + file_handler_set = False + handler_pattern = None + # Create context filter to adapt wallet_id in logger messages + _cf = ContextFilter() + for _handler in logging.root.handlers: + if isinstance(_handler, TimedRotatingFileMultiProcessHandler): + file_handler_set = True + handler_pattern = _handler.formatter._fmt + # Set Json formatter for rotated file handler which + # cannot be set with config file. By default this will + # be set up. + _handler.setFormatter( + jsonlogger.JsonFormatter(handler_pattern) + ) + # Add context filter to handlers + _handler.addFilter(_cf) + if not file_handler_set: + file_path = os.path.join( + os.path.dirname(os.path.realpath(__file__)).replace( + "aries_cloudagent/config", "" + ), + log_file, + ) + # If configuration is not provided within .ini or dict config file + # then by default the rotated file handler will have interval=7, + # when=d and backupCount=1 configuration + timed_file_handler = TimedRotatingFileMultiProcessHandler( + filename=file_path, + interval=7, + when="d", + backupCount=1, + ) + timed_file_handler.addFilter(_cf) + # By default this will be set up. timed_file_handler.setFormatter( - jsonlogger.JsonFormatter(file_handler_pattern) + jsonlogger.JsonFormatter(LOG_FORMAT_FILE_ALIAS_PATTERN) ) - else: - timed_file_handler.setFormatter(logging.Formatter(file_handler_pattern)) - std_out_handler.setFormatter(logging.Formatter(LOG_FORMAT_STREAM_PATTERN)) - logging.root.handlers.append(timed_file_handler) - logging.root.handlers.append(std_out_handler) + logging.root.handlers.append(timed_file_handler) + elif log_file and not multitenant: + # Don't go with rotated file handler when not in multitenant mode. + logging.root.handlers.append( + logging.FileHandler(log_file, encoding="utf-8") + ) if log_level: log_level = log_level.upper() logging.root.setLevel(log_level) @@ -550,39 +566,4 @@ def doRollover(self): self.stream = self._open() self.release() - -def get_log_file_handlers( - log_file_name: str, - log_interval: int = None, - log_bak_count: int = None, - log_at_when: str = None, -) -> Tuple[TimedRotatingFileMultiProcessHandler, logging.StreamHandler]: - """Get TimedRotatingFileMultiProcessHandler and StreamHandler.""" - file_path = os.path.join( - os.path.dirname(os.path.realpath(__file__)).replace( - "aries_cloudagent/config", "" - ), - log_file_name, - ) - timed_file_handler = TimedRotatingFileMultiProcessHandler( - filename=file_path, - interval=log_interval or 7, - when=log_at_when or "d", - backupCount=log_bak_count or 1, - ) - std_out_handler = logging.StreamHandler(sys.stdout) - return (timed_file_handler, std_out_handler) - - -def get_adapted_logger_inst( - logger: logging.Logger, - log_file: str = None, - wallet_id: str = None, -) -> logging.Logger: - """Get adapted logger, formatted with wallet_id if applicable.""" - _logger = None - if log_file and wallet_id: - _logger = logging.LoggerAdapter(logger, {"wallet_id": wallet_id}) - else: - _logger = logger - return _logger +logging.handlers.TimedRotatingFileMultiProcessHandler = TimedRotatingFileMultiProcessHandler diff --git a/aries_cloudagent/config/tests/test_argparse.py b/aries_cloudagent/config/tests/test_argparse.py index 32f9de4ebf..0c52c12ef7 100644 --- a/aries_cloudagent/config/tests/test_argparse.py +++ b/aries_cloudagent/config/tests/test_argparse.py @@ -332,10 +332,6 @@ async def test_logging(self): "test_file.log", "--log-level", "INFO", - "--log-handler-config", - "d;7;1", - "--log-fmt-pattern", - "%(asctime)s %(levelname)s %(filename)s %(lineno)d %(message)s", ] ) @@ -343,35 +339,6 @@ async def test_logging(self): assert settings.get("log.file") == "test_file.log" assert settings.get("log.level") == "INFO" - assert settings.get("log.handler_when") == "d" - assert settings.get("log.handler_interval") == 7 - assert settings.get("log.handler_bakcount") == 1 - assert ( - settings.get("log.fmt_pattern") - == "%(asctime)s %(levelname)s %(filename)s %(lineno)d %(message)s" - ) - assert not settings.get("log.json_fmt") - - result = parser.parse_args( - [ - "--log-file", - "test_file.log", - "--log-level", - "INFO", - "--log-handler-config", - "d;7;1", - "--log-json-fmt", - ] - ) - - settings = group.get_settings(result) - - assert settings.get("log.file") == "test_file.log" - assert settings.get("log.level") == "INFO" - assert settings.get("log.handler_when") == "d" - assert settings.get("log.handler_interval") == 7 - assert settings.get("log.handler_bakcount") == 1 - assert settings.get("log.json_fmt") async def test_error_raised_when_multitenancy_used_and_no_jwt_provided(self): """Test that error is raised if no jwt_secret is provided with multitenancy.""" diff --git a/aries_cloudagent/config/tests/test_logging.py b/aries_cloudagent/config/tests/test_logging.py index 53509fa260..ef81af1404 100644 --- a/aries_cloudagent/config/tests/test_logging.py +++ b/aries_cloudagent/config/tests/test_logging.py @@ -40,33 +40,13 @@ def test_configure_default_no_resource(self): test_module.LoggingConfigurator.configure() def test_configure_default_file(self): + log_file = NamedTemporaryFile() with async_mock.patch.object( test_module, "load_resource", async_mock.MagicMock() ) as mock_load: mock_load.return_value = None - test_module.LoggingConfigurator.configure(log_level="ERROR") - - def test_configure_per_tenant(self): - mock_log_handlers = ( - async_mock.MagicMock(setFormatter=async_mock.MagicMock()), - async_mock.MagicMock(setFormatter=async_mock.MagicMock()), - ) - with async_mock.patch.object( - test_module, "logging", autospec=True - ), async_mock.patch.object( - test_module, "load_resource", async_mock.MagicMock() - ) as mock_load, async_mock.patch.object( - test_module, - "get_log_file_handlers", - async_mock.MagicMock(return_value=mock_log_handlers), - ): - mock_load.return_value = None - test_module.LoggingConfigurator.configure_per_tenant( - log_level="ERROR", - log_file="test.log", - log_interval=1, - log_json_fmt=True, - log_at_when="m", + test_module.LoggingConfigurator.configure( + log_level="ERROR", log_file=log_file.name ) @async_mock.patch.object(test_module, "load_resource", autospec=True) @@ -119,14 +99,24 @@ def test_load_resource(self): ) as mock_res_stream: test_module.load_resource("abc:def", encoding=None) - def test_get_log_file_handlers(self): - with async_mock.patch.object( - test_module, "TimedRotatingFileMultiProcessHandler", async_mock.MagicMock() - ) as mock_file_handler, async_mock.patch.object( - test_module.logging, "StreamHandler", async_mock.MagicMock() - ) as mock_stream_handler: - ret_file_handler, ret_stream_handler = test_module.get_log_file_handlers( - "test.log", 1, 1, "m" - ) - assert ret_file_handler - assert ret_stream_handler + def test_get_logger_with_handlers(self): + profile = InMemoryProfile.test_profile() + profile.settings["log.file"] = "test_file.log" + logger = logging.getLogger(__name__) + logger = test_module.get_logger_with_handlers( + settings=profile.settings, + logger=logger, + at_when="m", + interval=1, + backup_count=1, + ) + assert logger + logger = test_module.get_logger_with_handlers( + settings=profile.settings, + logger=logger, + did_ident="tenant_did_123", + at_when="m", + interval=1, + backup_count=1, + ) + assert logger diff --git a/aries_cloudagent/config/util.py b/aries_cloudagent/config/util.py index 4d79a30497..00f9af8654 100644 --- a/aries_cloudagent/config/util.py +++ b/aries_cloudagent/config/util.py @@ -15,24 +15,13 @@ def common_config(settings: Mapping[str, Any]): log_config = settings.get("log.config") log_level = settings.get("log.level") or os.getenv("LOG_LEVEL") log_file = settings.get("log.file") - log_interval = settings.get("log.handler_interval") - log_bak_count = settings.get("log.handler_bakcount") - log_at_when = settings.get("log.handler_when") - log_fmt_pattern = settings.get("log.fmt_pattern") - log_json_fmt = settings.get("log.json_fmt") - if not log_file: - LoggingConfigurator.configure(log_config, log_level) - else: - LoggingConfigurator.configure_per_tenant( - log_config, - log_level, - log_file, - log_interval, - log_bak_count, - log_at_when, - log_fmt_pattern, - log_json_fmt, - ) + multitenant_enabled = settings.get("multitenant.enabled") or False + LoggingConfigurator.configure( + logging_config_path=log_config, + log_level=log_level, + log_file=log_file, + multitenant=multitenant_enabled, + ) class BoundedInt: diff --git a/aries_cloudagent/connections/base_manager.py b/aries_cloudagent/connections/base_manager.py index 5a4aa708da..247fa3e93d 100644 --- a/aries_cloudagent/connections/base_manager.py +++ b/aries_cloudagent/connections/base_manager.py @@ -20,7 +20,6 @@ ) from ..cache.base import BaseCache from ..config.base import InjectionError -from ..config.logging import get_adapted_logger_inst from ..core.error import BaseError from ..core.profile import Profile from ..did.did_key import DIDKey @@ -73,11 +72,6 @@ def __init__(self, profile: Profile): """ self._profile = profile self._route_manager = profile.inject(RouteManager) - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) async def create_did_document( self, @@ -228,7 +222,7 @@ async def add_key_for_did(self, did: str, key: str): except StorageNotFoundError: await storage.add_record(record) except StorageDuplicateError: - self._logger.warning( + LOGGER.warning( "Key already associated with DID: %s; this is likely caused by " "routing keys being erroneously stored in the past", key, @@ -358,10 +352,10 @@ async def resolve_connection_targets( their_label: Optional[str] = None, ) -> List[ConnectionTarget]: """Resolve connection targets for a DID.""" - self._logger.debug("Resolving connection targets for DID %s", did) + LOGGER.debug("Resolving connection targets for DID %s", did) doc, didcomm_services = await self.resolve_didcomm_services(did) - self._logger.debug("Resolved DID document: %s", doc) - self._logger.debug("Resolved DIDComm services: %s", didcomm_services) + LOGGER.debug("Resolved DID document: %s", doc) + LOGGER.debug("Resolved DIDComm services: %s", didcomm_services) targets = [] for service in didcomm_services: try: @@ -386,7 +380,7 @@ async def resolve_connection_targets( ) ) except ResolverError: - self._logger.exception( + LOGGER.exception( "Failed to resolve service details while determining " "connection targets; skipping service" ) @@ -547,7 +541,7 @@ async def fetch_connection_targets( """ if not connection.my_did: - self._logger.debug("No local DID associated with connection") + LOGGER.debug("No local DID associated with connection") return [] async with self._profile.session() as session: @@ -564,7 +558,7 @@ async def fetch_connection_targets( ) if not connection.their_did: - self._logger.debug("No target DID associated with connection") + LOGGER.debug("No target DID associated with connection") return [] return await self.resolve_connection_targets( @@ -595,7 +589,7 @@ async def get_connection_targets( if cache: async with cache.acquire(cache_key) as entry: if entry.result: - self._logger.debug("Connection targets retrieved from cache") + LOGGER.debug("Connection targets retrieved from cache") targets = [ ConnectionTarget.deserialize(row) for row in entry.result ] @@ -612,12 +606,12 @@ async def get_connection_targets( # Only set cache if connection has reached completed state # Otherwise, a replica that participated early in exchange # may have bad data set in cache. - self._logger.debug("Caching connection targets") + LOGGER.debug("Caching connection targets") await entry.set_result( [row.serialize() for row in targets], 3600 ) else: - self._logger.debug( + LOGGER.debug( "Not caching connection targets for connection in " f"state ({connection.state})" ) @@ -803,7 +797,7 @@ async def resolve_inbound_connection( try: receipt.sender_did = await self.find_did_for_key(receipt.sender_verkey) except StorageNotFoundError: - self._logger.warning( + LOGGER.warning( "No corresponding DID found for sender verkey: %s", receipt.sender_verkey, ) @@ -819,13 +813,13 @@ async def resolve_inbound_connection( if "posted" in my_info.metadata and my_info.metadata["posted"] is True: receipt.recipient_did_public = True except InjectionError: - self._logger.warning( + LOGGER.warning( "Cannot resolve recipient verkey, no wallet defined by " "context: %s", receipt.recipient_verkey, ) except WalletNotFoundError: - self._logger.warning( + LOGGER.warning( "No corresponding DID found for recipient verkey: %s", receipt.recipient_verkey, ) diff --git a/aries_cloudagent/core/event_bus.py b/aries_cloudagent/core/event_bus.py index 3d76252bb4..d314bb3c3f 100644 --- a/aries_cloudagent/core/event_bus.py +++ b/aries_cloudagent/core/event_bus.py @@ -19,8 +19,6 @@ ) from functools import partial -from ..config.logging import get_adapted_logger_inst - if TYPE_CHECKING: # To avoid circular import error from .profile import Profile @@ -99,12 +97,7 @@ async def notify(self, profile: "Profile", event: Event): # TODO don't block notifier until subscribers have all been called? # TODO trigger each processor but don't await? # TODO log errors but otherwise ignore? - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.debug("Notifying subscribers: %s", event) + LOGGER.debug("Notifying subscribers: %s", event) partials = [] for pattern, subscribers in self.topic_patterns_to_subscribers.items(): @@ -126,7 +119,7 @@ async def notify(self, profile: "Profile", event: Event): try: await processor() except Exception: - _logger.exception("Error occurred while processing event") + LOGGER.exception("Error occurred while processing event") def subscribe(self, pattern: Pattern, processor: Callable): """Subscribe to an event. @@ -174,12 +167,7 @@ def wait_for_event( async def _handle_single_event(profile, event): """Handle the single event.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.debug( + LOGGER.debug( "wait_for_event event listener with event %s and profile %s", event, profile, diff --git a/aries_cloudagent/core/oob_processor.py b/aries_cloudagent/core/oob_processor.py index 9d8b97b0f0..c7b29b16d9 100644 --- a/aries_cloudagent/core/oob_processor.py +++ b/aries_cloudagent/core/oob_processor.py @@ -5,7 +5,6 @@ from typing import Any, Callable, Dict, List, Optional, cast from ..messaging.agent_message import AgentMessage -from ..config.logging import get_adapted_logger_inst from ..connections.models.conn_record import ConnRecord from ..connections.models.connection_target import ConnectionTarget from ..messaging.decorators.service_decorator import ServiceDecorator @@ -72,11 +71,6 @@ async def find_oob_target_for_outbound_message( self, profile: Profile, outbound_message: OutboundMessage ) -> Optional[ConnectionTarget]: """Find connection target for the outbound message.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) try: async with profile.session() as session: # Try to find the oob record for the outbound message: @@ -84,7 +78,7 @@ async def find_oob_target_for_outbound_message( session, {"attach_thread_id": outbound_message.reply_thread_id} ) - _logger.debug( + LOGGER.debug( "extracting their service from oob record %s", oob_record.their_service, ) @@ -94,7 +88,7 @@ async def find_oob_target_for_outbound_message( # Attach ~service decorator so other message can respond message = json.loads(outbound_message.payload) if not message.get("~service"): - _logger.debug( + LOGGER.debug( "Setting our service on the message ~service %s", oob_record.our_service, ) @@ -107,7 +101,7 @@ async def find_oob_target_for_outbound_message( outbound_message.payload = json.dumps(message) - _logger.debug( + LOGGER.debug( "Sending oob message payload %s", outbound_message.payload ) @@ -127,16 +121,11 @@ async def find_oob_record_for_inbound_message( message_type = context.message._type oob_record = None profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) async with context.profile.session() as session: # First try to find the oob record based on the associated pthid if context.message_receipt.parent_thread_id: try: - _logger.debug( + LOGGER.debug( "Retrieving OOB record using pthid " f"{context.message_receipt.parent_thread_id} " f"for message type {message_type}" @@ -160,7 +149,7 @@ async def find_oob_record_for_inbound_message( and context.message_receipt.recipient_verkey ): try: - _logger.debug( + LOGGER.debug( "Retrieving OOB record using thid " f"{context.message_receipt.thread_id} and recipient verkey" f" {context.message_receipt.recipient_verkey} for " @@ -181,7 +170,7 @@ async def find_oob_record_for_inbound_message( if not oob_record: return None - _logger.debug( + LOGGER.debug( f"Found out of band record for inbound message with type {message_type}" f": {oob_record.oob_id}" ) @@ -197,14 +186,14 @@ async def find_oob_record_for_inbound_message( and context.connection_record and context.connection_record.connection_id != oob_record.connection_id ): - _logger.debug( + LOGGER.debug( f"Oob record connection id {oob_record.connection_id} is different from" f" inbound message connection {context.connection_record.connection_id}", ) # Mismatch in connection id's in only allowed in state await response # (connection id can change bc of reuse) if oob_record.state != OobRecord.STATE_AWAIT_RESPONSE: - _logger.debug( + LOGGER.debug( "Inbound message has incorrect connection_id " f"{context.connection_record.connection_id}. Oob record " f"{oob_record.oob_id} associated with connection id " @@ -219,7 +208,7 @@ async def find_oob_record_for_inbound_message( oob_record.invitation.requests_attach and oob_record.state == OobRecord.STATE_AWAIT_RESPONSE ): - _logger.debug( + LOGGER.debug( f"Removing stale connection {oob_record.connection_id} due " "to connection reuse" ) @@ -244,7 +233,7 @@ async def find_oob_record_for_inbound_message( ] if context.message_receipt.thread_id not in allowed_thread_ids: - _logger.debug( + LOGGER.debug( "Inbound message is for not allowed thread " f"{context.message_receipt.thread_id}. Allowed " f"threads are {allowed_thread_ids}" @@ -256,7 +245,7 @@ async def find_oob_record_for_inbound_message( oob_record.attach_thread_id and context.message_receipt.thread_id != oob_record.attach_thread_id ): - _logger.debug( + LOGGER.debug( f"Inbound message thread id {context.message_receipt.thread_id} does not" f" match oob record thread id {oob_record.attach_thread_id}" ) @@ -283,7 +272,7 @@ async def find_oob_record_for_inbound_message( ) ) ): - _logger.debug( + LOGGER.debug( "Inbound message sender verkey does not match stored service on oob" " record" ) @@ -292,7 +281,7 @@ async def find_oob_record_for_inbound_message( # If the message has a ~service decorator we save it in the oob record so we # can reply to this message if context._message._service: - _logger.debug( + LOGGER.debug( "Storing service decorator in oob record %s", context.message._service.serialize(), ) @@ -320,11 +309,6 @@ async def handle_message( their_service: Optional[ServiceDecorator] = None, ): """Message handler for inbound messages.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) supported_types = [ CREDENTIAL_OFFER, @@ -365,7 +349,7 @@ async def handle_message( if not oob_record.connection_id: oob_record.attach_thread_id = self.get_thread_id(message) if their_service: - _logger.debug( + LOGGER.debug( "Storing their service in oob record %s", their_service ) oob_record.their_service = their_service.serialize() diff --git a/aries_cloudagent/indy/credx/holder.py b/aries_cloudagent/indy/credx/holder.py index fa16598304..d593838319 100644 --- a/aries_cloudagent/indy/credx/holder.py +++ b/aries_cloudagent/indy/credx/holder.py @@ -20,13 +20,13 @@ ) from ...askar.profile import AskarProfile -from ...config.logging import get_adapted_logger_inst from ...ledger.base import BaseLedger from ...wallet.error import WalletNotFoundError from ..holder import IndyHolder, IndyHolderError LOGGER = logging.getLogger(__name__) + CATEGORY_CREDENTIAL = "credential" CATEGORY_LINK_SECRET = "master_secret" @@ -61,11 +61,6 @@ def __init__(self, profile: AskarProfile): """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) @property def profile(self) -> AskarProfile: @@ -143,7 +138,7 @@ async def create_credential_request( cred_req_metadata.to_json(), ) - self._logger.debug( + LOGGER.debug( "Created credential request. " "credential_request_json=%s credential_request_metadata_json=%s", cred_req_json, diff --git a/aries_cloudagent/indy/credx/issuer.py b/aries_cloudagent/indy/credx/issuer.py index a383425bc1..6150d9d9ca 100644 --- a/aries_cloudagent/indy/credx/issuer.py +++ b/aries_cloudagent/indy/credx/issuer.py @@ -21,7 +21,6 @@ ) from ...askar.profile import AskarProfile -from ...config.logging import get_adapted_logger_inst from ..issuer import ( IndyIssuer, @@ -32,6 +31,7 @@ ) LOGGER = logging.getLogger(__name__) + CATEGORY_CRED_DEF = "credential_def" CATEGORY_CRED_DEF_PRIVATE = "credential_def_private" CATEGORY_CRED_DEF_KEY_PROOF = "credential_def_key_proof" @@ -54,11 +54,6 @@ def __init__(self, profile: AskarProfile): """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) @property def profile(self) -> AskarProfile: @@ -453,7 +448,7 @@ async def revoke_credentials( for rev_id in cred_revoc_ids: rev_id = int(rev_id) if rev_id < 1 or rev_id > max_cred_num: - self._logger.error( + LOGGER.error( "Skipping requested credential revocation" "on rev reg id %s, cred rev id=%s not in range", revoc_reg_id, @@ -461,7 +456,7 @@ async def revoke_credentials( ) failed_crids.add(rev_id) elif rev_id > rev_info["curr_id"]: - self._logger.warn( + LOGGER.warn( "Skipping requested credential revocation" "on rev reg id %s, cred rev id=%s not yet issued", revoc_reg_id, @@ -469,7 +464,7 @@ async def revoke_credentials( ) failed_crids.add(rev_id) elif rev_id in used_ids: - self._logger.warn( + LOGGER.warn( "Skipping requested credential revocation" "on rev reg id %s, cred rev id=%s already revoked", revoc_reg_id, @@ -505,7 +500,7 @@ async def revoke_credentials( CATEGORY_REV_REG_INFO, revoc_reg_id, for_update=True ) if not rev_reg_upd or not rev_reg_info: - self._logger.warn( + LOGGER.warn( "Revocation registry missing, skipping update: {}", revoc_reg_id, ) diff --git a/aries_cloudagent/indy/credx/verifier.py b/aries_cloudagent/indy/credx/verifier.py index a641096b31..0911009144 100644 --- a/aries_cloudagent/indy/credx/verifier.py +++ b/aries_cloudagent/indy/credx/verifier.py @@ -8,7 +8,6 @@ from indy_credx import CredxError, Presentation from ...core.profile import Profile -from ...config.logging import get_adapted_logger_inst from ..verifier import IndyVerifier, PresVerifyMsg @@ -26,11 +25,6 @@ def __init__(self, profile: Profile): """ self.profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self.profile.settings.get("log.file"), - wallet_id=self.profile.settings.get("wallet.id"), - ) async def verify_presentation( self, @@ -66,7 +60,7 @@ async def verify_presentation( except ValueError as err: s = str(err) msgs.append(f"{PresVerifyMsg.PRES_VALUE_ERROR.value}::{s}") - self._logger.error( + LOGGER.error( f"Presentation on nonce={pres_req['nonce']} " f"cannot be validated: {str(err)}" ) @@ -87,7 +81,7 @@ async def verify_presentation( except CredxError as err: s = str(err) msgs.append(f"{PresVerifyMsg.PRES_VERIFY_ERROR.value}::{s}") - self._logger.exception( + LOGGER.exception( f"Validation of presentation on nonce={pres_req['nonce']} " "failed with error" ) diff --git a/aries_cloudagent/indy/sdk/issuer.py b/aries_cloudagent/indy/sdk/issuer.py index 56891cbc4f..8ac62b8637 100644 --- a/aries_cloudagent/indy/sdk/issuer.py +++ b/aries_cloudagent/indy/sdk/issuer.py @@ -8,7 +8,6 @@ import indy.blob_storage from indy.error import AnoncredsRevocationRegistryFullError, IndyError, ErrorCode -from ...config.logging import get_adapted_logger_inst from ...indy.sdk.profile import IndySdkProfile from ...messaging.util import encode from ...storage.error import StorageError @@ -38,11 +37,6 @@ def __init__(self, profile: IndySdkProfile): """ self.profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self.profile.settings.get("log.file"), - wallet_id=self.profile.settings.get("wallet.id"), - ) async def create_schema( self, @@ -217,7 +211,7 @@ async def create_credential( tails_reader_handle, ) except AnoncredsRevocationRegistryFullError: - self._logger.warning( + LOGGER.warning( "Revocation registry %s is full: cannot create credential", rev_reg_id, ) @@ -229,7 +223,7 @@ async def create_credential( err, "Error when issuing credential", IndyIssuerError ) from err except StorageError as err: - self._logger.warning( + LOGGER.warning( ( "Created issuer cred rev record for " "Could not store issuer cred rev record for " @@ -278,7 +272,7 @@ async def revoke_credentials( ) except IndyError as err: if err.error_code == ErrorCode.AnoncredsInvalidUserRevocId: - self._logger.error( + LOGGER.error( ( "Abstaining from revoking credential on " "rev reg id %s, cred rev id=%s: " @@ -288,7 +282,7 @@ async def revoke_credentials( cred_rev_id, ) else: - self._logger.error( + LOGGER.error( IndyErrorHandler.wrap_error( err, "Revocation error", IndyIssuerError ).roll_up @@ -296,7 +290,7 @@ async def revoke_credentials( failed_crids.add(int(cred_rev_id)) continue except StorageError as err: - self._logger.warning( + LOGGER.warning( ( "Revoked credential on rev reg id %s, cred rev id %s " "without corresponding issuer cred rev record: %s" diff --git a/aries_cloudagent/indy/sdk/verifier.py b/aries_cloudagent/indy/sdk/verifier.py index 59c3815f43..81bdc5a601 100644 --- a/aries_cloudagent/indy/sdk/verifier.py +++ b/aries_cloudagent/indy/sdk/verifier.py @@ -9,7 +9,6 @@ from indy.error import IndyError from ...core.profile import Profile -from ...config.logging import get_adapted_logger_inst from ..verifier import IndyVerifier, PresVerifyMsg @@ -27,11 +26,6 @@ def __init__(self, profile: Profile): """ self.profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self.profile.settings.get("log.file"), - wallet_id=self.profile.settings.get("wallet.id"), - ) async def verify_presentation( self, @@ -53,8 +47,8 @@ async def verify_presentation( rev_reg_entries: revocation registry entries """ - self._logger.debug(f">>> received presentation: {pres}") - self._logger.debug(f">>> for pres_req: {pres_req}") + LOGGER.debug(f">>> received presentation: {pres}") + LOGGER.debug(f">>> for pres_req: {pres_req}") msgs = [] try: msgs += self.non_revoc_intervals(pres_req, pres, credential_definitions) @@ -65,14 +59,14 @@ async def verify_presentation( except ValueError as err: s = str(err) msgs.append(f"{PresVerifyMsg.PRES_VALUE_ERROR.value}::{s}") - self._logger.error( + LOGGER.error( f"Presentation on nonce={pres_req['nonce']} " f"cannot be validated: {str(err)}" ) return (False, msgs) - self._logger.debug(f">>> verifying presentation: {pres}") - self._logger.debug(f">>> for pres_req: {pres_req}") + LOGGER.debug(f">>> verifying presentation: {pres}") + LOGGER.debug(f">>> for pres_req: {pres_req}") try: verified = await indy.anoncreds.verifier_verify_proof( json.dumps(pres_req), @@ -85,7 +79,7 @@ async def verify_presentation( except IndyError as err: s = str(err) msgs.append(f"{PresVerifyMsg.PRES_VERIFY_ERROR.value}::{s}") - self._logger.exception( + LOGGER.exception( f"Validation of presentation on nonce={pres_req['nonce']} " "failed with error" ) diff --git a/aries_cloudagent/indy/verifier.py b/aries_cloudagent/indy/verifier.py index 1da88f8c17..0b7dd5f536 100644 --- a/aries_cloudagent/indy/verifier.py +++ b/aries_cloudagent/indy/verifier.py @@ -7,7 +7,6 @@ from time import time from typing import Mapping, Tuple -from ..config.logging import get_adapted_logger_inst from ..core.profile import Profile from ..ledger.multiple_ledger.ledger_requests_executor import ( GET_CRED_DEF, @@ -124,19 +123,14 @@ async def check_timestamps( pres: indy proof request rev_reg_defs: rev reg defs by rev reg id, augmented with transaction times """ - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) msgs = [] now = int(time()) non_revoc_intervals = indy_proof_req2non_revoc_intervals(pres_req) - _logger.debug(f">>> got non-revoc intervals: {non_revoc_intervals}") + LOGGER.debug(f">>> got non-revoc intervals: {non_revoc_intervals}") # timestamp for irrevocable credential cred_defs = [] for index, ident in enumerate(pres["identifiers"]): - _logger.debug(f">>> got (index, ident): ({index},{ident})") + LOGGER.debug(f">>> got (index, ident): ({index},{ident})") cred_def_id = ident["cred_def_id"] multitenant_mgr = profile.inject_or(BaseMultitenantManager) if multitenant_mgr: @@ -196,8 +190,8 @@ async def check_timestamps( if (timestamp is not None) ^ bool( non_revoc_intervals.get(uuid) ): - _logger.debug(f">>> uuid: {uuid}") - _logger.debug( + LOGGER.debug(f">>> uuid: {uuid}") + LOGGER.debug( f">>> revealed_attrs[uuid]: {revealed_attrs[uuid]}" ) raise ValueError( @@ -214,7 +208,7 @@ async def check_timestamps( f"{PresVerifyMsg.TSTMP_OUT_NON_REVOC_INTRVAL.value}::" f"{uuid}" ) - _logger.info( + LOGGER.info( f"Timestamp {timestamp} from ledger for item" f"{uuid} falls outside non-revocation interval " f"{non_revoc_intervals[uuid]}" @@ -255,7 +249,7 @@ async def check_timestamps( f"{PresVerifyMsg.TSTMP_OUT_NON_REVOC_INTRVAL.value}::" f"{uuid}" ) - _logger.warning( + LOGGER.warning( f"Timestamp {timestamp} from ledger for item" f"{uuid} falls outside non-revocation interval " f"{non_revoc_intervals[uuid]}" @@ -284,7 +278,7 @@ async def check_timestamps( msgs.append( f"{PresVerifyMsg.TSTMP_OUT_NON_REVOC_INTRVAL.value}::" f"{uuid}" ) - _logger.warning( + LOGGER.warning( f"Best-effort timestamp {timestamp} " "from ledger falls outside non-revocation interval " f"{non_revoc_intervals[uuid]}" diff --git a/aries_cloudagent/ledger/indy.py b/aries_cloudagent/ledger/indy.py index c66d4edf12..34e216339a 100644 --- a/aries_cloudagent/ledger/indy.py +++ b/aries_cloudagent/ledger/indy.py @@ -16,7 +16,6 @@ from ..cache.base import BaseCache from ..config.base import BaseInjector, BaseProvider, BaseSettings -from ..config.logging import get_adapted_logger_inst from ..indy.sdk.error import IndyErrorHandler from ..storage.base import StorageRecord from ..storage.indy import IndySdkStorage @@ -277,11 +276,6 @@ def __init__( """ self.pool = pool self.profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self.profile.settings.get("log.file"), - wallet_id=self.profile.settings.get("wallet.id"), - ) @property def pool_handle(self): @@ -1063,7 +1057,7 @@ async def get_revoc_reg_def(self, revoc_reg_id: str) -> dict: found_def["txnTime"] = json.loads(response_json)["result"]["txnTime"] except IndyError as e: - self._logger.error( + LOGGER.error( f"get_revoc_reg_def failed with revoc_reg_id={revoc_reg_id} - " f"{e.error_code}: {getattr(e, 'message', '[no message]')}" ) @@ -1087,7 +1081,7 @@ async def get_revoc_reg_entry(self, revoc_reg_id: str, timestamp: int): ledger_timestamp, ) = await indy.ledger.parse_get_revoc_reg_response(response_json) except IndyError as e: - self._logger.error( + LOGGER.error( f"get_revoc_reg_entry failed with revoc_reg_id={revoc_reg_id} - " f"{e.error_code}: {getattr(e, 'message', '[no message]')}" ) diff --git a/aries_cloudagent/ledger/multiple_ledger/indy_manager.py b/aries_cloudagent/ledger/multiple_ledger/indy_manager.py index df25db9b78..cf379b7913 100644 --- a/aries_cloudagent/ledger/multiple_ledger/indy_manager.py +++ b/aries_cloudagent/ledger/multiple_ledger/indy_manager.py @@ -1,5 +1,4 @@ """Multiple IndySdkLedger Manager.""" - import asyncio import concurrent.futures import logging @@ -10,7 +9,6 @@ from ...cache.base import BaseCache from ...core.profile import Profile -from ...config.logging import get_adapted_logger_inst from ...ledger.base import BaseLedger from ...ledger.error import LedgerError from ...wallet.crypto import did_is_self_certified @@ -55,11 +53,6 @@ def __init__( self.endorser_map = endorser_map self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=5) self.cache_ttl = cache_ttl - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self.profile.settings.get("log.file"), - wallet_id=self.profile.settings.get("wallet.id"), - ) async def get_write_ledgers(self) -> List[str]: """Return the write IndySdkLedger instance.""" @@ -131,7 +124,7 @@ async def _get_ledger_by_did( response = json.loads(response_json) data = response.get("result", {}).get("data") if not data: - self._logger.warning(f"Did {did} not posted to ledger {ledger_id}") + LOGGER.warning(f"Did {did} not posted to ledger {ledger_id}") return None if isinstance(data, str): data = json.loads(data) @@ -139,7 +132,7 @@ async def _get_ledger_by_did( expected_value=prepare_for_state_read(response), proof_nodes=get_proof_nodes(response), ): - self._logger.warning( + LOGGER.warning( f"State Proof validation failed for Did {did} " f"and ledger {ledger_id}" ) @@ -148,13 +141,13 @@ async def _get_ledger_by_did( return (ledger_id, indy_sdk_ledger, True) return (ledger_id, indy_sdk_ledger, False) except asyncio.TimeoutError: - self._logger.exception( + LOGGER.exception( f"get-nym request timedout for Did {did} and " f"ledger {ledger_id}, reply not received within 10 sec" ) return None except LedgerError as err: - self._logger.error( + LOGGER.error( "Exception when building and submitting get-nym request, " f"for Did {did} and ledger {ledger_id}, {err}" ) diff --git a/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py b/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py index 5c8a51e61b..8d2c51c576 100644 --- a/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py +++ b/aries_cloudagent/ledger/multiple_ledger/indy_vdr_manager.py @@ -9,7 +9,6 @@ from ...cache.base import BaseCache from ...core.profile import Profile -from ...config.logging import get_adapted_logger_inst from ...ledger.base import BaseLedger from ...ledger.error import LedgerError from ...wallet.crypto import did_is_self_certified @@ -54,11 +53,6 @@ def __init__( self.endorser_map = endorser_map self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=5) self.cache_ttl = cache_ttl - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self.profile.settings.get("log.file"), - wallet_id=self.profile.settings.get("wallet.id"), - ) async def get_write_ledgers(self) -> List[str]: """Return the write IndyVdrLedger instance.""" @@ -136,7 +130,7 @@ async def _get_ledger_by_did( else: data = response.get("data") if not data: - self._logger.warning(f"Did {did} not posted to ledger {ledger_id}") + LOGGER.warning(f"Did {did} not posted to ledger {ledger_id}") return None if isinstance(data, str): data = json.loads(data) @@ -144,7 +138,7 @@ async def _get_ledger_by_did( expected_value=prepare_for_state_read(response), proof_nodes=get_proof_nodes(response), ): - self._logger.warning( + LOGGER.warning( f"State Proof validation failed for Did {did} " f"and ledger {ledger_id}" ) @@ -153,13 +147,13 @@ async def _get_ledger_by_did( return (ledger_id, indy_vdr_ledger, True) return (ledger_id, indy_vdr_ledger, False) except asyncio.TimeoutError: - self._logger.exception( + LOGGER.exception( f"get-nym request timedout for Did {did} and " f"ledger {ledger_id}, reply not received within 10 sec" ) return None except LedgerError as err: - self._logger.error( + LOGGER.error( "Exception when building and submitting get-nym request, " f"for Did {did} and ledger {ledger_id}, {err}" ) diff --git a/aries_cloudagent/ledger/routes.py b/aries_cloudagent/ledger/routes.py index a45fc85a7f..46aa2612fe 100644 --- a/aries_cloudagent/ledger/routes.py +++ b/aries_cloudagent/ledger/routes.py @@ -15,7 +15,6 @@ from marshmallow import fields, validate from ..admin.request_context import AdminRequestContext -from ..config.logging import get_adapted_logger_inst from ..connections.models.conn_record import ConnRecord from ..messaging.models.base import BaseModelError from ..messaging.models.openapi import OpenAPISchema @@ -647,7 +646,6 @@ async def ledger_accept_taa(request: web.BaseRequest): """ context: AdminRequestContext = request["context"] - profile = context.profile async with context.profile.session() as session: ledger = session.inject_or(BaseLedger) if not ledger: @@ -657,12 +655,7 @@ async def ledger_accept_taa(request: web.BaseRequest): raise web.HTTPForbidden(reason=reason) accept_input = await request.json() - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.info(">>> accepting TAA with: %s", accept_input) + LOGGER.info(">>> accepting TAA with: %s", accept_input) async with ledger: try: taa_info = await ledger.get_txn_author_agreement() @@ -670,14 +663,14 @@ async def ledger_accept_taa(request: web.BaseRequest): raise web.HTTPBadRequest( reason=f"Ledger {ledger.pool_name} TAA not available" ) - _logger.info("TAA on ledger: ", taa_info) + LOGGER.info("TAA on ledger: ", taa_info) # this is a bit of a hack, but the "\ufeff" code is included in the # ledger TAA and digest calculation, so it needs to be included in the # TAA text that the user is accepting # (if you copy the TAA text using swagger it won't include this character) if taa_info["taa_record"]["text"].startswith("\ufeff"): if not accept_input["text"].startswith("\ufeff"): - _logger.info( + LOGGER.info( ">>> pre-pending -endian character to TAA acceptance text" ) accept_input["text"] = "\ufeff" + accept_input["text"] @@ -690,7 +683,7 @@ async def ledger_accept_taa(request: web.BaseRequest): ), } taa_record_digest = taa_record["digest"] - _logger.info(">>> accepting with digest: %s", taa_record_digest) + LOGGER.info(">>> accepting with digest: %s", taa_record_digest) await ledger.accept_txn_author_agreement( taa_record, accept_input["mechanism"] ) diff --git a/aries_cloudagent/multitenant/base.py b/aries_cloudagent/multitenant/base.py index 40a59d3001..832aaf9e7c 100644 --- a/aries_cloudagent/multitenant/base.py +++ b/aries_cloudagent/multitenant/base.py @@ -8,7 +8,7 @@ import jwt from ..config.injection_context import InjectionContext -from ..config.logging import get_adapted_logger_inst +from ..config.logging import context_wallet_id from ..core.error import BaseError from ..core.profile import Profile, ProfileSession from ..protocols.coordinate_mediation.v1_0.manager import ( @@ -43,11 +43,6 @@ def __init__(self, profile: Profile): self._profile = profile if not profile: raise MultitenantManagerError("Missing profile") - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) @property @abstractmethod @@ -110,7 +105,7 @@ def get_webhook_urls( if dispatch_type == "both": webhook_urls = list(set(base_webhook_urls) | set(subwallet_webhook_urls)) if not webhook_urls: - self._logger.warning( + LOGGER.warning( "No webhook URLs in context configuration " f"nor wallet record {wallet_id}, but wallet record " f"configures dispatch type {dispatch_type}" @@ -118,7 +113,7 @@ def get_webhook_urls( elif dispatch_type == "default": webhook_urls = subwallet_webhook_urls if not webhook_urls: - self._logger.warning( + LOGGER.warning( f"No webhook URLs in nor wallet record {wallet_id}, but " f"wallet record configures dispatch type {dispatch_type}" ) @@ -207,6 +202,9 @@ async def create_wallet( await profile.inject(RouteManager).route_verkey( profile, public_did_info.verkey ) + # add wallet id contextVar for logging + wallet_id = profile.settings.get("wallet.id") + context_wallet_id.set(wallet_id) except Exception: await wallet_record.delete_record(session) raise diff --git a/aries_cloudagent/multitenant/cache.py b/aries_cloudagent/multitenant/cache.py index f9b5625a1f..1fb3f37e3c 100644 --- a/aries_cloudagent/multitenant/cache.py +++ b/aries_cloudagent/multitenant/cache.py @@ -5,7 +5,6 @@ from typing import Optional from weakref import WeakValueDictionary -from ..config.logging import get_adapted_logger_inst from ..core.profile import Profile LOGGER = logging.getLogger(__name__) @@ -55,13 +54,8 @@ def get(self, key: str) -> Optional[Profile]: """ value = self.profiles.get(key) if value: - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=value.settings.get("log.file"), - wallet_id=value.settings.get("wallet.id"), - ) if key not in self._cache: - _logger.debug( + LOGGER.debug( f"Rescuing profile {key} from eviction from cache; profile " "will be reinserted into cache" ) diff --git a/aries_cloudagent/multitenant/route_manager.py b/aries_cloudagent/multitenant/route_manager.py index c664eddfef..954b3c98f9 100644 --- a/aries_cloudagent/multitenant/route_manager.py +++ b/aries_cloudagent/multitenant/route_manager.py @@ -4,7 +4,6 @@ import logging from typing import List, Optional, Tuple -from ..config.logging import get_adapted_logger_inst from ..connections.models.conn_record import ConnRecord from ..core.profile import Profile from ..messaging.responder import BaseResponder @@ -49,13 +48,8 @@ async def _route_for_key( skip_if_exists: bool = False, replace_key: Optional[str] = None, ): - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) wallet_id = profile.settings["wallet.id"] - _logger.info( + LOGGER.info( f"Add route record for recipient {recipient_key} to wallet {wallet_id}" ) routing_mgr = RoutingManager(self.root_profile) @@ -140,12 +134,7 @@ async def connection_from_recipient_key( for sub wallets, we check the sub wallet's connections before the base wallet. """ - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.debug("Retrieving connection for recipient key for multitenant wallet") + LOGGER.debug("Retrieving connection for recipient key for multitenant wallet") manager = profile.inject(BaseMultitenantManager) profile_to_search = ( await manager.get_profile_for_key( diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py index e7806ee596..905e039ce8 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/menu_request_handler.py @@ -1,6 +1,5 @@ """Action menu request message handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,12 +20,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("MenuRequestHandler called with context %s", context) assert isinstance(context.message, MenuRequest) diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py index 83f1dd2254..5e38bc90f3 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/handlers/perform_handler.py @@ -1,6 +1,5 @@ """Action menu perform request message handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,12 +20,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("PerformHandler called with context %s", context) assert isinstance(context.message, Perform) diff --git a/aries_cloudagent/protocols/actionmenu/v1_0/routes.py b/aries_cloudagent/protocols/actionmenu/v1_0/routes.py index d2ebc1be04..c9c94af9d6 100644 --- a/aries_cloudagent/protocols/actionmenu/v1_0/routes.py +++ b/aries_cloudagent/protocols/actionmenu/v1_0/routes.py @@ -8,7 +8,6 @@ from marshmallow import fields from ....admin.request_context import AdminRequestContext -from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord from ....messaging.models.base import BaseModelError from ....messaging.models.openapi import OpenAPISchema @@ -179,19 +178,14 @@ async def actionmenu_request(request: web.BaseRequest): """ context: AdminRequestContext = request["context"] - profile = context.profile connection_id = request.match_info["conn_id"] outbound_handler = request["outbound_message_router"] - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + try: async with context.profile.session() as session: connection = await ConnRecord.retrieve_by_id(session, connection_id) except StorageNotFoundError as err: - _logger.debug("Connection not found for action menu request: %s", connection_id) + LOGGER.debug("Connection not found for action menu request: %s", connection_id) raise web.HTTPNotFound(reason=err.roll_up) from err if connection.is_ready: @@ -214,27 +208,21 @@ async def actionmenu_send(request: web.BaseRequest): """ context: AdminRequestContext = request["context"] - profile = context.profile connection_id = request.match_info["conn_id"] outbound_handler = request["outbound_message_router"] menu_json = await request.json() - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.debug("Received send-menu request: %s %s", connection_id, menu_json) + LOGGER.debug("Received send-menu request: %s %s", connection_id, menu_json) try: msg = Menu.deserialize(menu_json["menu"]) except BaseModelError as err: - _logger.exception("Exception deserializing menu: %s", err.roll_up) + LOGGER.exception("Exception deserializing menu: %s", err.roll_up) raise web.HTTPBadRequest(reason=err.roll_up) from err try: async with context.profile.session() as session: connection = await ConnRecord.retrieve_by_id(session, connection_id) except StorageNotFoundError as err: - _logger.debug( + LOGGER.debug( "Connection not found for action menu send request: %s", connection_id ) raise web.HTTPNotFound(reason=err.roll_up) from err diff --git a/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py b/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py index c84f218b20..93bd91760f 100644 --- a/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py +++ b/aries_cloudagent/protocols/basicmessage/v1_0/handlers/basicmessage_handler.py @@ -1,6 +1,5 @@ """Basic message handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -20,12 +19,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("BasicMessageHandler called with context %s", context) assert isinstance(context.message, BasicMessage) diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py index d4ed484743..73efd9ecf8 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_request_handler.py @@ -1,10 +1,8 @@ """Connection request handler.""" -from .....config.logging import get_adapted_logger_inst from .....connections.models.conn_record import ConnRecord from .....messaging.base_handler import BaseHandler, BaseResponder, RequestContext from ....coordinate_mediation.v1_0.manager import MediationManager - from ..manager import ConnectionManager, ConnectionManagerError from ..messages.connection_request import ConnectionRequest from ..messages.problem_report import ConnectionProblemReport @@ -20,14 +18,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug(f"ConnectionRequestHandler called with context {context}") assert isinstance(context.message, ConnectionRequest) + + profile = context.profile mgr = ConnectionManager(profile) mediation_id = None diff --git a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py index c542a72a9f..5bb79269db 100644 --- a/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py +++ b/aries_cloudagent/protocols/connections/v1_0/handlers/connection_response_handler.py @@ -1,6 +1,5 @@ """Connection response handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -23,14 +22,10 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug(f"ConnectionResponseHandler called with context {context}") assert isinstance(context.message, ConnectionResponse) + + profile = context.profile mgr = ConnectionManager(profile) try: connection = await mgr.accept_response( diff --git a/aries_cloudagent/protocols/connections/v1_0/manager.py b/aries_cloudagent/protocols/connections/v1_0/manager.py index a05db729c1..fe33e1dac3 100644 --- a/aries_cloudagent/protocols/connections/v1_0/manager.py +++ b/aries_cloudagent/protocols/connections/v1_0/manager.py @@ -5,7 +5,6 @@ from ....core.oob_processor import OobMessageProcessor -from ....config.logging import get_adapted_logger_inst from ....connections.base_manager import BaseConnectionManager from ....connections.models.conn_record import ConnRecord from ....core.error import BaseError @@ -26,8 +25,6 @@ from .messages.problem_report import ProblemReportReason from .models.connection_detail import ConnectionDetail -LOGGER = logging.getLogger(__name__) - class ConnectionManagerError(BaseError): """Connection error.""" @@ -43,11 +40,7 @@ def __init__(self, profile: Profile): profile: The profile for this connection manager """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) + self._logger = logging.getLogger(__name__) super().__init__(self._profile) @property diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py index 3567feeea0..de00566498 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_handler.py @@ -1,6 +1,6 @@ """Handler for keylist message.""" +import logging -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -10,17 +10,14 @@ from ..models.mediation_record import MediationRecord +LOG = logging.getLogger(__name__) + + class KeylistHandler(BaseHandler): """Handler for keylist message.""" async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist message.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "%s called with context %s", self.__class__.__name__, context ) @@ -35,11 +32,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): session, context.connection_record.connection_id ) except StorageNotFoundError as err: - self._logger.warning( + LOG.warning( "Received keylist from connection that is not acting as mediator: %s", err, ) return # TODO verify our keylist matches? - self._logger.info("Keylist received: %s", context.message) + LOG.info("Keylist received: %s", context.message) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py index 047af97ed7..7d47296b64 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_query_handler.py @@ -1,6 +1,5 @@ """Handler for keylist-query message.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -17,12 +16,6 @@ class KeylistQueryHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist-query message.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "%s called with context %s", self.__class__.__name__, context ) @@ -30,6 +23,8 @@ async def handle(self, context: RequestContext, responder: BaseResponder): if not context.connection_ready: raise HandlerException("Invalid keylist query: no active connection") + + profile = context.profile mgr = MediationManager(profile) try: async with profile.session() as session: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py index 37e7066682..20c63a5e15 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_handler.py @@ -1,6 +1,5 @@ """Handler for keylist-update messages.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -17,12 +16,6 @@ class KeylistUpdateHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist-update messages.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "%s called with context %s", self.__class__.__name__, context ) @@ -30,6 +23,8 @@ async def handle(self, context: RequestContext, responder: BaseResponder): if not context.connection_ready: raise HandlerException("Cannot update routes: no active connection") + + profile = context.profile mgr = MediationManager(profile) try: async with profile.session() as session: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py index f45cef4fba..d2c33704d8 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/keylist_update_response_handler.py @@ -1,6 +1,5 @@ """Handler for keylist-update-response message.""" -from .....config.logging import get_adapted_logger_inst from .....core.profile import Profile from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -17,12 +16,6 @@ class KeylistUpdateResponseHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle keylist-update-response message.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "%s called with context %s", self.__class__.__name__, context ) @@ -43,11 +36,6 @@ async def notify_keylist_updated( self, profile: Profile, connection_id: str, response: KeylistUpdateResponse ): """Notify of keylist update response received.""" - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) route_manager = profile.inject(RouteManager) self._logger.debug( "Retrieving connection ID from route manager of type %s", diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py index e0406195af..7a27a8fdce 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_deny_handler.py @@ -1,6 +1,5 @@ """Handler for mediate-deny message.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -16,12 +15,6 @@ class MediationDenyHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle mediate-deny message.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "%s called with context %s", self.__class__.__name__, context ) @@ -29,6 +22,8 @@ async def handle(self, context: RequestContext, responder: BaseResponder): if not context.connection_ready: raise HandlerException("Received mediation deny from inactive connection") + + profile = context.profile mgr = MediationManager(profile) try: async with profile.session() as session: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py index af13775852..fc597b63c7 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_grant_handler.py @@ -1,6 +1,5 @@ """Handler for mediate-grant message.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -17,12 +16,6 @@ class MediationGrantHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle mediate-grant message.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "%s called with context %s", self.__class__.__name__, context ) @@ -30,6 +23,8 @@ async def handle(self, context: RequestContext, responder: BaseResponder): if not context.connection_ready: raise HandlerException("Received mediation grant from inactive connection") + + profile = context.profile mgr = MediationManager(profile) try: async with profile.session() as session: diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py index 2a017d9852..fedd7da258 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/mediation_request_handler.py @@ -1,6 +1,5 @@ """Handler for mediate-request message.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -15,12 +14,6 @@ class MediationRequestHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle mediate-request message.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "%s called with context %s", self.__class__.__name__, context ) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py index 92cb5a0bac..8a5a1143ec 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/manager.py @@ -5,7 +5,6 @@ from ....core.error import BaseError from ....core.profile import Profile, ProfileSession -from ....config.logging import get_adapted_logger_inst from ....storage.base import BaseStorage from ....storage.error import StorageNotFoundError from ....storage.record import StorageRecord @@ -68,11 +67,6 @@ def __init__(self, profile: Profile): self._profile = profile if not profile: raise MediationManagerError("Missing profile") - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) # Role: Server {{{ @@ -586,7 +580,7 @@ async def store_update_results( for updated in results: if updated.result != KeylistUpdated.RESULT_SUCCESS: # TODO better handle different results? - self._logger.warning( + LOGGER.warning( "Keylist update failure: %s(%s): %s", updated.action, updated.recipient_key, @@ -620,13 +614,13 @@ async def store_update_results( }, ) except StorageNotFoundError as err: - self._logger.error( + LOGGER.error( "No route found while processing keylist update response: %s", err, ) else: if len(records) > 1: - self._logger.error( + LOGGER.error( f"Too many ({len(records)}) routes found " "while processing keylist update response" ) diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py index 84e7ce05a0..990252cd5a 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/route_manager.py @@ -8,7 +8,6 @@ import logging from typing import List, Optional, Tuple -from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -23,6 +22,7 @@ from .models.mediation_record import MediationRecord from .normalization import normalize_from_did_key + LOGGER = logging.getLogger(__name__) @@ -129,12 +129,7 @@ async def route_connection_as_invitee( mediation_record: Optional[MediationRecord] = None, ) -> Optional[KeylistUpdate]: """Set up routing for a new connection when we are the invitee.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.debug("Routing connection as invitee") + LOGGER.debug("Routing connection as invitee") my_info = await self.get_or_create_my_did(profile, conn_record) return await self._route_for_key( profile, my_info.verkey, mediation_record, skip_if_exists=True @@ -147,12 +142,7 @@ async def route_connection_as_inviter( mediation_record: Optional[MediationRecord] = None, ) -> Optional[KeylistUpdate]: """Set up routing for a new connection when we are the inviter.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.debug("Routing connection as inviter") + LOGGER.debug("Routing connection as inviter") my_info = await self.get_or_create_my_did(profile, conn_record) replace_key = conn_record.invitation_key diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py index 4ca42c8e04..5ccab85c5f 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py @@ -375,12 +375,9 @@ async def test_add_remove_key_mix(self, manager): async def test_store_update_results( self, session: ProfileSession, + manager: MediationManager, ): """test_store_update_results.""" - profile = session.profile - profile.settings["log.file"] = "test.log" - profile.settings["wallet.id"] = "test123" - mock_logger = async_mock.MagicMock(error=async_mock.MagicMock()) await RouteRecord( role=RouteRecord.ROLE_CLIENT, connection_id=TEST_CONN_ID, @@ -398,49 +395,41 @@ async def test_store_update_results( result=KeylistUpdated.RESULT_SUCCESS, ), ] + await manager.store_update_results(TEST_CONN_ID, results) + routes = await RouteRecord.query(session) + + assert len(routes) == 1 + assert routes[0].recipient_key == TEST_ROUTE_VERKEY + + results = [ + KeylistUpdated( + recipient_key=TEST_VERKEY, + action=KeylistUpdateRule.RULE_REMOVE, + result=KeylistUpdated.RESULT_SUCCESS, + ), + ] + with async_mock.patch.object( - test_module, - "get_adapted_logger_inst", - async_mock.MagicMock(return_value=mock_logger), - ): - manager = MediationManager(profile) + RouteRecord, "query", async_mock.CoroutineMock() + ) as mock_route_rec_query, async_mock.patch.object( + test_module.LOGGER, "error", async_mock.MagicMock() + ) as mock_logger_error: + mock_route_rec_query.side_effect = StorageNotFoundError("no record") + await manager.store_update_results(TEST_CONN_ID, results) - routes = await RouteRecord.query(session) - - assert len(routes) == 1 - assert routes[0].recipient_key == TEST_ROUTE_VERKEY - - results = [ - KeylistUpdated( - recipient_key=TEST_VERKEY, - action=KeylistUpdateRule.RULE_REMOVE, - result=KeylistUpdated.RESULT_SUCCESS, - ), - ] - - with async_mock.patch.object( - RouteRecord, "query", async_mock.CoroutineMock() - ) as mock_route_rec_query: - mock_route_rec_query.side_effect = StorageNotFoundError("no record") - await manager.store_update_results(TEST_CONN_ID, results) - assert mock_logger.error.call_count == 1 - - del profile.settings["log.file"] - del profile.settings["wallet.id"] - mock_logger = async_mock.MagicMock(error=async_mock.MagicMock()) + mock_logger_error.assert_called_once() + with async_mock.patch.object( RouteRecord, "query", async_mock.CoroutineMock() ) as mock_route_rec_query, async_mock.patch.object( - test_module, - "get_adapted_logger_inst", - async_mock.MagicMock(return_value=mock_logger), - ): + test_module.LOGGER, "error", async_mock.MagicMock() + ) as mock_logger_error: mock_route_rec_query.return_value = [ async_mock.MagicMock(delete_record=async_mock.CoroutineMock()) ] * 2 - manager = MediationManager(profile) + await manager.store_update_results(TEST_CONN_ID, results) - assert mock_logger.error.call_count == 1 + mock_logger_error.assert_called_once() async def test_store_update_results_exists_relay(self, session, manager): """test_store_update_results_record_exists_relay.""" diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py index 0af0452e43..72122aa62f 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/complete_handler.py @@ -1,6 +1,5 @@ """Connection complete handler under RFC 23 (DID exchange).""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,14 +20,10 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug(f"DIDXCompleteHandler called with context {context}") assert isinstance(context.message, DIDXComplete) + + profile = context.profile mgr = DIDXManager(profile) try: await mgr.accept_complete(context.message, context.message_receipt) diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py index faf7131224..b4b85eb1dc 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/request_handler.py @@ -3,8 +3,6 @@ from aries_cloudagent.protocols.didexchange.v1_0.messages.problem_report import ( DIDXProblemReport, ) - -from .....config.logging import get_adapted_logger_inst from .....connections.models.conn_record import ConnRecord from .....messaging.base_handler import BaseHandler, BaseResponder, RequestContext from ....coordinate_mediation.v1_0.manager import MediationManager @@ -22,14 +20,11 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug(f"DIDXRequestHandler called with context {context}") assert isinstance(context.message, DIDXRequest) + + profile = context.profile mgr = DIDXManager(profile) mediation_id = None diff --git a/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py b/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py index 0efbd0ec34..c2c094320a 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/handlers/response_handler.py @@ -3,8 +3,6 @@ from aries_cloudagent.protocols.didexchange.v1_0.messages.problem_report import ( DIDXProblemReport, ) - -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -27,14 +25,10 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug(f"DIDXResponseHandler called with context {context}") assert isinstance(context.message, DIDXResponse) + + profile = context.profile mgr = DIDXManager(profile) try: conn_rec = await mgr.accept_response( diff --git a/aries_cloudagent/protocols/didexchange/v1_0/manager.py b/aries_cloudagent/protocols/didexchange/v1_0/manager.py index a1440940dc..0db2702e51 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/manager.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/manager.py @@ -8,7 +8,6 @@ from pydid import BaseDIDDocument as ResolvedDocument from pydid import DIDCommService -from ....config.logging import get_adapted_logger_inst from ....connections.base_manager import BaseConnectionManager from ....connections.models.conn_record import ConnRecord from ....connections.models.diddoc import DIDDoc @@ -40,8 +39,6 @@ from .messages.request import DIDXRequest from .messages.response import DIDXResponse -LOGGER = logging.getLogger(__name__) - class DIDXManagerError(BaseError): """Connection error.""" @@ -57,11 +54,7 @@ def __init__(self, profile: Profile): profile: The profile for this did exchange manager """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) + self._logger = logging.getLogger(__name__) super().__init__(self._profile) @property diff --git a/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py b/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py index c547ab1096..7c5a313fc4 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py +++ b/aries_cloudagent/protocols/discovery/v1_0/handlers/disclose_handler.py @@ -1,6 +1,5 @@ """Handler for incoming disclose messages.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -17,18 +16,13 @@ class DiscloseHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("DiscloseHandler called with context %s", context) assert isinstance(context.message, Disclose) if not context.connection_ready: raise HandlerException( "Received disclosures message from inactive connection" ) + profile = context.profile mgr = V10DiscoveryMgr(profile) await mgr.receive_disclose( context.message, connection_id=context.connection_record.connection_id diff --git a/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py b/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py index 0defd19c6a..0336b01351 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py +++ b/aries_cloudagent/protocols/discovery/v1_0/handlers/query_handler.py @@ -1,6 +1,5 @@ """Handler for incoming query messages.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -16,14 +15,9 @@ class QueryHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("QueryHandler called with context %s", context) assert isinstance(context.message, Query) + profile = context.profile mgr = V10DiscoveryMgr(profile) reply = await mgr.receive_query(context.message) reply.assign_thread_from(context.message) diff --git a/aries_cloudagent/protocols/discovery/v1_0/manager.py b/aries_cloudagent/protocols/discovery/v1_0/manager.py index f90c0f94e5..c01093f631 100644 --- a/aries_cloudagent/protocols/discovery/v1_0/manager.py +++ b/aries_cloudagent/protocols/discovery/v1_0/manager.py @@ -5,7 +5,6 @@ from typing import Optional -from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....core.protocol_registry import ProtocolRegistry @@ -16,8 +15,6 @@ from .messages.query import Query from .models.discovery_record import V10DiscoveryExchangeRecord -LOGGER = logging.getLogger(__name__) - class V10DiscoveryMgrError(BaseError): """Discover feature v1_0 error.""" @@ -33,11 +30,7 @@ def __init__(self, profile: Profile): profile: The profile for this manager """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) + self._logger = logging.getLogger(__name__) @property def profile(self) -> Profile: diff --git a/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py b/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py index e3a59f0519..adab14bf3e 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py +++ b/aries_cloudagent/protocols/discovery/v2_0/handlers/disclosures_handler.py @@ -1,6 +1,5 @@ """Handler for incoming disclose messages.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -17,18 +16,13 @@ class DisclosuresHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("DiscloseHandler called with context %s", context) assert isinstance(context.message, Disclosures) if not context.connection_ready: raise HandlerException( "Received disclosures message from inactive connection" ) + profile = context.profile mgr = V20DiscoveryMgr(profile) await mgr.receive_disclose( context.message, connection_id=context.connection_record.connection_id diff --git a/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py b/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py index 4c843c7d7e..e970ad0c6f 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py +++ b/aries_cloudagent/protocols/discovery/v2_0/handlers/queries_handler.py @@ -1,6 +1,5 @@ """Handler for incoming queries messages.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -16,14 +15,9 @@ class QueriesHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("QueryHandler called with context %s", context) assert isinstance(context.message, Queries) + profile = context.profile mgr = V20DiscoveryMgr(profile) reply = await mgr.receive_query(context.message) reply.assign_thread_from(context.message) diff --git a/aries_cloudagent/protocols/discovery/v2_0/manager.py b/aries_cloudagent/protocols/discovery/v2_0/manager.py index 7ee18f6efd..05609e3c09 100644 --- a/aries_cloudagent/protocols/discovery/v2_0/manager.py +++ b/aries_cloudagent/protocols/discovery/v2_0/manager.py @@ -9,7 +9,6 @@ from ....core.profile import Profile from ....core.protocol_registry import ProtocolRegistry from ....core.goal_code_registry import GoalCodeRegistry -from ....config.logging import get_adapted_logger_inst from ....storage.error import StorageNotFoundError from ....messaging.responder import BaseResponder @@ -17,8 +16,6 @@ from .messages.queries import QueryItem, Queries from .models.discovery_record import V20DiscoveryExchangeRecord -LOGGER = logging.getLogger(__name__) - class V20DiscoveryMgrError(BaseError): """Discover feature v2_0 error.""" @@ -34,11 +31,7 @@ def __init__(self, profile: Profile): profile: The profile for this manager """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) + self._logger = logging.getLogger(__name__) @property def profile(self) -> Profile: diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py index d3910e5291..88dff4f6e8 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/endorsed_transaction_response_handler.py @@ -1,6 +1,5 @@ """Endorsed transaction response handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -23,12 +22,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug( f"EndorsedTransactionResponseHandler called with context {context}" ) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py index b327557566..46da51853e 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/refused_transaction_response_handler.py @@ -1,6 +1,5 @@ """Refused transaction response handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -22,12 +21,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug( f"RefusedTransactionResponseHandler called with context {context}" ) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py index 1294ef710f..0803a7216b 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_acknowledgement_handler.py @@ -1,6 +1,5 @@ """Transaction acknowledgement message handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -22,12 +21,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug( f"TransactionAcknowledgementHandler called with context {context}" ) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py index e194cf710e..0154b4e723 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_cancel_handler.py @@ -1,6 +1,5 @@ """Cancel transaction request handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -22,12 +21,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug(f"TransactionCancelHandler called with context {context}") assert isinstance(context.message, CancelTransaction) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py index 3a95958e1c..35e1d50bed 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_job_to_send_handler.py @@ -1,6 +1,5 @@ """Transaction Job to send handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,12 +20,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug(f"TransactionJobToSendHandler called with context {context}") assert isinstance(context.message, TransactionJobToSend) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py index 66da217863..bc60a9a69b 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_request_handler.py @@ -1,6 +1,5 @@ """Transaction request handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -25,12 +24,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug(f"TransactionRequestHandler called with context {context}") assert isinstance(context.message, TransactionRequest) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py index 1fe373b793..268b3f85f2 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/transaction_resend_handler.py @@ -1,6 +1,5 @@ """Transaction resend handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -22,12 +21,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug(f"TransactionResendHandler called with context {context}") assert isinstance(context.message, TransactionResend) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py index 5a349232b4..25405cd9e5 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py @@ -15,7 +15,6 @@ from marshmallow import fields, validate from ....admin.request_context import AdminRequestContext -from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.event_bus import Event, EventBus from ....core.profile import Profile @@ -720,11 +719,6 @@ def register_events(event_bus: EventBus): async def on_startup_event(profile: Profile, event: Event): """Handle any events we need to support.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) # auto setup is only for authors if not is_author_role(profile): return @@ -801,7 +795,7 @@ async def on_startup_event(profile: Profile, event: Event): except Exception: # log the error, but continue - _logger.exception( + LOGGER.exception( "Error accepting endorser invitation/configuring endorser connection: %s", ) diff --git a/aries_cloudagent/protocols/introduction/v0_1/demo_service.py b/aries_cloudagent/protocols/introduction/v0_1/demo_service.py index 95a0e9b09a..3f54dd6f8c 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/demo_service.py +++ b/aries_cloudagent/protocols/introduction/v0_1/demo_service.py @@ -3,7 +3,6 @@ import json import logging -from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.profile import ProfileSession from ....storage.base import ( @@ -111,12 +110,7 @@ async def return_invitation( outbound_handler: The outbound handler coroutine for sending a message """ thread_id = invitation._thread_id - profile = session.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + tag_filter = {"target_connection_id": target_connection_id} storage = session.inject(BaseStorage) records = await storage.find_all_records( @@ -140,8 +134,8 @@ async def return_invitation( init_connection_id = row.tags["init_connection_id"] await outbound_handler(msg, connection_id=init_connection_id) found = True - _logger.info("Forwarded fwd-invitation to %s", init_connection_id) + LOGGER.info("Forwarded fwd-invitation to %s", init_connection_id) break if not found: - _logger.error("Could not forward invitation, no pending introduction found") + LOGGER.error("Could not forward invitation, no pending introduction found") diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py index 99a02c3006..2b6cbeadba 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/forward_invitation_handler.py @@ -1,6 +1,5 @@ """Handler for incoming forward invitation messages.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -19,12 +18,6 @@ class ForwardInvitationHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("ForwardInvitationHandler called with context %s", context) assert isinstance(context.message, ForwardInvitation) @@ -34,6 +27,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): ) # Store invitation + profile = context.profile connection_mgr = ConnectionManager(profile) try: diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py index bf69f9a9fe..3244d2e338 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_handler.py @@ -1,8 +1,6 @@ """Handler for incoming invitation messages.""" from typing import Optional - -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -19,12 +17,6 @@ class InvitationHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("InvitationHandler called with context %s", context) assert isinstance(context.message, IntroInvitation) diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py index 508e082d85..c1d284c1f3 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/invitation_request_handler.py @@ -1,6 +1,5 @@ """Handler for incoming invitation request messages.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -19,12 +18,6 @@ class InvitationRequestHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("InvitationRequestHandler called with context %s", context) assert isinstance(context.message, IntroInvitationRequest) @@ -37,6 +30,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): if context.settings.get("auto_accept_intro_invitation_requests"): # Create a new connection invitation and send it back in an IntroInvitation + profile = context.profile connection_mgr = ConnectionManager(profile) _connection, invite = await connection_mgr.create_invitation() response = IntroInvitation( diff --git a/aries_cloudagent/protocols/introduction/v0_1/routes.py b/aries_cloudagent/protocols/introduction/v0_1/routes.py index 6a670e4422..ed1e9ea226 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/routes.py +++ b/aries_cloudagent/protocols/introduction/v0_1/routes.py @@ -9,7 +9,6 @@ from marshmallow import fields from ....admin.request_context import AdminRequestContext -from ....config.logging import get_adapted_logger_inst from ....messaging.models.openapi import OpenAPISchema from ....messaging.valid import UUID4_EXAMPLE from ....storage.error import StorageError @@ -61,14 +60,8 @@ async def introduction_start(request: web.BaseRequest): request: aiohttp request object """ + LOGGER.info("Introduction requested") context: AdminRequestContext = request["context"] - profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.info("Introduction requested") outbound_handler = request["outbound_message_router"] init_connection_id = request.match_info["conn_id"] target_connection_id = request.query.get("target_connection_id") diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py index 9a4da7c1a8..1c7f2f7d87 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_ack_handler.py @@ -1,6 +1,5 @@ """Credential ack message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -22,12 +21,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("CredentialAckHandler called with context %s", context) assert isinstance(context.message, CredentialAck) self._logger.info( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py index 3a3a005677..778a9985aa 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_issue_handler.py @@ -1,6 +1,5 @@ """Credential issue message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError from .....messaging.base_handler import BaseHandler, HandlerException @@ -29,11 +28,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("CredentialHandler called with context %s", context) assert isinstance(context.message, CredentialIssue) self._logger.info( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py index 2719813057..f2e1b0e324 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_offer_handler.py @@ -1,6 +1,6 @@ """Credential offer message handler.""" -from .....config.logging import get_adapted_logger_inst + from .....wallet.util import default_did_from_verkey from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError @@ -31,11 +31,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("CredentialOfferHandler called with context %s", context) assert isinstance(context.message, CredentialOffer) self._logger.info( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py index 6a23734851..3936dece50 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_problem_report_handler.py @@ -1,6 +1,5 @@ """Credential problem report message handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -20,12 +19,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "Issue-credential v1.0 problem report handler called with context %s", context, diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py index c1c355ecfd..5b4ff0b1ce 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_proposal_handler.py @@ -1,6 +1,5 @@ """Credential proposal message handler.""" -from .....config.logging import get_adapted_logger_inst from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -29,11 +28,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("CredentialProposalHandler called with context %s", context) assert isinstance(context.message, CredentialProposal) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py index 6cbaa247bc..02794bca6f 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/credential_request_handler.py @@ -1,6 +1,5 @@ """Credential request message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError @@ -30,11 +29,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("CredentialRequestHandler called with context %s", context) assert isinstance(context.message, CredentialRequest) self._logger.info( diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/manager.py b/aries_cloudagent/protocols/issue_credential/v1_0/manager.py index fc3ba0a366..f0dabfedff 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/manager.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/manager.py @@ -8,7 +8,6 @@ from ....cache.base import BaseCache from ....connections.models.conn_record import ConnRecord -from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....indy.holder import IndyHolder, IndyHolderError @@ -62,11 +61,6 @@ def __init__(self, profile: Profile): profile: The profile instance for this credential manager """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) @property def profile(self) -> Profile: @@ -445,7 +439,7 @@ async def _create(): } if cred_ex_record.state == V10CredentialExchange.STATE_REQUEST_SENT: - self._logger.warning( + LOGGER.warning( "create_request called multiple times for v1.0 credential exchange: %s", cred_ex_record.credential_exchange_id, ) @@ -547,7 +541,7 @@ async def receive_request( "Indy issue credential format can't start from credential request" ) from None if cred_ex_record.state != V10CredentialExchange.STATE_OFFER_SENT: - self._logger.error( + LOGGER.error( "Skipping credential request; exchange state is %s (id=%s)", cred_ex_record.state, cred_ex_record.credential_exchange_id, @@ -586,7 +580,7 @@ async def issue_credential( credential_ser = None if cred_ex_record.credential: - self._logger.warning( + LOGGER.warning( "issue_credential called multiple times for v1.0 credential exchange %s", cred_ex_record.credential_exchange_id, ) @@ -631,7 +625,7 @@ async def issue_credential( for attempt in range(max(retries, 1)): if attempt > 0: - self._logger.info( + LOGGER.info( "Waiting 2s before retrying credential issuance " "for cred def '%s'", cred_def_id, @@ -836,9 +830,7 @@ async def store_credential( rev_reg_def=revoc_reg_def, ) except IndyHolderError as e: - self._logger.error( - "Error storing credential: %s: %s", e.error_code, e.message - ) + LOGGER.error("Error storing credential: %s: %s", e.error_code, e.message) raise e credential_json = await holder.get_credential(credential_id) @@ -892,7 +884,7 @@ async def send_credential_ack( txn, cred_ex_record.credential_exchange_id, for_update=True ) except StorageNotFoundError: - self._logger.warning( + LOGGER.warning( "Skipping credential exchange ack, record not found: '%s'", cred_ex_record.credential_exchange_id, ) @@ -902,7 +894,7 @@ async def send_credential_ack( cred_ex_record.state != V10CredentialExchange.STATE_CREDENTIAL_RECEIVED ): - self._logger.warning( + LOGGER.warning( "Skipping credential exchange ack, state is '%s' for record '%s'", cred_ex_record.state, cred_ex_record.credential_exchange_id, @@ -918,7 +910,7 @@ async def send_credential_ack( await cred_ex_record.delete_record(session) # all done: delete except StorageError: - self._logger.exception( + LOGGER.exception( "Error updating credential exchange" ) # holder still owes an ack: carry on @@ -929,7 +921,7 @@ async def send_credential_ack( connection_id=cred_ex_record.connection_id, ) else: - self._logger.warning( + LOGGER.warning( "Configuration has no BaseResponder: cannot ack credential on %s", cred_ex_record.thread_id, ) @@ -959,7 +951,7 @@ async def receive_credential_ack( ) ) except StorageNotFoundError: - self._logger.warning( + LOGGER.warning( "Skip ack message on credential exchange, record not found %s", message._thread_id, ) @@ -996,7 +988,7 @@ async def receive_problem_report( ) ) except StorageNotFoundError: - self._logger.warning( + LOGGER.warning( "Skip problem report on credential exchange, record not found %s", message._thread_id, ) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py b/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py index 4d2cf0ab95..2137d04986 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/models/credential_exchange.py @@ -5,7 +5,6 @@ from marshmallow import fields, validate -from .....config.logging import get_adapted_logger_inst from .....core.profile import ProfileSession from .....indy.models.cred import IndyCredential, IndyCredentialSchema from .....indy.models.cred_abstract import IndyCredAbstract, IndyCredAbstractSchema @@ -207,12 +206,7 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - profile = session.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + if self._last_state == state: # already done return @@ -228,7 +222,7 @@ async def save_error_state( log_override=log_override, ) except StorageError: - _logger.exception("Error saving credential exchange error state") + LOGGER.exception("Error saving credential exchange error state") # Override async def emit_event(self, session: ProfileSession, payload: Any = None): diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py index ee56a933d9..183ecbf0a0 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/handler.py @@ -7,7 +7,6 @@ from .....core.error import BaseError from .....core.profile import Profile -from .....config.logging import get_adapted_logger_inst from .....messaging.decorators.attach_decorator import AttachDecorator from ..messages.cred_format import V20CredFormat @@ -18,6 +17,7 @@ from ..models.cred_ex_record import V20CredExRecord LOGGER = logging.getLogger(__name__) + CredFormatAttachment = Tuple[V20CredFormat, AttachDecorator] @@ -35,11 +35,6 @@ def __init__(self, profile: Profile): super().__init__() self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) @property def profile(self) -> Profile: diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py index 7912644363..26f5d10498 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_ack_handler.py @@ -1,6 +1,5 @@ """Credential ack message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -22,12 +21,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("V20CredAckHandler called with context %s", context) assert isinstance(context.message, V20CredAck) self._logger.info( diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py index 47de99eb69..f3c5704252 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_issue_handler.py @@ -1,6 +1,5 @@ """Credential issue message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError from .....messaging.base_handler import BaseHandler, HandlerException @@ -28,12 +27,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("V20CredIssueHandler called with context %s", context) assert isinstance(context.message, V20CredIssue) self._logger.info( diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py index dcc4a0e965..3184b79b55 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_offer_handler.py @@ -1,6 +1,5 @@ """Credential offer message handler.""" -from .....config.logging import get_adapted_logger_inst from .....wallet.util import default_did_from_verkey from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError @@ -30,12 +29,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("V20CredOfferHandler called with context %s", context) assert isinstance(context.message, V20CredOffer) self._logger.info( @@ -64,6 +58,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): else None ) + profile = context.profile cred_manager = V20CredManager(profile) cred_ex_record = await cred_manager.receive_offer( context.message, connection_id diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py index b3078298ba..d3b85ecacd 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_problem_report_handler.py @@ -1,6 +1,5 @@ """Credential problem report message handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -20,12 +19,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "Issue-credential v2.0 problem report handler called with context %s", context, diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py index f95a562518..4ff09f70aa 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_proposal_handler.py @@ -1,6 +1,5 @@ """Credential proposal message handler.""" -from .....config.logging import get_adapted_logger_inst from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -28,12 +27,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("V20CredProposalHandler called with context %s", context) assert isinstance(context.message, V20CredProposal) self._logger.info( @@ -49,6 +43,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): "Connectionless not supported for credential proposal" ) + profile = context.profile cred_manager = V20CredManager(profile) cred_ex_record = await cred_manager.receive_proposal( context.message, context.connection_record.connection_id diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py index 4df7e55905..ecf0d6fb15 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/cred_request_handler.py @@ -1,6 +1,5 @@ """Credential request message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.issuer import IndyIssuerError from .....ledger.error import LedgerError @@ -29,12 +28,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("V20CredRequestHandler called with context %s", context) assert isinstance(context.message, V20CredRequest) self._logger.info( @@ -58,6 +52,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): " request" ) + profile = context.profile cred_manager = V20CredManager(profile) cred_ex_record = await cred_manager.receive_request( context.message, context.connection_record, oob_record diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/manager.py b/aries_cloudagent/protocols/issue_credential/v2_0/manager.py index d699d66592..fe737c27f6 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/manager.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/manager.py @@ -5,7 +5,6 @@ from typing import Mapping, Optional, Tuple from ....connections.models.conn_record import ConnRecord -from ....config.logging import get_adapted_logger_inst from ....core.oob_processor import OobRecord from ....core.error import BaseError from ....core.profile import Profile @@ -39,11 +38,6 @@ def __init__(self, profile: Profile): profile: The profile instance for this credential manager """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) @property def profile(self) -> Profile: @@ -655,7 +649,7 @@ async def send_cred_ack( await self.delete_cred_ex_record(cred_ex_record.cred_ex_id) except StorageError: - self._logger.exception( + LOGGER.exception( "Error sending credential ack" ) # holder still owes an ack: carry on @@ -666,7 +660,7 @@ async def send_cred_ack( connection_id=cred_ex_record.connection_id, ) else: - self._logger.warning( + LOGGER.warning( "Configuration has no BaseResponder: cannot ack credential on %s", cred_ex_record.thread_id, ) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py b/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py index 8fa2a8557a..1eece14bac 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/models/cred_ex_record.py @@ -5,7 +5,6 @@ from marshmallow import Schema, fields, validate -from .....config.logging import get_adapted_logger_inst from .....core.profile import ProfileSession from .....messaging.models.base_record import BaseExchangeRecord, BaseExchangeSchema from .....messaging.valid import UUID4_EXAMPLE @@ -163,12 +162,7 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - profile = session.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + if self._last_state == state: # already done return @@ -184,7 +178,7 @@ async def save_error_state( log_override=log_override, ) except StorageError as err: - _logger.exception(err) + LOGGER.exception(err) # Override async def emit_event(self, session: ProfileSession, payload: Any = None): diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py b/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py index 2a6c3efdd4..d46fd498d7 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/models/tests/test_cred_ex_record.py @@ -118,23 +118,18 @@ def test_serde(self): async def test_save_error_state(self): session = InMemoryProfile.test_session() - profile = session.profile - profile.settings["log.file"] = "test_file.log" - profile.settings["wallet.id"] = "test123" record = V20CredExRecord(state=None) assert record._last_state is None await record.save_error_state(session) # cover short circuit record.state = V20CredExRecord.STATE_PROPOSAL_RECEIVED await record.save(session) - mock_logger = async_mock.MagicMock(exception=async_mock.MagicMock()) + with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( - test_module, - "get_adapted_logger_inst", - async_mock.MagicMock(return_value=mock_logger), - ): + test_module.LOGGER, "exception", async_mock.MagicMock() + ) as mock_log_exc: mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="test") - assert mock_logger.exception.call_count == 1 + mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/routes.py b/aries_cloudagent/protocols/issue_credential/v2_0/routes.py index 2a63a366e9..721128b4ae 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/routes.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/routes.py @@ -16,7 +16,6 @@ from marshmallow import ValidationError, fields, validate, validates_schema from ....admin.request_context import AdminRequestContext -from ....config.logging import get_adapted_logger_inst from ....connections.models.conn_record import ConnRecord from ....core.profile import Profile from ....indy.holder import IndyHolderError @@ -681,11 +680,6 @@ async def credential_exchange_send(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -749,7 +743,7 @@ async def credential_exchange_send(request: web.BaseRequest): V20CredManagerError, V20CredFormatError, ) as err: - _logger.exception("Error preparing credential offer") + LOGGER.exception("Error preparing credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -796,11 +790,6 @@ async def credential_exchange_send_proposal(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -842,7 +831,7 @@ async def credential_exchange_send_proposal(request: web.BaseRequest): result = cred_ex_record.serialize() except (BaseModelError, StorageError) as err: - _logger.exception("Error preparing credential proposal") + LOGGER.exception("Error preparing credential proposal") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -933,11 +922,7 @@ async def credential_exchange_create_free_offer(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + body = await request.json() auto_issue = body.get( @@ -970,7 +955,7 @@ async def credential_exchange_create_free_offer(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - _logger.exception("Error creating free credential offer") + LOGGER.exception("Error creating free credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1007,11 +992,6 @@ async def credential_exchange_send_free_offer(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -1058,7 +1038,7 @@ async def credential_exchange_send_free_offer(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - _logger.exception("Error preparing free credential offer") + LOGGER.exception("Error preparing free credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1106,11 +1086,6 @@ async def credential_exchange_send_bound_offer(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) outbound_handler = request["outbound_message_router"] body = await request.json() if request.body_exists else {} @@ -1169,7 +1144,7 @@ async def credential_exchange_send_bound_offer(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - _logger.exception("Error preparing bound credential offer") + LOGGER.exception("Error preparing bound credential offer") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1218,11 +1193,6 @@ async def credential_exchange_send_free_request(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -1278,7 +1248,7 @@ async def credential_exchange_send_free_request(request: web.BaseRequest): StorageError, V20CredManagerError, ) as err: - _logger.exception("Error preparing free credential request") + LOGGER.exception("Error preparing free credential request") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1323,11 +1293,6 @@ async def credential_exchange_send_bound_request(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) outbound_handler = request["outbound_message_router"] try: @@ -1399,7 +1364,7 @@ async def credential_exchange_send_bound_request(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - _logger.exception("Error preparing bound credential request") + LOGGER.exception("Error preparing bound credential request") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1446,11 +1411,6 @@ async def credential_exchange_issue(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) outbound_handler = request["outbound_message_router"] body = await request.json() @@ -1497,7 +1457,7 @@ async def credential_exchange_issue(request: web.BaseRequest): V20CredFormatError, V20CredManagerError, ) as err: - _logger.exception("Error preparing issued credential") + LOGGER.exception("Error preparing issued credential") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) @@ -1544,11 +1504,6 @@ async def credential_exchange_store(request: web.BaseRequest): context: AdminRequestContext = request["context"] profile = context.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) outbound_handler = request["outbound_message_router"] try: @@ -1588,7 +1543,7 @@ async def credential_exchange_store(request: web.BaseRequest): StorageError, V20CredManagerError, ) as err: # treat failure to store as mangled on receipt hence protocol error - _logger.exception("Error storing issued credential") + LOGGER.exception("Error storing issued credential") if cred_ex_record: async with profile.session() as session: await cred_ex_record.save_error_state(session, reason=err.roll_up) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py index 0c76972f94..b1ed8216ea 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/tests/test_manager.py @@ -1280,33 +1280,25 @@ async def test_send_cred_ack(self): trace=False, auto_remove=True, ) - mock_logger = async_mock.MagicMock( - warning=async_mock.MagicMock(), - exception=async_mock.MagicMock(), - ) - self.profile.settings["log.file"] = "test.log" - self.profile.settings["wallet.id"] = "test123" + with async_mock.patch.object( V20CredExRecord, "save", autospec=True ) as mock_save_ex, async_mock.patch.object( V20CredExRecord, "delete_record", autospec=True ) as mock_delete_ex, async_mock.patch.object( - test_module, - "get_adapted_logger_inst", - async_mock.MagicMock(return_value=mock_logger), - ): + test_module.LOGGER, "exception", async_mock.MagicMock() + ) as mock_log_exception, async_mock.patch.object( + test_module.LOGGER, "warning", async_mock.MagicMock() + ) as mock_log_warning: mock_delete_ex.side_effect = test_module.StorageError() - manager = V20CredManager(self.profile) - (_, ack) = await manager.send_cred_ack(stored_exchange) + (_, ack) = await self.manager.send_cred_ack(stored_exchange) assert ack._thread - assert ( - mock_logger.exception.call_count == 1 - ) # cover exception log-and-continue - assert mock_logger.warning.call_count == 1 # no BaseResponder + mock_log_exception.assert_called_once() # cover exception log-and-continue + mock_log_warning.assert_called_once() # no BaseResponder mock_responder = MockResponder() # cover with responder self.context.injector.bind_instance(BaseResponder, mock_responder) - (cx_rec, ack) = await manager.send_cred_ack(stored_exchange) + (cx_rec, ack) = await self.manager.send_cred_ack(stored_exchange) assert ack._thread assert cx_rec.state == V20CredExRecord.STATE_DONE diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py index cfb2da0309..9602d5ce7d 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/problem_report_handler.py @@ -1,6 +1,5 @@ """OOB Problem Report Message Handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -22,17 +21,12 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( f"OOBProblemReportMessageHandler called with context {context}" ) assert isinstance(context.message, OOBProblemReport) + profile = context.profile mgr = OutOfBandManager(profile) try: await mgr.receive_problem_report( diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py index 9e29ceec38..ae19d16441 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_accept_handler.py @@ -1,6 +1,5 @@ """Handshake Reuse Accepted Message Handler under RFC 0434.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,17 +18,12 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( f"HandshakeReuseAcceptMessageHandler called with context {context}" ) assert isinstance(context.message, HandshakeReuseAccept) + profile = context.profile mgr = OutOfBandManager(profile) try: await mgr.receive_reuse_accepted_message( diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py index db558cd061..a312a2af1f 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/reuse_handler.py @@ -1,6 +1,5 @@ """Handshake Reuse Message Handler under RFC 0434.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -19,17 +18,12 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: Request context responder: Responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( f"HandshakeReuseMessageHandler called with context {context}" ) assert isinstance(context.message, HandshakeReuse) + profile = context.profile mgr = OutOfBandManager(profile) try: await mgr.receive_reuse_message( diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/manager.py b/aries_cloudagent/protocols/out_of_band/v1_0/manager.py index b59cb6df8f..007b43a675 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/manager.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/manager.py @@ -6,12 +6,12 @@ from typing import Mapping, Optional, Sequence, Union, Text import uuid + from ....messaging.decorators.service_decorator import ServiceDecorator from ....core.event_bus import EventBus from ....core.util import get_version_from_message from ....connections.base_manager import BaseConnectionManager from ....connections.models.conn_record import ConnRecord -from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.oob_processor import OobMessageProcessor from ....core.profile import Profile @@ -63,11 +63,6 @@ def __init__(self, profile: Profile): profile: The profile for this out of band manager """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) super().__init__(self._profile) @property @@ -464,7 +459,7 @@ async def receive_invitation( if ( public_did is not None and use_existing_connection ): # invite has public DID: seek existing connection - self._logger.debug( + LOGGER.debug( "Trying to find existing connection for oob invitation with " f"did {public_did}" ) @@ -487,7 +482,7 @@ async def receive_invitation( oob_record, conn_rec, get_version_from_message(invitation) ) - self._logger.warning( + LOGGER.warning( f"Connection reuse request finished with state {oob_record.state}" ) @@ -508,7 +503,7 @@ async def receive_invitation( mediation_id=mediation_id, service_accept=service_accept, ) - self._logger.debug( + LOGGER.debug( f"Performed handshake with connection {oob_record.connection_id}" ) # re-fetch connection record @@ -532,7 +527,7 @@ async def receive_invitation( # Handle any attachments if invitation.requests_attach: - self._logger.debug( + LOGGER.debug( f"Process attached messages for oob exchange {oob_record.oob_id} " f"(connection_id {oob_record.connection_id})" ) @@ -584,9 +579,9 @@ async def _process_request_attach(self, oob_record: OobRecord): service = oob_record.invitation.services[0] their_service = await self._service_decorator_from_service(service) if their_service: - self._logger.debug("Found service for oob record %s", their_service) + LOGGER.debug("Found service for oob record %s", their_service) else: - self._logger.debug("No service decorator obtained from %s", service) + LOGGER.debug("No service decorator obtained from %s", service) await message_processor.handle_message( self.profile, messages, oob_record=oob_record, their_service=their_service @@ -631,7 +626,7 @@ async def _service_decorator_from_service( routing_keys=routing_keys, ) else: - self._logger.warning( + LOGGER.warning( "Unexpected type `%s` passed to `_service_decorator_from_service`", type(service), ) @@ -677,11 +672,9 @@ async def _wait_for_state() -> OobRecord: ]: return oob_record - self._logger.debug( - f"Wait for oob {oob_id} to receive reuse accepted mesage" - ) + LOGGER.debug(f"Wait for oob {oob_id} to receive reuse accepted mesage") event = await await_event - self._logger.debug("Received reuse response message") + LOGGER.debug("Received reuse response message") return OobRecord.deserialize(event.payload) try: @@ -703,7 +696,7 @@ async def _wait_for_conn_rec_active( "^acapy::record::connections::(active|completed|response)$" ) - self._logger.debug(f"Wait for connection {connection_id} to become active") + LOGGER.debug(f"Wait for connection {connection_id} to become active") async def _wait_for_state() -> ConnRecord: event = self.profile.inject(EventBus) @@ -722,9 +715,7 @@ async def _wait_for_state() -> ConnRecord: if conn_record.is_ready: return conn_record - self._logger.debug( - f"Wait for connection {connection_id} to become active" - ) + LOGGER.debug(f"Wait for connection {connection_id} to become active") # Wait for connection record to be in state event = await await_event return ConnRecord.deserialize(event.payload) @@ -736,9 +727,7 @@ async def _wait_for_state() -> ConnRecord: ) except asyncio.TimeoutError: - self._logger.warning( - f"Connection for connection_id {connection_id} not ready" - ) + LOGGER.warning(f"Connection for connection_id {connection_id} not ready") return None async def _handle_hanshake_reuse( @@ -751,7 +740,7 @@ async def _handle_hanshake_reuse( # Wait for the reuse accepted message oob_record = await self._wait_for_reuse_response(oob_record.oob_id) - self._logger.debug( + LOGGER.debug( f"Oob reuse for oob id {oob_record.oob_id} with connection " f"{oob_record.connection_id} finished with state {oob_record.state}" ) @@ -836,7 +825,7 @@ async def _perform_handshake( } ) - self._logger.debug(f"Creating connection with public did {public_did}") + LOGGER.debug(f"Creating connection with public did {public_did}") conn_record = None for protocol in supported_handshake_protocols: diff --git a/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py b/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py index 4a98d73fa7..46492d8e87 100644 --- a/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py +++ b/aries_cloudagent/protocols/present_proof/dif/pres_exch_handler.py @@ -23,7 +23,6 @@ from ....core.error import BaseError from ....core.profile import Profile -from ....config.logging import get_adapted_logger_inst from ....storage.vc_holder.vc_record import VCRecord from ....vc.ld_proofs import ( Ed25519Signature2018, @@ -59,13 +58,13 @@ PresentationSubmission, ) -LOGGER = logging.getLogger(__name__) PRESENTATION_SUBMISSION_JSONLD_CONTEXT = ( "https://identity.foundation/presentation-exchange/submission/v1" ) PRESENTATION_SUBMISSION_JSONLD_TYPE = "PresentationSubmission" PYTZ_TIMEZONE_PATTERN = re.compile(r"(([a-zA-Z]+)(?:\/)([a-zA-Z]+))") LIST_INDEX_PATTERN = re.compile(r"\[(\W+)\]|\[(\d+)\]") +LOGGER = logging.getLogger(__name__) class DIFPresExchError(BaseError): @@ -112,11 +111,6 @@ def __init__( self.proof_type = proof_type self.is_holder = False self.reveal_doc_frame = reveal_doc - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self.profile.settings.get("log.file"), - wallet_id=self.profile.settings.get("wallet.id"), - ) async def _get_issue_suite( self, @@ -791,7 +785,7 @@ def exclusive_minimum_check(self, val: any, _filter: Filter) -> bool: val = self.is_numeric(val) return val > _filter.exclusive_min except DIFPresExchError as err: - self._logger.error(err) + LOGGER.error(err) return False except (TypeError, ValueError, ParserError): return False @@ -821,7 +815,7 @@ def exclusive_maximum_check(self, val: any, _filter: Filter) -> bool: val = self.is_numeric(val) return val < _filter.exclusive_max except DIFPresExchError as err: - self._logger.error(err) + LOGGER.error(err) return False except (TypeError, ValueError, ParserError): return False @@ -851,7 +845,7 @@ def maximum_check(self, val: any, _filter: Filter) -> bool: val = self.is_numeric(val) return val <= _filter.maximum except DIFPresExchError as err: - self._logger.error(err) + LOGGER.error(err) return False except (TypeError, ValueError, ParserError): return False @@ -881,7 +875,7 @@ def minimum_check(self, val: any, _filter: Filter) -> bool: val = self.is_numeric(val) return val >= _filter.minimum except DIFPresExchError as err: - self._logger.error(err) + LOGGER.error(err) return False except (TypeError, ValueError, ParserError): return False diff --git a/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py b/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py index c21fc57f0f..4bff88cc89 100644 --- a/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py +++ b/aries_cloudagent/protocols/present_proof/indy/pres_exch_handler.py @@ -5,7 +5,6 @@ from typing import Union, Tuple -from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....indy.holder import IndyHolder, IndyHolderError @@ -39,11 +38,6 @@ def __init__( """Initialize PresExchange Handler.""" super().__init__() self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) async def return_presentation( self, @@ -89,7 +83,7 @@ async def return_presentation( if not credentials[req_item["cred_id"]].get( "rev_reg_id" ) and req_item.pop("timestamp", None): - self._logger.info( + LOGGER.info( f"Removed superfluous timestamp from requested_credentials {r} " f"{reft} for non-revocable credential {req_item['cred_id']}" ) @@ -196,7 +190,7 @@ async def return_presentation( ) ) except IndyHolderError as e: - self._logger.error( + LOGGER.error( f"Failed to create revocation state: {e.error_code}, {e.message}" ) raise e diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py index cb08a48828..6a3dfa9eef 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_ack_handler.py @@ -1,6 +1,5 @@ """Presentation ack message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -22,12 +21,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("PresentationAckHandler called with context %s", context) assert isinstance(context.message, PresentationAck) self._logger.info( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py index 270c9b0b1b..7aa96f7f27 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_handler.py @@ -1,6 +1,5 @@ """Presentation message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -29,11 +28,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("PresentationHandler called with context %s", context) assert isinstance(context.message, Presentation) self._logger.info( diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py index b49651d8fc..56ca1a6848 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_problem_report_handler.py @@ -1,6 +1,5 @@ """Presentation problem report message handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -20,12 +19,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "Present-proof v1.0 problem report handler called with context %s", context, diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py index c202c9dd70..d513123258 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_proposal_handler.py @@ -1,6 +1,5 @@ """Presentation proposal message handler.""" -from .....config.logging import get_adapted_logger_inst from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.models.base import BaseModelError @@ -28,11 +27,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "PresentationProposalHandler called with context %s", context ) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py index f08fc385f7..a34cdde4cd 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/presentation_request_handler.py @@ -1,6 +1,5 @@ """Presentation request message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolder, IndyHolderError from .....indy.models.xform import indy_proof_req_preview2indy_requested_creds @@ -33,11 +32,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("PresentationRequestHandler called with context %s", context) assert isinstance(context.message, PresentationRequest) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/manager.py b/aries_cloudagent/protocols/present_proof/v1_0/manager.py index a58ea8787a..b5a85278f9 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/manager.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/manager.py @@ -4,17 +4,14 @@ import logging from typing import Optional +from ...out_of_band.v1_0.models.oob_record import OobRecord from ....connections.models.conn_record import ConnRecord -from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....indy.verifier import IndyVerifier from ....messaging.decorators.attach_decorator import AttachDecorator from ....messaging.responder import BaseResponder from ....storage.error import StorageNotFoundError - -from ...out_of_band.v1_0.models.oob_record import OobRecord - from ..indy.pres_exch_handler import IndyPresExchHandler from .messages.presentation_ack import PresentationAck @@ -46,11 +43,6 @@ def __init__(self, profile: Profile): """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) async def create_exchange_for_proposal( self, @@ -477,7 +469,7 @@ async def send_presentation_ack( except StorageNotFoundError: # This can happen in AIP1 style connectionless exchange. ACA-PY only # supported this for receiving a presentation - self._logger.error( + LOGGER.error( "Unable to send connectionless presentation ack without associated " "oob record. This can happen if proof request was sent without " "wrapping it in an out of band invitation (AIP1-style)." @@ -506,7 +498,7 @@ async def send_presentation_ack( async with self._profile.session() as session: await presentation_exchange_record.delete_record(session) else: - self._logger.warning( + LOGGER.warning( "Configuration has no BaseResponder: cannot ack presentation on %s", presentation_exchange_record.thread_id, ) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py b/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py index 6d3858c27b..a32c1355eb 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/models/presentation_exchange.py @@ -5,7 +5,6 @@ from marshmallow import fields, validate -from .....config.logging import get_adapted_logger_inst from .....core.profile import ProfileSession from .....indy.models.proof import IndyProof, IndyProofSchema from .....indy.models.proof_request import IndyProofRequest, IndyProofRequestSchema @@ -177,12 +176,7 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - profile = session.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + if self._last_state == state: # already done return @@ -198,7 +192,7 @@ async def save_error_state( log_override=log_override, ) except StorageError as err: - _logger.exception(err) + LOGGER.exception(err) # Override async def emit_event(self, session: ProfileSession, payload: Any = None): diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py index 6adbbaa2cf..1d8a2e5d07 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/handler.py @@ -4,7 +4,6 @@ from typing import Tuple -from .....config.logging import get_adapted_logger_inst from .....core.error import BaseError from .....core.profile import Profile from .....messaging.decorators.attach_decorator import AttachDecorator @@ -14,6 +13,7 @@ from ..models.pres_exchange import V20PresExRecord LOGGER = logging.getLogger(__name__) + PresFormatAttachment = Tuple[V20PresFormat, AttachDecorator] @@ -30,11 +30,6 @@ def __init__(self, profile: Profile): """Initialize PresExchange Handler.""" super().__init__() self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) @property def profile(self) -> Profile: diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py index ad71766dfc..2534a65c4f 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_ack_handler.py @@ -1,6 +1,5 @@ """Presentation ack message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.request_context import RequestContext @@ -22,12 +21,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: responder callback """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("V20PresAckHandler called with context %s", context) assert isinstance(context.message, V20PresAck) self._logger.info( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py index 2ee7682ae5..9a93d68cc0 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_handler.py @@ -1,6 +1,5 @@ """Presentation message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException @@ -28,12 +27,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("V20PresHandler called with context %s", context) assert isinstance(context.message, V20Pres) self._logger.info( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py index 2e2f150d5f..32c5e23e0a 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_problem_report_handler.py @@ -1,6 +1,5 @@ """Presentation problem report message handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -20,12 +19,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): context: request context responder: responder callback """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "Present-proof v2.0 problem report handler called with context %s", context, diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py index bdd2fa6f8b..23b16c0ebf 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_proposal_handler.py @@ -1,6 +1,5 @@ """Presentation proposal message handler.""" -from .....config.logging import get_adapted_logger_inst from .....ledger.error import LedgerError from .....messaging.base_handler import BaseHandler, HandlerException from .....messaging.models.base import BaseModelError @@ -27,12 +26,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("V20PresProposalHandler called with context %s", context) assert isinstance(context.message, V20PresProposal) self._logger.info( @@ -50,6 +44,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): "Connection used for presentation proposal not ready" ) + profile = context.profile pres_manager = V20PresManager(profile) pres_ex_record = await pres_manager.receive_pres_proposal( context.message, context.connection_record diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py index 22902a9c26..abac0f7398 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/pres_request_handler.py @@ -1,6 +1,5 @@ """Presentation request message handler.""" -from .....config.logging import get_adapted_logger_inst from .....core.oob_processor import OobMessageProcessor from .....indy.holder import IndyHolderError from .....ledger.error import LedgerError @@ -32,12 +31,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): """ r_time = get_timer() - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("V20PresRequestHandler called with context %s", context) assert isinstance(context.message, V20PresRequest) self._logger.info( @@ -66,6 +60,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): else None ) + profile = context.profile pres_manager = V20PresManager(profile) # Get pres ex record (holder initiated via proposal) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/manager.py b/aries_cloudagent/protocols/present_proof/v2_0/manager.py index 43dafbbec4..083dcac5ac 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/manager.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/manager.py @@ -4,14 +4,12 @@ from typing import Optional, Tuple +from ...out_of_band.v1_0.models.oob_record import OobRecord from ....connections.models.conn_record import ConnRecord -from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....messaging.responder import BaseResponder -from ...out_of_band.v1_0.models.oob_record import OobRecord - from .messages.pres import V20Pres from .messages.pres_ack import V20PresAck from .messages.pres_format import V20PresFormat @@ -20,6 +18,7 @@ from .messages.pres_request import V20PresRequest from .models.pres_exchange import V20PresExRecord + LOGGER = logging.getLogger(__name__) @@ -38,11 +37,6 @@ def __init__(self, profile: Profile): """ self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) async def create_exchange_for_proposal( self, @@ -446,7 +440,7 @@ async def send_pres_ack( async with self._profile.session() as session: await pres_ex_record.delete_record(session) else: - self._logger.warning( + LOGGER.warning( "Configuration has no BaseResponder: cannot ack presentation on %s", pres_ex_record.thread_id, ) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py b/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py index ae429f35a4..06f43036ea 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/models/pres_exchange.py @@ -5,7 +5,6 @@ from marshmallow import Schema, fields, validate -from .....config.logging import get_adapted_logger_inst from .....core.profile import ProfileSession from .....messaging.models.base_record import BaseExchangeRecord, BaseExchangeSchema from .....messaging.valid import UUID4_EXAMPLE @@ -163,12 +162,7 @@ async def save_error_state( log_params: Additional parameters to log override: Override configured logging regimen, print to stderr instead """ - profile = session.profile - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + if self._last_state == state: # already done return @@ -184,7 +178,7 @@ async def save_error_state( log_override=log_override, ) except StorageError as err: - _logger.exception(err) + LOGGER.exception(err) # Override async def emit_event(self, session: ProfileSession, payload: Any = None): diff --git a/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py b/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py index 3d506447df..ba27e20f45 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/models/tests/test_record.py @@ -120,21 +120,17 @@ async def test_record(self): async def test_save_error_state(self): session = InMemoryProfile.test_session() record = V20PresExRecord(state=None) - profile = session.profile - profile.settings["log.file"] = "test_file.log" - profile.settings["wallet.id"] = "test123" assert record._last_state is None await record.save_error_state(session) # cover short circuit + record.state = V20PresExRecord.STATE_PROPOSAL_RECEIVED await record.save(session) - mock_logger = async_mock.MagicMock(exception=async_mock.MagicMock()) + with async_mock.patch.object( record, "save", async_mock.CoroutineMock() ) as mock_save, async_mock.patch.object( - test_module, - "get_adapted_logger_inst", - async_mock.MagicMock(return_value=mock_logger), - ): + test_module.LOGGER, "exception", async_mock.MagicMock() + ) as mock_log_exc: mock_save.side_effect = test_module.StorageError() await record.save_error_state(session, reason="testing") - assert mock_logger.exception.call_count == 1 + mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/problem_report/v1_0/handler.py b/aries_cloudagent/protocols/problem_report/v1_0/handler.py index 9949c5170c..99e1c1d179 100644 --- a/aries_cloudagent/protocols/problem_report/v1_0/handler.py +++ b/aries_cloudagent/protocols/problem_report/v1_0/handler.py @@ -1,6 +1,5 @@ """Generic problem report handler.""" -from ....config.logging import get_adapted_logger_inst from ....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,12 +20,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: Responder used to reply """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("ProblemReportHandler called with context %s", context) assert isinstance(context.message, ProblemReport) diff --git a/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py b/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py index cf0e1733ec..366cbcd6c2 100644 --- a/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py +++ b/aries_cloudagent/protocols/revocation_notification/v1_0/handlers/revoke_handler.py @@ -1,6 +1,5 @@ """Handler for revoke message.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -17,12 +16,6 @@ class RevokeHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle revoke message.""" assert isinstance(context.message, Revoke) - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "Received notification of revocation for cred issued in thread %s " "with comment: %s", diff --git a/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py b/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py index f3a2d820d2..cdefdaf642 100644 --- a/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py +++ b/aries_cloudagent/protocols/revocation_notification/v1_0/routes.py @@ -2,7 +2,6 @@ import logging import re -from ....config.logging import get_adapted_logger_inst from ....core.event_bus import Event, EventBus from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -31,12 +30,7 @@ def register_events(event_bus: EventBus): async def on_revocation_published(profile: Profile, event: Event): """Handle issuer revoke event.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.debug("Sending notification of revocation to recipient: %s", event.payload) + LOGGER.debug("Sending notification of revocation to recipient: %s", event.payload) responder = profile.inject(BaseResponder) crids = event.payload.get("crids") or [] @@ -56,12 +50,12 @@ async def on_revocation_published(profile: Profile, event: Event): ) except StorageNotFoundError: - _logger.info( + LOGGER.info( "No revocation notification record found for revoked credential; " "no notification will be sent" ) except StorageError: - _logger.exception("Failed to retrieve revocation notification record") + LOGGER.exception("Failed to retrieve revocation notification record") async def on_pending_cleared(profile: Profile, event: Event): diff --git a/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py b/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py index 188530affd..f2ffafe7e0 100644 --- a/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py +++ b/aries_cloudagent/protocols/revocation_notification/v2_0/handlers/revoke_handler.py @@ -1,6 +1,5 @@ """Handler for revoke message.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import BaseHandler from .....messaging.request_context import RequestContext from .....messaging.responder import BaseResponder @@ -17,12 +16,6 @@ class RevokeHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Handle revoke message.""" assert isinstance(context.message, Revoke) - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug( "Received notification of revocation for %s cred %s with comment: %s", context.message.revocation_format, diff --git a/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py b/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py index 7604528e7c..83ba81fe63 100644 --- a/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py +++ b/aries_cloudagent/protocols/revocation_notification/v2_0/routes.py @@ -2,7 +2,6 @@ import logging import re -from ....config.logging import get_adapted_logger_inst from ....core.event_bus import Event, EventBus from ....core.profile import Profile from ....messaging.responder import BaseResponder @@ -31,12 +30,7 @@ def register_events(event_bus: EventBus): async def on_revocation_published(profile: Profile, event: Event): """Handle issuer revoke event.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) - _logger.debug("Sending notification of revocation to recipient: %s", event.payload) + LOGGER.debug("Sending notification of revocation to recipient: %s", event.payload) should_notify = profile.settings.get("revocation.notify", False) responder = profile.inject(BaseResponder) @@ -58,12 +52,12 @@ async def on_revocation_published(profile: Profile, event: Event): ) except StorageNotFoundError: - _logger.info( + LOGGER.info( "No revocation notification record found for revoked credential; " "no notification will be sent" ) except StorageError: - _logger.exception("Failed to retrieve revocation notification record") + LOGGER.exception("Failed to retrieve revocation notification record") async def on_pending_cleared(profile: Profile, event: Event): diff --git a/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py b/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py index 91852a3369..47654fc5b0 100644 --- a/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py +++ b/aries_cloudagent/protocols/routing/v1_0/handlers/forward_handler.py @@ -2,7 +2,6 @@ import json -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -19,12 +18,6 @@ class ForwardHandler(BaseHandler): async def handle(self, context: RequestContext, responder: BaseResponder): """Message handler implementation.""" - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug("ForwardHandler called with context %s", context) assert isinstance(context.message, Forward) diff --git a/aries_cloudagent/protocols/routing/v1_0/manager.py b/aries_cloudagent/protocols/routing/v1_0/manager.py index cafa757e87..a5fe48c924 100644 --- a/aries_cloudagent/protocols/routing/v1_0/manager.py +++ b/aries_cloudagent/protocols/routing/v1_0/manager.py @@ -4,7 +4,6 @@ import logging from typing import Sequence -from ....config.logging import get_adapted_logger_inst from ....core.error import BaseError from ....core.profile import Profile from ....storage.error import ( @@ -14,7 +13,9 @@ from .models.route_record import RouteRecord + LOGGER = logging.getLogger(__name__) + RECIP_ROUTE_PAUSE = 0.1 RECIP_ROUTE_RETRY = 10 @@ -41,11 +42,6 @@ def __init__(self, profile: Profile): self._profile = profile if not profile: raise RoutingManagerError("Missing profile") - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) async def get_recipient(self, recip_verkey: str) -> RouteRecord: """Resolve the recipient for a verkey. @@ -64,28 +60,20 @@ async def get_recipient(self, recip_verkey: str) -> RouteRecord: record = None while not record: try: - self._logger.info( - ">>> fetching routing record for verkey: " + recip_verkey - ) + LOGGER.info(">>> fetching routing record for verkey: " + recip_verkey) async with self._profile.session() as session: record = await RouteRecord.retrieve_by_recipient_key( session, recip_verkey ) - self._logger.info( - ">>> FOUND routing record for verkey: " + recip_verkey - ) + LOGGER.info(">>> FOUND routing record for verkey: " + recip_verkey) return record except StorageDuplicateError: - self._logger.info( - ">>> DUPLICATE routing record for verkey: " + recip_verkey - ) + LOGGER.info(">>> DUPLICATE routing record for verkey: " + recip_verkey) raise RouteNotFoundError( f"More than one route record found with recipient key: {recip_verkey}" ) except StorageNotFoundError: - self._logger.info( - ">>> NOT FOUND routing record for verkey: " + recip_verkey - ) + LOGGER.info(">>> NOT FOUND routing record for verkey: " + recip_verkey) i += 1 if i > RECIP_ROUTE_RETRY: raise RouteNotFoundError( @@ -157,7 +145,7 @@ async def create_route_record( ) if not recipient_key: raise RoutingManagerError("Missing recipient_key") - self._logger.info(">>> creating routing record for verkey: " + recipient_key) + LOGGER.info(">>> creating routing record for verkey: " + recipient_key) route = RouteRecord( connection_id=client_connection_id, wallet_id=internal_wallet_id, @@ -165,5 +153,5 @@ async def create_route_record( ) async with self._profile.session() as session: await route.save(session, reason="Created new route") - self._logger.info(">>> CREATED routing record for verkey: " + recipient_key) + LOGGER.info(">>> CREATED routing record for verkey: " + recipient_key) return route diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py index 0828c8bb2a..7963109e43 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_handler.py @@ -1,6 +1,5 @@ """Ping handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -22,12 +21,6 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: Responder used to reply """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) self._logger.debug(f"PingHandler called with context {context}") assert isinstance(context.message, Ping) diff --git a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py index e002c08ca8..c66c68158a 100644 --- a/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py +++ b/aries_cloudagent/protocols/trustping/v1_0/handlers/ping_response_handler.py @@ -1,6 +1,5 @@ """Ping response handler.""" -from .....config.logging import get_adapted_logger_inst from .....messaging.base_handler import ( BaseHandler, BaseResponder, @@ -21,12 +20,7 @@ async def handle(self, context: RequestContext, responder: BaseResponder): responder: Responder used to reply """ - profile = context.profile - self._logger = get_adapted_logger_inst( - logger=self._logger, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + self._logger.debug("PingResponseHandler called with context: %s", context) assert isinstance(context.message, PingResponse) diff --git a/aries_cloudagent/resolver/default/universal.py b/aries_cloudagent/resolver/default/universal.py index 19b77a8fba..2efee46009 100644 --- a/aries_cloudagent/resolver/default/universal.py +++ b/aries_cloudagent/resolver/default/universal.py @@ -7,12 +7,11 @@ import aiohttp from ...config.injection_context import InjectionContext -from ...config.logging import get_adapted_logger_inst from ...core.profile import Profile from ..base import BaseDIDResolver, DIDNotFound, ResolverError, ResolverType -DEFAULT_ENDPOINT = "https://dev.uniresolver.io/1.0" LOGGER = logging.getLogger(__name__) +DEFAULT_ENDPOINT = "https://dev.uniresolver.io/1.0" def _compile_supported_did_regex(patterns: Iterable[Union[str, Pattern]]): @@ -85,17 +84,13 @@ async def _resolve( service_accept: Optional[Sequence[Text]] = None, ) -> dict: """Resolve DID through remote universal resolver.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=_profile.settings.get("log.file"), - wallet_id=_profile.settings.get("wallet.id"), - ) + async with aiohttp.ClientSession(headers=self.__default_headers) as session: async with session.get(f"{self._endpoint}/identifiers/{did}") as resp: if resp.status == 200: doc = await resp.json() did_doc = doc["didDocument"] - _logger.info("Retrieved doc: %s", did_doc) + LOGGER.info("Retrieved doc: %s", did_doc) return did_doc if resp.status == 404: raise DIDNotFound(f"{did} not found by {self.__class__.__name__}") diff --git a/aries_cloudagent/revocation/indy.py b/aries_cloudagent/revocation/indy.py index 6b571ae3b9..622ef3f583 100644 --- a/aries_cloudagent/revocation/indy.py +++ b/aries_cloudagent/revocation/indy.py @@ -3,7 +3,6 @@ from typing import Optional, Sequence, Tuple from uuid import uuid4 -from ..config.logging import get_adapted_logger_inst from ..core.profile import Profile from ..ledger.base import BaseLedger from ..ledger.multiple_ledger.ledger_requests_executor import ( @@ -39,11 +38,6 @@ class IndyRevocation: def __init__(self, profile: Profile): """Initialize the IndyRevocation instance.""" self._profile = profile - self._logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=self._profile.settings.get("log.file"), - wallet_id=self._profile.settings.get("wallet.id"), - ) async def init_issuer_registry( self, @@ -131,9 +125,9 @@ async def decommission_registry(self, cred_def_id: str): ) for rec in recs: - self._logger.debug(f"decommission {rec.state} rev. reg.") - self._logger.debug(f"revoc_reg_id: {rec.revoc_reg_id}") - self._logger.debug(f"cred_def_id: {cred_def_id}") + LOGGER.debug(f"decommission {rec.state} rev. reg.") + LOGGER.debug(f"revoc_reg_id: {rec.revoc_reg_id}") + LOGGER.debug(f"cred_def_id: {cred_def_id}") # decommission active registry, we need to init a replacement init = IssuerRevRegRecord.STATE_ACTIVE == rec.state await self._set_registry_status( diff --git a/aries_cloudagent/revocation/models/issuer_rev_reg_record.py b/aries_cloudagent/revocation/models/issuer_rev_reg_record.py index 541e0daf49..ccb47e63ed 100644 --- a/aries_cloudagent/revocation/models/issuer_rev_reg_record.py +++ b/aries_cloudagent/revocation/models/issuer_rev_reg_record.py @@ -12,7 +12,6 @@ from marshmallow import fields, validate -from ...config.logging import get_adapted_logger_inst from ...core.profile import Profile, ProfileSession from ...indy.issuer import IndyIssuer, IndyIssuerError from ...indy.models.revocation import ( @@ -43,6 +42,7 @@ from .revocation_registry import RevocationRegistry DEFAULT_REGISTRY_SIZE = 1000 + LOGGER = logging.getLogger(__name__) @@ -184,11 +184,6 @@ def _check_url(self, url) -> None: async def generate_registry(self, profile: Profile): """Create the revocation registry definition and tails file.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) if not self.tag: self.tag = self._id or str(uuid.uuid4()) @@ -202,7 +197,7 @@ async def generate_registry(self, profile: Profile): issuer = profile.inject(IndyIssuer) tails_hopper_dir = indy_client_dir(join("tails", ".hopper"), create=True) - _logger.debug("Creating revocation registry with size: %d", self.max_cred_num) + LOGGER.debug("Creating revocation registry with size: %d", self.max_cred_num) try: ( @@ -290,11 +285,6 @@ async def send_entry( endorser_did: str = None, ) -> dict: """Send a registry entry to the ledger.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) if not ( self.revoc_reg_id and self.revoc_def_type @@ -335,27 +325,27 @@ async def send_entry( # Ledger rejected transaction request: client request invalid: # InvalidClientRequest(...) # In this scenario we try to post a correction - _logger.warn("Retry ledger update/fix due to error") - _logger.warn(err) + LOGGER.warn("Retry ledger update/fix due to error") + LOGGER.warn(err) (_, _, res) = await self.fix_ledger_entry( profile, True, ledger.pool.genesis_txns, ) rev_entry_res = {"result": res} - _logger.warn("Ledger update/fix applied") + LOGGER.warn("Ledger update/fix applied") elif "InvalidClientTaaAcceptanceError" in err.roll_up: # if no write access (with "InvalidClientTaaAcceptanceError") # e.g. aries_cloudagent.ledger.error.LedgerTransactionError: # Ledger rejected transaction request: client request invalid: # InvalidClientTaaAcceptanceError(...) - _logger.error("Ledger update failed due to TAA issue") - _logger.error(err) + LOGGER.error("Ledger update failed due to TAA issue") + LOGGER.error(err) raise err else: # not sure what happened, raise an error - _logger.error("Ledger update failed due to unknown issue") - _logger.error(err) + LOGGER.error("Ledger update failed due to unknown issue") + LOGGER.error(err) raise err if self.state == IssuerRevRegRecord.STATE_POSTED: self.state = IssuerRevRegRecord.STATE_ACTIVE # initial entry activates @@ -374,11 +364,6 @@ async def fix_ledger_entry( ) -> Tuple[dict, dict, dict]: """Fix the ledger entry to match wallet-recorded credentials.""" # get rev reg delta (revocations published to ledger) - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) ledger = profile.inject(BaseLedger) async with ledger: (rev_reg_delta, _) = await ledger.get_revoc_reg_delta(self.revoc_reg_id) @@ -402,12 +387,12 @@ async def fix_ledger_entry( # await rec.set_state(session, IssuerCredRevRecord.STATE_ISSUED) rec_count += 1 - _logger.debug(">>> fixed entry recs count = %s", rec_count) - _logger.debug( + LOGGER.debug(">>> fixed entry recs count = %s", rec_count) + LOGGER.debug( ">>> rev_reg_record.revoc_reg_entry.value: %s", self.revoc_reg_entry.value, ) - _logger.debug( + LOGGER.debug( '>>> rev_reg_delta.get("value"): %s', rev_reg_delta.get("value") ) @@ -427,7 +412,7 @@ async def fix_ledger_entry( ) recovery_txn = json.loads(calculated_txn.to_json()) - _logger.debug(">>> apply_ledger_update = %s", apply_ledger_update) + LOGGER.debug(">>> apply_ledger_update = %s", apply_ledger_update) if apply_ledger_update: ledger = session.inject_or(BaseLedger) if not ledger: diff --git a/aries_cloudagent/wallet/routes.py b/aries_cloudagent/wallet/routes.py index 2ca3a23306..20dd8727c1 100644 --- a/aries_cloudagent/wallet/routes.py +++ b/aries_cloudagent/wallet/routes.py @@ -10,7 +10,6 @@ from marshmallow import fields, validate from ..admin.request_context import AdminRequestContext -from ..config.logging import get_adapted_logger_inst from ..connections.models.conn_record import ConnRecord from ..core.event_bus import Event, EventBus from ..core.profile import Profile @@ -1049,11 +1048,7 @@ def register_events(event_bus: EventBus): async def on_register_nym_event(profile: Profile, event: Event): """Handle any events we need to support.""" - _logger = get_adapted_logger_inst( - logger=LOGGER, - log_file=profile.settings.get("log.file"), - wallet_id=profile.settings.get("wallet.id"), - ) + # after the nym record is written, promote to wallet public DID if is_author_role(profile) and profile.context.settings.get_value( "endorser.auto_promote_author_did" @@ -1066,7 +1061,7 @@ async def on_register_nym_event(profile: Profile, event: Event): ) except Exception as err: # log the error, but continue - _logger.exception( + LOGGER.exception( "Error promoting to public DID: %s", err, ) @@ -1079,8 +1074,9 @@ async def on_register_nym_event(profile: Profile, event: Event): ) except StorageError as err: # log the error, but continue - _logger.exception( - "Error accepting endorser invitation/configuring endorser connection: %s", + LOGGER.exception( + "Error accepting endorser invitation/configuring endorser" + " connection: %s", err, ) return @@ -1096,7 +1092,7 @@ async def on_register_nym_event(profile: Profile, event: Event): ) except (StorageError, TransactionManagerError) as err: # log the error, but continue - _logger.exception( + LOGGER.exception( "Error creating endorser transaction request: %s", err, ) @@ -1110,7 +1106,7 @@ async def on_register_nym_event(profile: Profile, event: Event): connection_id=connection_id, ) else: - _logger.warning( + LOGGER.warning( "Configuration has no BaseResponder: cannot update " "ATTRIB record on DID: %s", did, diff --git a/demo/runners/agent_container.py b/demo/runners/agent_container.py index e237061b8b..879d01e104 100644 --- a/demo/runners/agent_container.py +++ b/demo/runners/agent_container.py @@ -1322,25 +1322,6 @@ def arg_parser(ident: str = None, port: int = 8020): "('debug', 'info', 'warning', 'error', 'critical')" ), ) - parser.add_argument( - "--log-handler-config", - type=str, - metavar="", - help=( - "Specifies when, interval, backupCount for the TimedRotatingFileHandler." - ), - ) - parser.add_argument( - "--log-fmt-pattern", - type=str, - metavar="", - help="Specifies logging formatter pattern as string.", - ) - parser.add_argument( - "--log-json-fmt", - action="store_true", - help="JSON logging formatter.", - ) return parser @@ -1374,11 +1355,6 @@ async def create_agent_with_args(args, ident: str = None): log_file = args.log_file or os.getenv("ACAPY_LOG_FILE") log_level = args.log_level - log_handler_config = args.log_handler_config or os.getenv( - "ACAPY_LOG_HANDLER_CONFIG" - ) - log_fmt_pattern = args.log_fmt_pattern or os.getenv("ACAPY_LOG_FMT_PATTERN") - log_json_fmt = args.log_json_fmt or False # if we don't have a tails server url then guess it if ("revocation" in args and args.revocation) and not tails_server_base_url: # assume we're running in docker @@ -1457,9 +1433,6 @@ async def create_agent_with_args(args, ident: str = None): taa_accept=args.taa_accept, anoncreds_legacy_revocation=anoncreds_legacy_revocation, log_file=log_file, - log_handler_config=log_handler_config, - log_fmt_pattern=log_fmt_pattern, - log_json_fmt=log_json_fmt, log_level=log_level, ) diff --git a/demo/runners/performance.py b/demo/runners/performance.py index cbbed96d03..9deba03609 100644 --- a/demo/runners/performance.py +++ b/demo/runners/performance.py @@ -139,7 +139,10 @@ async def check_received_creds(self) -> Tuple[int, int]: return pending, total async def update_creds(self): - await self.credential_event.wait() + try: + await self.credential_event.wait() + except asyncio.exceptions.CancelledError: + pass async def check_received_pings(self) -> Tuple[int, int]: while True: @@ -767,25 +770,6 @@ async def check_received_pings(agent, issue_count, pb): "('debug', 'info', 'warning', 'error', 'critical')" ), ) - parser.add_argument( - "--log-handler-config", - type=str, - metavar="", - help=( - "Specifies when, interval, backupCount for the TimedRotatingFileHandler." - ), - ) - parser.add_argument( - "--log-fmt-pattern", - type=str, - metavar="", - help=("Specifies logging formatter pattern as string."), - ) - parser.add_argument( - "--log-json-fmt", - action="store_true", - help=("JSON logging formatter."), - ) args = parser.parse_args() if args.did_exchange and args.mediation: @@ -825,9 +809,6 @@ async def check_received_pings(agent, issue_count, pb): args.wallet_type, args.arg_file, args.log_file, - args.log_handler_config, - args.log_fmt_pattern, - args.log_json_fmt, args.log_level, ) ) diff --git a/demo/runners/support/agent.py b/demo/runners/support/agent.py index 2ee9d7b27d..b040361a5a 100644 --- a/demo/runners/support/agent.py +++ b/demo/runners/support/agent.py @@ -361,26 +361,12 @@ def get_agent_args(self): ("--log-file", self.log_file), ] ) - if self.log_handler_config: - result.extend( - [ - ("--log-handler-config", self.log_handler_config), - ] - ) - if self.log_fmt_pattern: - result.extend( - [ - ("--log-fmt-pattern", self.log_fmt_pattern), - ] - ) if self.log_level: result.extend( [ ("--log-level", self.log_level), ] ) - if self.log_json_fmt: - result.append("--log-json-fmt") if self.aip == 20: result.append("--emit-new-didcomm-prefix") if self.multitenant: diff --git a/demo/runners/support/utils.py b/demo/runners/support/utils.py index 0056686fbf..45ef1b733e 100644 --- a/demo/runners/support/utils.py +++ b/demo/runners/support/utils.py @@ -122,8 +122,10 @@ def output_reader(handle, callback, *args, **kwargs): def log_msg(*msg, color="fg:ansimagenta", **kwargs): - run_in_terminal(lambda: print_ext(*msg, color=color, **kwargs)) - + try: + run_in_terminal(lambda: print_ext(*msg, color=color, **kwargs)) + except AssertionError: + pass def log_json(data, **kwargs): run_in_terminal(lambda: print_json(data, **kwargs)) From 6bdc1119be4d7e3f3a8da81352ecb54bbc35ceb9 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Fri, 8 Sep 2023 18:49:47 +0530 Subject: [PATCH 11/18] cleanup from previous work Signed-off-by: Shaanjot Gill --- aries_cloudagent/config/ledger.py | 2 + aries_cloudagent/config/logging.py | 23 +++--- aries_cloudagent/connections/base_manager.py | 33 ++++---- aries_cloudagent/core/oob_processor.py | 4 +- .../tests/test_problem_report_handler.py | 6 -- ...t_endorsed_transaction_response_handler.py | 18 ----- ...st_refused_transaction_response_handler.py | 18 ----- ...est_transaction_acknowledgement_handler.py | 18 ----- .../tests/test_transaction_cancel_handler.py | 18 ----- .../test_transaction_job_to_send_handler.py | 12 --- .../tests/test_transaction_request_handler.py | 18 ----- .../tests/test_transaction_resend_handler.py | 18 ----- .../endorse_transaction/v1_0/routes.py | 1 + .../tests/test_forward_invitation_handler.py | 18 ----- .../handlers/tests/test_invitation_handler.py | 19 +---- .../tests/test_invitation_request_handler.py | 19 +---- .../tests/test_credential_ack_handler.py | 18 ----- .../tests/test_credential_issue_handler.py | 30 ------- .../tests/test_credential_offer_handler.py | 36 +-------- .../test_credential_problem_report_handler.py | 24 ------ .../tests/test_credential_proposal_handler.py | 36 +-------- .../tests/test_credential_request_handler.py | 42 +--------- .../v1_0/tests/test_manager.py | 4 +- .../v2_0/formats/indy/handler.py | 12 +-- .../v2_0/formats/indy/tests/test_handler.py | 13 ++- .../v2_0/formats/ld_proof/handler.py | 6 +- .../formats/ld_proof/tests/test_handler.py | 13 ++- .../handlers/tests/test_cred_ack_handler.py | 18 ----- .../handlers/tests/test_cred_offer_handler.py | 12 +-- .../tests/test_cred_problem_report_handler.py | 24 ------ .../tests/test_cred_proposal_handler.py | 12 +-- .../tests/test_cred_request_handler.py | 36 +-------- .../v1_0/handlers/tests/test_ack_handler.py | 6 -- .../tests/test_problem_report_handler.py | 22 ++---- .../tests/test_reuse_accept_handler.py | 12 --- .../v1_0/handlers/tests/test_reuse_handler.py | 18 ----- .../tests/test_presentation_ack_handler.py | 18 ----- .../tests/test_presentation_handler.py | 26 ++---- ...est_presentation_problem_report_handler.py | 12 --- .../test_presentation_proposal_handler.py | 38 ++------- .../test_presentation_request_handler.py | 79 ++----------------- .../present_proof/v1_0/tests/test_manager.py | 5 +- .../present_proof/v2_0/formats/dif/handler.py | 9 ++- .../v2_0/formats/dif/tests/test_handler.py | 66 +++++----------- .../v2_0/formats/indy/handler.py | 5 +- .../handlers/tests/test_pres_ack_handler.py | 18 ----- .../v2_0/handlers/tests/test_pres_handler.py | 26 ++---- .../tests/test_pres_problem_report_handler.py | 12 --- .../tests/test_pres_proposal_handler.py | 38 ++------- .../tests/test_pres_request_handler.py | 74 ++--------------- .../present_proof/v2_0/tests/test_manager.py | 5 +- .../handlers/tests/test_forward_handler.py | 20 +---- .../resolver/tests/test_did_resolver.py | 2 +- demo/runners/agent_container.py | 28 +++---- demo/runners/alice.py | 12 +-- demo/runners/faber.py | 12 +-- demo/runners/performance.py | 43 ++++------ demo/runners/support/agent.py | 14 ++-- demo/runners/support/utils.py | 1 + 59 files changed, 209 insertions(+), 993 deletions(-) diff --git a/aries_cloudagent/config/ledger.py b/aries_cloudagent/config/ledger.py index 0007ecdba6..750ba314ff 100644 --- a/aries_cloudagent/config/ledger.py +++ b/aries_cloudagent/config/ledger.py @@ -128,6 +128,7 @@ async def ledger_config( """Perform Indy ledger configuration.""" session = await profile.session() + ledger = session.inject_or(BaseLedger) if not ledger: LOGGER.info("Ledger instance not provided") @@ -251,6 +252,7 @@ async def accept_taa( mechanisms = taa_info["aml_record"]["aml"] mechanism = None + taa_acceptance_mechanism = profile.settings.get("ledger.taa_acceptance_mechanism") taa_acceptance_version = profile.settings.get("ledger.taa_acceptance_version") diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index 7dc6b9be96..953af10144 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -23,7 +23,9 @@ from .banner import Banner DEFAULT_LOGGING_CONFIG_PATH = "aries_cloudagent.config:default_logging_config.ini" -DEFAULT_PER_TENANT_LOGGING_CONFIG_PATH = "./aries_cloudagent/config/default_per_tenant_logging_config.yml" +DEFAULT_PER_TENANT_LOGGING_CONFIG_PATH = ( + "./aries_cloudagent/config/default_per_tenant_logging_config.yml" +) LOG_FORMAT_FILE_ALIAS_PATTERN = ( "%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s" ) @@ -43,10 +45,10 @@ def __init__(self): def filter(self, record): try: wallet_id = context_wallet_id.get() - record.wallet_id= wallet_id + record.wallet_id = wallet_id return True except LookupError: - record.wallet_id= None + record.wallet_id = None return True @@ -94,7 +96,7 @@ def configure( config_path = logging_config_path else: config_path = DEFAULT_LOGGING_CONFIG_PATH - if ".yml" in config_path or ".yaml" in config_path: + if ".yml" in config_path or ".yaml" in config_path: is_dict_config = True with open(config_path, "r") as stream: log_config = yaml.safe_load(stream) @@ -121,9 +123,7 @@ def configure( # Set Json formatter for rotated file handler which # cannot be set with config file. By default this will # be set up. - _handler.setFormatter( - jsonlogger.JsonFormatter(handler_pattern) - ) + _handler.setFormatter(jsonlogger.JsonFormatter(handler_pattern)) # Add context filter to handlers _handler.addFilter(_cf) if not file_handler_set: @@ -134,7 +134,7 @@ def configure( log_file, ) # If configuration is not provided within .ini or dict config file - # then by default the rotated file handler will have interval=7, + # then by default the rotated file handler will have interval=7, # when=d and backupCount=1 configuration timed_file_handler = TimedRotatingFileMultiProcessHandler( filename=file_path, @@ -152,7 +152,7 @@ def configure( # Don't go with rotated file handler when not in multitenant mode. logging.root.handlers.append( logging.FileHandler(log_file, encoding="utf-8") - ) + ) if log_level: log_level = log_level.upper() logging.root.setLevel(log_level) @@ -566,4 +566,7 @@ def doRollover(self): self.stream = self._open() self.release() -logging.handlers.TimedRotatingFileMultiProcessHandler = TimedRotatingFileMultiProcessHandler + +logging.handlers.TimedRotatingFileMultiProcessHandler = ( + TimedRotatingFileMultiProcessHandler +) diff --git a/aries_cloudagent/connections/base_manager.py b/aries_cloudagent/connections/base_manager.py index 247fa3e93d..f1d2ce9fa8 100644 --- a/aries_cloudagent/connections/base_manager.py +++ b/aries_cloudagent/connections/base_manager.py @@ -20,6 +20,7 @@ ) from ..cache.base import BaseCache from ..config.base import InjectionError +from ..config.logging import get_logger_inst from ..core.error import BaseError from ..core.profile import Profile from ..did.did_key import DIDKey @@ -51,8 +52,6 @@ from .models.connection_target import ConnectionTarget from .models.diddoc import DIDDoc, PublicKey, PublicKeyType, Service -LOGGER = logging.getLogger(__name__) - class BaseConnectionManagerError(BaseError): """BaseConnectionManager error.""" @@ -72,6 +71,10 @@ def __init__(self, profile: Profile): """ self._profile = profile self._route_manager = profile.inject(RouteManager) + self._logger: logging.Logger = get_logger_inst( + profile=self._profile, + logger_name=__name__, + ) async def create_did_document( self, @@ -222,7 +225,7 @@ async def add_key_for_did(self, did: str, key: str): except StorageNotFoundError: await storage.add_record(record) except StorageDuplicateError: - LOGGER.warning( + self._logger.warning( "Key already associated with DID: %s; this is likely caused by " "routing keys being erroneously stored in the past", key, @@ -352,10 +355,10 @@ async def resolve_connection_targets( their_label: Optional[str] = None, ) -> List[ConnectionTarget]: """Resolve connection targets for a DID.""" - LOGGER.debug("Resolving connection targets for DID %s", did) + self._logger.debug("Resolving connection targets for DID %s", did) doc, didcomm_services = await self.resolve_didcomm_services(did) - LOGGER.debug("Resolved DID document: %s", doc) - LOGGER.debug("Resolved DIDComm services: %s", didcomm_services) + self._logger.debug("Resolved DID document: %s", doc) + self._logger.debug("Resolved DIDComm services: %s", didcomm_services) targets = [] for service in didcomm_services: try: @@ -380,7 +383,7 @@ async def resolve_connection_targets( ) ) except ResolverError: - LOGGER.exception( + self._logger.exception( "Failed to resolve service details while determining " "connection targets; skipping service" ) @@ -541,7 +544,7 @@ async def fetch_connection_targets( """ if not connection.my_did: - LOGGER.debug("No local DID associated with connection") + self._logger.debug("No local DID associated with connection") return [] async with self._profile.session() as session: @@ -558,7 +561,7 @@ async def fetch_connection_targets( ) if not connection.their_did: - LOGGER.debug("No target DID associated with connection") + self._logger.debug("No target DID associated with connection") return [] return await self.resolve_connection_targets( @@ -589,7 +592,7 @@ async def get_connection_targets( if cache: async with cache.acquire(cache_key) as entry: if entry.result: - LOGGER.debug("Connection targets retrieved from cache") + self._logger.debug("Connection targets retrieved from cache") targets = [ ConnectionTarget.deserialize(row) for row in entry.result ] @@ -606,12 +609,12 @@ async def get_connection_targets( # Only set cache if connection has reached completed state # Otherwise, a replica that participated early in exchange # may have bad data set in cache. - LOGGER.debug("Caching connection targets") + self._logger.debug("Caching connection targets") await entry.set_result( [row.serialize() for row in targets], 3600 ) else: - LOGGER.debug( + self._logger.debug( "Not caching connection targets for connection in " f"state ({connection.state})" ) @@ -797,7 +800,7 @@ async def resolve_inbound_connection( try: receipt.sender_did = await self.find_did_for_key(receipt.sender_verkey) except StorageNotFoundError: - LOGGER.warning( + self._logger.warning( "No corresponding DID found for sender verkey: %s", receipt.sender_verkey, ) @@ -813,13 +816,13 @@ async def resolve_inbound_connection( if "posted" in my_info.metadata and my_info.metadata["posted"] is True: receipt.recipient_did_public = True except InjectionError: - LOGGER.warning( + self._logger.warning( "Cannot resolve recipient verkey, no wallet defined by " "context: %s", receipt.recipient_verkey, ) except WalletNotFoundError: - LOGGER.warning( + self._logger.warning( "No corresponding DID found for recipient verkey: %s", receipt.recipient_verkey, ) diff --git a/aries_cloudagent/core/oob_processor.py b/aries_cloudagent/core/oob_processor.py index c7b29b16d9..c327b6d234 100644 --- a/aries_cloudagent/core/oob_processor.py +++ b/aries_cloudagent/core/oob_processor.py @@ -101,9 +101,7 @@ async def find_oob_target_for_outbound_message( outbound_message.payload = json.dumps(message) - LOGGER.debug( - "Sending oob message payload %s", outbound_message.payload - ) + LOGGER.debug("Sending oob message payload %s", outbound_message.payload) return ConnectionTarget( endpoint=their_service.endpoint, diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py index f9929ef518..7ec79632db 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_problem_report_handler.py @@ -42,11 +42,5 @@ async def test_cover(self, request_context, connection_record): } ) handler = test_module.CMProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(context=request_context, responder=responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_endorsed_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_endorsed_transaction_response_handler.py index 66e55325db..d6f8fe5ca6 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_endorsed_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_endorsed_transaction_response_handler.py @@ -26,12 +26,6 @@ async def test_called(self): request_context.message = EndorsedTransactionResponse() request_context.connection_ready = True handler = test_module.EndorsedTransactionResponseHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -54,12 +48,6 @@ async def test_called_not_ready(self): request_context.message = EndorsedTransactionResponse() request_context.connection_ready = False handler = test_module.EndorsedTransactionResponseHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -82,12 +70,6 @@ async def test_called_x(self): request_context.message = EndorsedTransactionResponse() request_context.connection_ready = True handler = test_module.EndorsedTransactionResponseHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_refused_transaction_response_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_refused_transaction_response_handler.py index 167458ac6a..33f00c5da5 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_refused_transaction_response_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_refused_transaction_response_handler.py @@ -26,12 +26,6 @@ async def test_called(self): request_context.message = RefusedTransactionResponse() request_context.connection_ready = True handler = test_module.RefusedTransactionResponseHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -54,12 +48,6 @@ async def test_called_not_ready(self): request_context.message = RefusedTransactionResponse() request_context.connection_ready = False handler = test_module.RefusedTransactionResponseHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -82,12 +70,6 @@ async def test_called_x(self): request_context.message = RefusedTransactionResponse() request_context.connection_ready = True handler = test_module.RefusedTransactionResponseHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_acknowledgement_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_acknowledgement_handler.py index 6b480cc1e4..ed4a864727 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_acknowledgement_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_acknowledgement_handler.py @@ -29,12 +29,6 @@ async def test_called(self): ) request_context.connection_ready = True handler = test_module.TransactionAcknowledgementHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -57,12 +51,6 @@ async def test_called_not_ready(self): request_context.message = TransactionAcknowledgement() request_context.connection_ready = False handler = test_module.TransactionAcknowledgementHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -87,12 +75,6 @@ async def test_called_x(self): ) request_context.connection_ready = True handler = test_module.TransactionAcknowledgementHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_cancel_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_cancel_handler.py index e9992ffc0e..bc144c16d6 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_cancel_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_cancel_handler.py @@ -29,12 +29,6 @@ async def test_called(self): ) request_context.connection_ready = True handler = test_module.TransactionCancelHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -57,12 +51,6 @@ async def test_called_not_ready(self): request_context.message = CancelTransaction() request_context.connection_ready = False handler = test_module.TransactionCancelHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -87,12 +75,6 @@ async def test_called_x(self): ) request_context.connection_ready = True handler = test_module.TransactionCancelHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_job_to_send_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_job_to_send_handler.py index a51cdecf02..41c66d4a78 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_job_to_send_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_job_to_send_handler.py @@ -26,12 +26,6 @@ async def test_called(self): request_context.message = TransactionJobToSend() request_context.connection_ready = True handler = test_module.TransactionJobToSendHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -56,12 +50,6 @@ async def test_called_x(self): request_context.message = TransactionJobToSend() request_context.connection_ready = True handler = test_module.TransactionJobToSendHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_request_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_request_handler.py index b6a70557e7..61c525e5f5 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_request_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_request_handler.py @@ -27,12 +27,6 @@ async def test_called(self): ) request_context.connection_ready = True handler = test_module.TransactionRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -53,12 +47,6 @@ async def test_called_not_ready(self): request_context.message = TransactionRequest() request_context.connection_ready = False handler = test_module.TransactionRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -81,12 +69,6 @@ async def test_called_x(self): ) request_context.connection_ready = True handler = test_module.TransactionRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_resend_handler.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_resend_handler.py index 8c87cdf195..e0e9ccbcde 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_resend_handler.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/handlers/tests/test_transaction_resend_handler.py @@ -29,12 +29,6 @@ async def test_called(self): ) request_context.connection_ready = True handler = test_module.TransactionResendHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -57,12 +51,6 @@ async def test_called_not_ready(self): request_context.message = TransactionResend() request_context.connection_ready = False handler = test_module.TransactionResendHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException): await handler.handle(request_context, responder) @@ -87,12 +75,6 @@ async def test_called_x(self): ) request_context.connection_ready = True handler = test_module.TransactionResendHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py index 25405cd9e5..57c0b054e4 100644 --- a/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py +++ b/aries_cloudagent/protocols/endorse_transaction/v1_0/routes.py @@ -719,6 +719,7 @@ def register_events(event_bus: EventBus): async def on_startup_event(profile: Profile, event: Event): """Handle any events we need to support.""" + # auto setup is only for authors if not is_author_role(profile): return diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_forward_invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_forward_invitation_handler.py index b846d01c16..bb19cea6de 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_forward_invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_forward_invitation_handler.py @@ -40,12 +40,6 @@ async def setUp(self): async def test_handle(self): handler = test_module.ForwardInvitationHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with async_mock.patch.object( @@ -60,12 +54,6 @@ async def test_handle(self): async def test_handle_x(self): handler = test_module.ForwardInvitationHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with async_mock.patch.object( @@ -83,12 +71,6 @@ async def test_handle_x(self): async def test_handle_not_ready(self): handler = test_module.ForwardInvitationHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) self.context.connection_ready = False with self.assertRaises(HandlerException): diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py index a0a75761ad..7e92953531 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_handler.py @@ -39,12 +39,7 @@ async def setUp(self): async def test_handle(self): handler = test_module.InvitationHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) + mock_conn_rec = async_mock.MagicMock(connection_id="dummy") responder = MockResponder() @@ -65,24 +60,12 @@ async def test_handle(self): async def test_handle_no_service(self): handler = test_module.InvitationHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) with self.assertRaises(HandlerException): await handler.handle(self.context, None) async def test_handle_not_ready(self): handler = test_module.InvitationHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) self.context.connection_ready = False with self.assertRaises(HandlerException): diff --git a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_request_handler.py b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_request_handler.py index 170a1e15f0..3bf7fe259d 100644 --- a/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_request_handler.py +++ b/aries_cloudagent/protocols/introduction/v0_1/handlers/tests/test_invitation_request_handler.py @@ -33,12 +33,7 @@ async def setUp(self): async def test_handle(self): handler = test_module.InvitationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) + responder = MockResponder() inv_req = InvitationRequest(responder=responder, message="Hello") @@ -49,12 +44,6 @@ async def test_handle(self): async def test_handle_auto_accept(self): handler = test_module.InvitationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) self.context.update_settings({"auto_accept_intro_invitation_requests": True}) conn_invitation = ConnectionInvitation( @@ -86,12 +75,6 @@ async def test_handle_auto_accept(self): async def test_handle_not_ready(self): handler = test_module.InvitationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) self.context.connection_ready = False with self.assertRaises(HandlerException): diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_ack_handler.py index e1c357877f..ae0c31f0e6 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_ack_handler.py @@ -34,12 +34,6 @@ async def test_called(self): request_context.message = CredentialAck() request_context.connection_ready = True handler = test_module.CredentialAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -66,12 +60,6 @@ async def test_called_not_ready(self): request_context.message = CredentialAck() request_context.connection_ready = False handler = test_module.CredentialAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -100,12 +88,6 @@ async def test_called_no_connection_no_oob(self): request_context.message = CredentialAck() request_context.connection_ready = False handler = test_module.CredentialAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py index 90fb3fa00b..0f831927a1 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_issue_handler.py @@ -31,12 +31,6 @@ async def test_called(self): request_context.message = CredentialIssue() request_context.connection_ready = True handler = test_module.CredentialIssueHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -78,12 +72,6 @@ async def test_called_auto_store(self): request_context.message = CredentialIssue() request_context.connection_ready = True handler = test_module.CredentialIssueHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -132,12 +120,6 @@ async def test_called_auto_store_x(self): request_context.message = CredentialIssue() request_context.connection_ready = True handler = test_module.CredentialIssueHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with async_mock.patch.object( @@ -160,12 +142,6 @@ async def test_called_not_ready(self): request_context.message = CredentialIssue() request_context.connection_ready = False handler = test_module.CredentialIssueHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -191,12 +167,6 @@ async def test_called_no_connection_no_oob(self): mock_cred_mgr.return_value.receive_credential = async_mock.CoroutineMock() request_context.message = CredentialIssue() handler = test_module.CredentialIssueHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py index f11ef8b374..a9aedbb0a9 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_offer_handler.py @@ -31,12 +31,6 @@ async def test_called(self): request_context.message = CredentialOffer() request_context.connection_ready = True handler = test_module.CredentialOfferHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -73,12 +67,6 @@ async def test_called_auto_request(self): request_context.message = CredentialOffer() request_context.connection_ready = True handler = test_module.CredentialOfferHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -124,19 +112,15 @@ async def test_called_auto_request_x(self): request_context.message = CredentialOffer() request_context.connection_ready = True handler = test_module.CredentialOfferHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply: + ) as mock_send_reply, async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_log_exc: await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + mock_log_exc.assert_called_once() async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -150,12 +134,6 @@ async def test_called_not_ready(self): request_context.message = CredentialOffer() request_context.connection_ready = False handler = test_module.CredentialOfferHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -185,12 +163,6 @@ async def test_no_conn_no_oob(self): request_context.message = CredentialOffer() request_context.connection_ready = False handler = test_module.CredentialOfferHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_problem_report_handler.py index f675111fe9..2187e6258c 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_problem_report_handler.py @@ -32,12 +32,6 @@ async def test_called(self): } ) handler = test_module.CredentialProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -68,12 +62,6 @@ async def test_called_x(self): } ) handler = test_module.CredentialProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -96,12 +84,6 @@ async def test_called_not_ready(self): } ) handler = test_module.CredentialProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: @@ -123,12 +105,6 @@ async def test_called_no_connection(self): } ) handler = test_module.CredentialProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py index 5682fbf6ee..911f056d43 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_proposal_handler.py @@ -25,12 +25,6 @@ async def test_called(self): request_context.message = CredentialProposal() request_context.connection_ready = True handler = test_module.CredentialProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -58,12 +52,6 @@ async def test_called_auto_offer(self): request_context.message = CredentialProposal() request_context.connection_ready = True handler = test_module.CredentialProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -98,19 +86,15 @@ async def test_called_auto_offer_x(self): request_context.message = CredentialProposal() request_context.connection_ready = True handler = test_module.CredentialProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply: + ) as mock_send_reply, async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_log_exc: await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + mock_log_exc.assert_called_once() async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -124,12 +108,6 @@ async def test_called_not_ready(self): request_context.message = CredentialProposal() request_context.connection_ready = False handler = test_module.CredentialProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -146,12 +124,6 @@ async def test_called_no_connection(self): request_context.message = CredentialProposal() handler = test_module.CredentialProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py index 2a4741ecbb..b74bf445ef 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/handlers/tests/test_credential_request_handler.py @@ -38,12 +38,6 @@ async def test_called(self): request_context.message = CredentialRequest() request_context.connection_ready = True handler = test_module.CredentialRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -92,12 +86,6 @@ async def test_called_auto_issue(self): request_context.message = CredentialRequest() request_context.connection_ready = True handler = test_module.CredentialRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_cred_mgr.return_value.issue_credential.assert_called_once_with( @@ -156,19 +144,15 @@ async def test_called_auto_issue_x(self): request_context.message = CredentialRequest() request_context.connection_ready = True handler = test_module.CredentialRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply: + ) as mock_send_reply, async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_log_exc: await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + mock_log_exc.assert_called_once() async def test_called_auto_issue_no_preview(self): request_context = RequestContext.test_context() @@ -201,12 +185,6 @@ async def test_called_auto_issue_no_preview(self): request_context.message = CredentialRequest() request_context.connection_ready = True handler = test_module.CredentialRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_cred_mgr.return_value.issue_credential.assert_not_called() @@ -232,12 +210,6 @@ async def test_called_not_ready(self): request_context.message = CredentialRequest() request_context.connection_ready = False handler = test_module.CredentialRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -266,12 +238,6 @@ async def test_called_no_connection_no_oob(self): mock_cred_mgr.return_value.receive_request = async_mock.CoroutineMock() request_context.message = CredentialRequest() handler = test_module.CredentialRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py index 0d6f7d4b74..66cf6315a5 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/tests/test_manager.py @@ -1552,9 +1552,9 @@ async def test_send_credential_ack(self): ) as mock_save_ex, async_mock.patch.object( V10CredentialExchange, "delete_record", autospec=True ) as mock_delete_ex, async_mock.patch.object( - self.manager._logger, "exception", async_mock.MagicMock() + test_module.LOGGER, "exception", async_mock.MagicMock() ) as mock_log_exception, async_mock.patch.object( - self.manager._logger, "warning", async_mock.MagicMock() + test_module.LOGGER, "warning", async_mock.MagicMock() ) as mock_log_warning: mock_delete_ex.side_effect = test_module.StorageError() (exch, ack) = await self.manager.send_credential_ack(stored_exchange) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py index 386028a8a6..d6329cfcb6 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/handler.py @@ -1,5 +1,7 @@ """V2.0 issue-credential indy credential format handler.""" +import logging + from marshmallow import RAISE import json from typing import Mapping, Tuple @@ -45,6 +47,8 @@ from ..handler import CredFormatAttachment, V20CredFormatError, V20CredFormatHandler +LOGGER = logging.getLogger(__name__) + class IndyCredFormatHandler(V20CredFormatHandler): """Indy credential format handler.""" @@ -92,7 +96,7 @@ async def get_detail_record(self, cred_ex_id: str) -> V20CredExRecordIndy: ) if len(records) > 1: - self._logger.warning( + LOGGER.warning( "Cred ex id %s has %d %s detail records: should be 1", cred_ex_id, len(records), @@ -351,7 +355,7 @@ async def issue_credential( for attempt in range(max(retries, 1)): if attempt > 0: - self._logger.info( + LOGGER.info( "Waiting 2s before retrying credential issuance for cred def '%s'", cred_def_id, ) @@ -489,7 +493,5 @@ async def store_credential( session, reason="store credential v2.0", event=True ) except IndyHolderError as e: - self._logger.error( - f"Error storing credential: {e.error_code} - {e.message}" - ) + LOGGER.error(f"Error storing credential: {e.error_code} - {e.message}") raise e diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py index 96cda66574..66ac360d3e 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/indy/tests/test_handler.py @@ -42,6 +42,7 @@ from ...handler import V20CredFormatError from ..handler import IndyCredFormatHandler +from ..handler import LOGGER as INDY_LOGGER TEST_DID = "LjgpST2rjsoxYegQDRm7EL" SCHEMA_NAME = "bc-reg" @@ -286,16 +287,12 @@ async def test_get_indy_detail_record(self): ] await details_indy[0].save(self.session) await details_indy[1].save(self.session) # exercise logger warning on get() - mock_logger = async_mock.MagicMock( - return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), - ) + with async_mock.patch.object( - self.handler, - "_logger", - mock_logger, - ): + INDY_LOGGER, "warning", async_mock.MagicMock() + ) as mock_warning: assert await self.handler.get_detail_record(cred_ex_id) in details_indy - assert mock_logger.warning.call_count == 1 + mock_warning.assert_called_once() async def test_check_uniqueness(self): with async_mock.patch.object( diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py index 15705bf3e4..02231f134d 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/handler.py @@ -1,5 +1,7 @@ """V2.0 issue-credential linked data proof credential format handler.""" + +import logging from typing import Mapping, Optional from marshmallow import EXCLUDE, INCLUDE @@ -51,6 +53,8 @@ from .models.cred_detail_options import LDProofVCDetailOptions from .models.cred_detail import LDProofVCDetail, LDProofVCDetailSchema +LOGGER = logging.getLogger(__name__) + SUPPORTED_ISSUANCE_PROOF_PURPOSES = { CredentialIssuancePurpose.term, AuthenticationProofPurpose.term, @@ -130,7 +134,7 @@ async def get_detail_record(self, cred_ex_id: str) -> V20CredExRecordLDProof: ) if len(records) > 1: - self._logger.warning( + LOGGER.warning( "Cred ex id %s has %d %s detail records: should be 1", cred_ex_id, len(records), diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py index 716c386e12..f17202fd31 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/formats/ld_proof/tests/test_handler.py @@ -59,6 +59,7 @@ from ...handler import V20CredFormatError from ..handler import LDProofCredFormatHandler +from ..handler import LOGGER as LD_PROOF_LOGGER TEST_DID_SOV = "did:sov:LjgpST2rjsoxYegQDRm7EL" TEST_DID_KEY = "did:key:z6Mkgg342Ycpuk263R9d8Aq6MUaxPn1DDeHyGo38EefXmgDL" @@ -211,16 +212,12 @@ async def test_get_ld_proof_detail_record(self): ] await details_ld_proof[0].save(self.session) await details_ld_proof[1].save(self.session) # exercise logger warning on get() - mock_logger = async_mock.MagicMock( - return_value=async_mock.MagicMock(warning=async_mock.MagicMock()), - ) + with async_mock.patch.object( - self.handler, - "_logger", - mock_logger, - ): + LD_PROOF_LOGGER, "warning", async_mock.MagicMock() + ) as mock_warning: assert await self.handler.get_detail_record(cred_ex_id) in details_ld_proof - assert mock_logger.warning.call_count == 1 + mock_warning.assert_called_once() async def test_assert_can_issue_with_id_and_proof_type(self): with self.assertRaises(V20CredFormatError) as context: diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_ack_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_ack_handler.py index 4712b9200b..f4283168fa 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_ack_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_ack_handler.py @@ -32,12 +32,6 @@ async def test_called(self): request_context.message = V20CredAck() request_context.connection_ready = True handler = test_module.V20CredAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -63,12 +57,6 @@ async def test_called_not_ready(self): request_context.message = V20CredAck() request_context.connection_ready = False handler = test_module.V20CredAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -92,12 +80,6 @@ async def test_called_no_connection_no_oob(self): request_context.message = V20CredAck() handler = test_module.V20CredAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py index 5a385563e4..66e295ce34 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_offer_handler.py @@ -112,19 +112,15 @@ async def test_called_auto_request_x(self): request_context.message = V20CredOffer() request_context.connection_ready = True handler = test_module.V20CredOfferHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply: + ) as mock_send_reply, async_mock.patch.object( + handler._logger, "exception", async_mock.CoroutineMock() + ) as mock_log_exc: await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + mock_log_exc.assert_called_once() async def test_called_not_ready(self): request_context = RequestContext.test_context() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_problem_report_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_problem_report_handler.py index ebf70ad1fa..fa5195fce9 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_problem_report_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_problem_report_handler.py @@ -29,12 +29,6 @@ async def test_called(self): } ) handler = test_module.CredProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -65,12 +59,6 @@ async def test_called_x(self): } ) handler = test_module.CredProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -93,12 +81,6 @@ async def test_called_not_ready(self): } ) handler = test_module.CredProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: @@ -120,12 +102,6 @@ async def test_called_no_connection(self): } ) handler = test_module.CredProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py index e8ac4b98d3..daaf4c0d79 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_proposal_handler.py @@ -86,19 +86,15 @@ async def test_called_auto_offer_x(self): request_context.message = V20CredProposal() request_context.connection_ready = True handler = test_module.V20CredProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply: + ) as mock_send_reply, async_mock.patch.object( + handler._logger, "exception", async_mock.CoroutineMock() + ) as mock_log_exc: await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + mock_log_exc.assert_called_once() async def test_called_not_ready(self): request_context = RequestContext.test_context() diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py index 9f815b59ea..25edba8b36 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/handlers/tests/test_cred_request_handler.py @@ -37,12 +37,6 @@ async def test_called(self): request_context.message = V20CredRequest() request_context.connection_ready = True handler = test_module.V20CredRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -80,12 +74,6 @@ async def test_called_auto_issue(self): request_context.message = V20CredRequest() request_context.connection_ready = True handler = test_module.V20CredRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_cred_mgr.return_value.issue_credential.assert_called_once_with( @@ -133,19 +121,15 @@ async def test_called_auto_issue_x(self): request_context.message = V20CredRequest() request_context.connection_ready = True handler = test_module.V20CredRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with async_mock.patch.object( responder, "send_reply", async_mock.CoroutineMock() - ) as mock_send_reply: + ) as mock_send_reply, async_mock.patch.object( + handler._logger, "exception", async_mock.CoroutineMock() + ) as mock_log_exc: await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + mock_log_exc.assert_called_once() async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -159,12 +143,6 @@ async def test_called_not_ready(self): request_context.message = V20CredRequest() request_context.connection_ready = False handler = test_module.V20CredRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -189,12 +167,6 @@ async def test_called_no_connection_no_oob(self): request_context.message = V20CredRequest() handler = test_module.V20CredRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/notification/v1_0/handlers/tests/test_ack_handler.py b/aries_cloudagent/protocols/notification/v1_0/handlers/tests/test_ack_handler.py index 1c4f4fcb4a..eb63e04b37 100644 --- a/aries_cloudagent/protocols/notification/v1_0/handlers/tests/test_ack_handler.py +++ b/aries_cloudagent/protocols/notification/v1_0/handlers/tests/test_ack_handler.py @@ -17,11 +17,5 @@ async def test_called(self): request_context.message = V10Ack(status="OK") handler = test_module.V10AckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py index 240efa213c..c8b69357cb 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_problem_report_handler.py @@ -46,12 +46,6 @@ async def test_called(self, mock_oob_mgr, request_context, connection_record): } ) handler = test_module.OOBProblemReportMessageHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(context=request_context, responder=responder) mock_oob_mgr.return_value.receive_problem_report.assert_called_once_with( @@ -74,12 +68,10 @@ async def test_exception(self, mock_oob_mgr, request_context, connection_record) } ) handler = test_module.OOBProblemReportMessageHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) - responder = MockResponder() - await handler.handle(context=request_context, responder=responder) - assert handler._logger.exception.call_count == 1 + with async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_exc_logger: + responder = MockResponder() + await handler.handle(context=request_context, responder=responder) + + assert mock_exc_logger.called_once() diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py index 147a9c901b..f403a1ce17 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_accept_handler.py @@ -43,12 +43,6 @@ async def test_called(self, mock_oob_mgr, request_context, connection_record): ) request_context.message = HandshakeReuseAccept() handler = test_module.HandshakeReuseAcceptMessageHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(context=request_context, responder=responder) mock_oob_mgr.return_value.receive_reuse_accepted_message.assert_called_once_with( @@ -68,12 +62,6 @@ async def test_exception(self, mock_oob_mgr, request_context, connection_record) ) request_context.message = HandshakeReuseAccept() handler = test_module.HandshakeReuseAcceptMessageHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(context=request_context, responder=responder) assert mock_oob_mgr.return_value._logger.exception.called_once_("error") diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py index b130a5493d..d4d94f546c 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/handlers/tests/test_reuse_handler.py @@ -34,12 +34,6 @@ async def test_called(self, mock_oob_mgr, request_context): mock_oob_mgr.return_value.receive_reuse_message = async_mock.CoroutineMock() request_context.message = HandshakeReuse() handler = test_module.HandshakeReuseMessageHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) request_context.connection_record = ConnRecord() responder = MockResponder() await handler.handle(request_context, responder) @@ -57,12 +51,6 @@ async def test_reuse_accepted(self, mock_oob_mgr, request_context): mock_oob_mgr.return_value.receive_reuse_message.return_value = reuse_accepted request_context.message = HandshakeReuse() handler = test_module.HandshakeReuseMessageHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) request_context.connection_record = ConnRecord() responder = MockResponder() await handler.handle(request_context, responder) @@ -81,12 +69,6 @@ async def test_exception(self, mock_oob_mgr, request_context): ) request_context.message = HandshakeReuse() handler = test_module.HandshakeReuseMessageHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) request_context.connection_record = ConnRecord() responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_ack_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_ack_handler.py index ba0eee77fc..db233adc17 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_ack_handler.py @@ -33,12 +33,6 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -62,12 +56,6 @@ async def test_called_not_ready(self): request_context.message = PresentationAck() request_context.connection_ready = False handler = test_module.PresentationAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -89,12 +77,6 @@ async def test_called_no_connection_no_oob(self): request_context.message = PresentationAck() handler = test_module.PresentationAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py index 0df8e8aef1..28b4747502 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_handler.py @@ -32,12 +32,6 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -69,12 +63,6 @@ async def test_called_auto_verify(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -115,12 +103,10 @@ async def test_called_auto_verify_x(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() - await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + + with async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_log_exc: + await handler.handle(request_context, responder) + mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_problem_report_handler.py index 887e4630ea..a726dc349c 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_problem_report_handler.py @@ -32,12 +32,6 @@ async def test_called(self): } ) handler = test_module.PresentationProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -68,12 +62,6 @@ async def test_called_x(self): } ) handler = test_module.PresentationProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py index 773640d3d9..95c963f704 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_proposal_handler.py @@ -26,12 +26,6 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.PresentationProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -64,12 +58,6 @@ async def test_called_auto_request(self): request_context.message = PresentationProposal() request_context.connection_ready = True handler = test_module.PresentationProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -109,15 +97,13 @@ async def test_called_auto_request_x(self): request_context.message = PresentationProposal() request_context.connection_ready = True handler = test_module.PresentationProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() - await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + + with async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_log_exc: + await handler.handle(request_context, responder) + mock_log_exc.assert_called_once() async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -131,12 +117,6 @@ async def test_called_not_ready(self): request_context.message = PresentationProposal() request_context.connection_ready = False handler = test_module.PresentationProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -153,12 +133,6 @@ async def test_called_no_connection(self): request_context.message = PresentationProposal() handler = test_module.PresentationProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py index 658f551629..83329461a4 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/handlers/tests/test_presentation_request_handler.py @@ -113,12 +113,6 @@ async def test_called(self): request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -180,12 +174,6 @@ async def test_called_not_found(self): request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -268,12 +256,6 @@ async def test_called_auto_present(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -365,16 +347,13 @@ async def test_called_auto_present_x(self): request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() - await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + with async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_log_exc: + await handler.handle(request_context, responder) + mock_log_exc.assert_called_once() async def test_called_auto_present_no_preview(self): request_context = RequestContext.test_context() @@ -446,12 +425,6 @@ async def test_called_auto_present_no_preview(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -527,12 +500,6 @@ async def test_called_auto_present_pred_no_match(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_not_called() @@ -606,12 +573,6 @@ async def test_called_auto_present_pred_single_match(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -692,12 +653,6 @@ async def test_called_auto_present_pred_multi_match(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -829,12 +784,6 @@ async def test_called_auto_present_multi_cred_match_reft(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_presentation.assert_called_once() @@ -948,12 +897,6 @@ async def test_called_auto_present_bait_and_switch(self): ) request_context.connection_ready = True handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -979,12 +922,6 @@ async def test_called_not_ready(self): request_context.message = PresentationRequest() request_context.connection_ready = False handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -1009,12 +946,6 @@ async def test_no_conn_no_oob(self): request_context.message = PresentationRequest() handler = test_module.PresentationRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py b/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py index 386c52a6e6..97f77aac9e 100644 --- a/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/present_proof/v1_0/tests/test_manager.py @@ -645,7 +645,9 @@ async def test_create_presentation_no_revocation(self): V10PresentationExchange, "save", autospec=True ) as save_ex, async_mock.patch.object( test_module, "AttachDecorator", autospec=True - ) as mock_attach_decorator: + ) as mock_attach_decorator, async_mock.patch.object( + test_indy_util_module.LOGGER, "info", async_mock.MagicMock() + ) as mock_log_info: mock_attach_decorator.data_base64 = async_mock.MagicMock( return_value=mock_attach_decorator ) @@ -664,6 +666,7 @@ async def test_create_presentation_no_revocation(self): for pred_reft_spec in req_creds["requested_predicates"].values(): pred_reft_spec["timestamp"] = 1234567890 await self.manager.create_presentation(exchange_in, req_creds) + mock_log_info.assert_called_once() async def test_create_presentation_bad_revoc_state(self): exchange_in = V10PresentationExchange() diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py index 2236a2a76d..868d7148bf 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/handler.py @@ -1,6 +1,7 @@ """V2.0 present-proof dif presentation-exchange format handler.""" import json +import logging from marshmallow import RAISE from typing import Mapping, Tuple, Sequence @@ -47,6 +48,8 @@ from ..handler import V20PresFormatHandler, V20PresFormatHandlerError +LOGGER = logging.getLogger(__name__) + class DIFPresFormatHandler(V20PresFormatHandler): """DIF presentation format handler.""" @@ -353,7 +356,7 @@ async def create_pres( except StorageNotFoundError as err: raise V20PresFormatHandlerError(err) except TypeError as err: - self._logger.error(str(err)) + LOGGER.error(str(err)) responder = self._profile.inject_or(BaseResponder) if responder: report = ProblemReport( @@ -388,7 +391,7 @@ async def create_pres( ) return self.get_format_data(PRES_20, pres) except DIFPresExchError as err: - self._logger.error(str(err)) + LOGGER.error(str(err)) responder = self._profile.inject_or(BaseResponder) if responder: report = ProblemReport( @@ -441,7 +444,7 @@ async def receive_pres(self, message: V20Pres, pres_ex_record: V20PresExRecord): await dif_handler.verify_received_pres(pd=pres_definition, pres=dif_proof) return True except DIFPresExchError as err: - self._logger.error(str(err)) + LOGGER.error(str(err)) responder = self._profile.inject_or(BaseResponder) if responder: report = ProblemReport( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py index 099195f0fd..8143083c0a 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/dif/tests/test_handler.py @@ -1967,16 +1967,11 @@ async def test_verify_received_pres_invalid_jsonpath(self): auto_present=True, error_msg="error", ) - mock_logger = async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ) with async_mock.patch.object( - self.handler, - "_logger", - mock_logger, - ): + test_module.LOGGER, "error", async_mock.MagicMock() + ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - assert mock_logger.error.call_count == 1 + mock_log_err.assert_called_once() async def test_verify_received_pres_no_match_a(self): dif_proof_req = deepcopy(DIF_PRES_REQUEST_B) @@ -2025,16 +2020,11 @@ async def test_verify_received_pres_no_match_a(self): auto_present=True, error_msg="error", ) - mock_logger = async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ) with async_mock.patch.object( - self.handler, - "_logger", - mock_logger, - ): + test_module.LOGGER, "error", async_mock.MagicMock() + ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - assert mock_logger.error.call_count == 1 + mock_log_err.assert_called_once() async def test_verify_received_pres_no_match_b(self): dif_proof_req = deepcopy(DIF_PRES_REQUEST_B) @@ -2083,16 +2073,11 @@ async def test_verify_received_pres_no_match_b(self): auto_present=True, error_msg="error", ) - mock_logger = async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ) with async_mock.patch.object( - self.handler, - "_logger", - mock_logger, - ): + test_module.LOGGER, "error", async_mock.MagicMock() + ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - assert mock_logger.error.call_count == 1 + mock_log_err.assert_called_once() async def test_verify_received_pres_limit_disclosure_fail_a(self): dif_proof = deepcopy(DIF_PRES) @@ -2138,16 +2123,11 @@ async def test_verify_received_pres_limit_disclosure_fail_a(self): auto_present=True, error_msg="error", ) - mock_logger = async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ) with async_mock.patch.object( - self.handler, - "_logger", - mock_logger, - ): + test_module.LOGGER, "error", async_mock.MagicMock() + ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - assert mock_logger.error.call_count == 1 + mock_log_err.assert_called_once() async def test_verify_received_pres_limit_disclosure_fail_b(self): dif_proof = deepcopy(DIF_PRES) @@ -2193,16 +2173,11 @@ async def test_verify_received_pres_limit_disclosure_fail_b(self): auto_present=True, error_msg="error", ) - mock_logger = async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ) with async_mock.patch.object( - self.handler, - "_logger", - mock_logger, - ): + test_module.LOGGER, "error", async_mock.MagicMock() + ) as mock_log_err: await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - assert mock_logger.error.call_count == 1 + mock_log_err.assert_called_once() async def test_verify_received_pres_fail_schema_filter(self): dif_proof = deepcopy(DIF_PRES) @@ -2288,19 +2263,14 @@ async def test_verify_received_pres_fail_schema_filter(self): auto_present=True, error_msg="error", ) - mock_logger = async_mock.MagicMock( - return_value=async_mock.MagicMock(error=async_mock.MagicMock()), - ) with async_mock.patch.object( - self.handler, - "_logger", - mock_logger, - ), async_mock.patch.object( + test_module.LOGGER, "error", async_mock.MagicMock() + ) as mock_log_err, async_mock.patch.object( jsonld, "expand", async_mock.MagicMock() ) as mock_jsonld_expand: mock_jsonld_expand.return_value = EXPANDED_CRED_FHIR_TYPE_2 await self.handler.receive_pres(message=dif_pres, pres_ex_record=record) - assert mock_logger.error.call_count == 1 + mock_log_err.assert_called_once() async def test_create_pres_catch_typeerror(self): self.context.injector.bind_instance( diff --git a/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py b/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py index 1892a36ee9..16ebb7fec6 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/formats/indy/handler.py @@ -1,6 +1,7 @@ """V2.0 present-proof indy presentation-exchange format handler.""" import json +import logging from marshmallow import RAISE from typing import Mapping, Tuple @@ -29,6 +30,8 @@ from ..handler import V20PresFormatHandler, V20PresFormatHandlerError +LOGGER = logging.getLogger(__name__) + class IndyPresExchangeHandler(V20PresFormatHandler): """Indy presentation format handler.""" @@ -143,7 +146,7 @@ async def create_pres( ) ) except ValueError as err: - self._logger.warning(f"{err}") + LOGGER.warning(f"{err}") raise V20PresFormatHandlerError( f"No matching Indy credentials found: {err}" ) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_ack_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_ack_handler.py index e246637fff..928a2df6be 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_ack_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_ack_handler.py @@ -31,12 +31,6 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -58,12 +52,6 @@ async def test_called_not_ready(self): request_context.message = V20PresAck() request_context.connection_ready = False handler = test_module.V20PresAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -85,12 +73,6 @@ async def test_called_no_connection_no_oob(self): request_context.message = V20PresAck() handler = test_module.V20PresAckHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py index ed4a3eb201..b28027c263 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_handler.py @@ -32,12 +32,6 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -69,12 +63,6 @@ async def test_called_auto_verify(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -115,12 +103,10 @@ async def test_called_auto_verify_x(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() - await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + + with async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_log_exc: + await handler.handle(request_context, responder) + mock_log_exc.assert_called_once() diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_problem_report_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_problem_report_handler.py index ac42f98499..170a826e14 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_problem_report_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_problem_report_handler.py @@ -28,12 +28,6 @@ async def test_called(self): } ) handler = test_module.V20PresProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -63,12 +57,6 @@ async def test_called_x(self): } ) handler = test_module.V20PresProblemReportHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py index afaab2f3d6..033742133e 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_proposal_handler.py @@ -26,12 +26,6 @@ async def test_called(self): request_context.connection_ready = True request_context.connection_record = async_mock.MagicMock() handler = test_module.V20PresProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -64,12 +58,6 @@ async def test_called_auto_request(self): request_context.message = V20PresProposal() request_context.connection_ready = True handler = test_module.V20PresProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -109,15 +97,13 @@ async def test_called_auto_request_x(self): request_context.message = V20PresProposal() request_context.connection_ready = True handler = test_module.V20PresProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() - await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + + with async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_log_exc: + await handler.handle(request_context, responder) + mock_log_exc.assert_called_once() async def test_called_not_ready(self): request_context = RequestContext.test_context() @@ -133,12 +119,6 @@ async def test_called_not_ready(self): request_context.message = V20PresProposal() request_context.connection_ready = False handler = test_module.V20PresProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -155,12 +135,6 @@ async def test_called_no_connection(self): request_context.message = V20PresProposal() handler = test_module.V20PresProposalHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py index bc43f02860..786d78bee5 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/handlers/tests/test_pres_request_handler.py @@ -228,12 +228,6 @@ async def test_called(self): request_context.connection_ready = True handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -294,12 +288,6 @@ async def test_called_not_found(self): request_context.connection_ready = True handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -372,15 +360,13 @@ async def test_called_auto_present_x(self): request_context.connection_ready = True handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() - await handler.handle(request_context, responder) - assert handler._logger.exception.call_count == 1 + + with async_mock.patch.object( + handler._logger, "exception", async_mock.MagicMock() + ) as mock_log_exc: + await handler.handle(request_context, responder) + mock_log_exc.assert_called_once() async def test_called_auto_present_indy(self): request_context = RequestContext.test_context() @@ -443,12 +429,6 @@ async def test_called_auto_present_indy(self): request_context.connection_ready = True handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -592,12 +572,6 @@ async def test_called_auto_present_no_preview(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_pres.assert_called_once() @@ -672,12 +646,6 @@ async def test_called_auto_present_pred_no_match(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) @@ -742,12 +710,6 @@ async def test_called_auto_present_pred_single_match(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_pres.assert_called_once() @@ -819,12 +781,6 @@ async def test_called_auto_present_pred_multi_match(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_pres.assert_called_once() @@ -941,12 +897,6 @@ async def test_called_auto_present_multi_cred_match_reft(self): ) request_context.connection_ready = True handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() await handler.handle(request_context, responder) mock_pres_mgr.return_value.create_pres.assert_called_once() @@ -975,12 +925,6 @@ async def test_called_not_ready(self): request_context.message = V20PresRequest() request_context.connection_ready = False handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) @@ -1005,12 +949,6 @@ async def test_no_conn_no_oob(self): request_context.message = V20PresRequest() handler = test_module.V20PresRequestHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) responder = MockResponder() with self.assertRaises(test_module.HandlerException) as err: await handler.handle(request_context, responder) diff --git a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py index 1858dcadd2..51da3c6450 100644 --- a/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py +++ b/aries_cloudagent/protocols/present_proof/v2_0/tests/test_manager.py @@ -27,7 +27,7 @@ from ...indy import pres_exch_handler as test_indy_util_module from .. import manager as test_module -from ..formats.handler import V20PresFormatHandler, V20PresFormatHandlerError +from ..formats.handler import V20PresFormatHandlerError from ..formats.dif.handler import DIFPresFormatHandler from ..formats.dif.tests.test_handler import ( DIF_PRES_REQUEST_B as DIF_PRES_REQ, @@ -1040,6 +1040,7 @@ async def test_create_pres_no_revocation(self): ) self.holder.create_presentation = async_mock.CoroutineMock(return_value="{}") self.profile.context.injector.bind_instance(IndyHolder, self.holder) + with async_mock.patch.object( V20PresExRecord, "save", autospec=True ) as save_ex, async_mock.patch.object( @@ -1143,7 +1144,7 @@ async def test_create_pres_bad_revoc_state(self): ) as mock_attach_decorator, async_mock.patch.object( test_indy_util_module, "RevocationRegistry", autospec=True ) as mock_rr, async_mock.patch.object( - self.manager._logger, "error", async_mock.MagicMock() + test_indy_util_module.LOGGER, "error", async_mock.MagicMock() ) as mock_log_error: mock_rr.from_definition = async_mock.MagicMock(return_value=more_magic_rr) diff --git a/aries_cloudagent/protocols/routing/v1_0/handlers/tests/test_forward_handler.py b/aries_cloudagent/protocols/routing/v1_0/handlers/tests/test_forward_handler.py index 5010773668..03e3b2993e 100644 --- a/aries_cloudagent/protocols/routing/v1_0/handlers/tests/test_forward_handler.py +++ b/aries_cloudagent/protocols/routing/v1_0/handlers/tests/test_forward_handler.py @@ -27,12 +27,7 @@ async def setUp(self): async def test_handle(self): self.context.message_receipt = MessageReceipt(recipient_verkey=TEST_VERKEY) handler = test_module.ForwardHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) + responder = MockResponder() with async_mock.patch.object( test_module, "RoutingManager", autospec=True @@ -74,24 +69,13 @@ async def test_handle(self): async def test_handle_receipt_no_recipient_verkey(self): self.context.message_receipt = MessageReceipt() handler = test_module.ForwardHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) with self.assertRaises(HandlerException): await handler.handle(self.context, None) async def test_handle_cannot_resolve_recipient(self): self.context.message_receipt = MessageReceipt(recipient_verkey=TEST_VERKEY) handler = test_module.ForwardHandler() - handler._logger = async_mock.MagicMock( - error=async_mock.MagicMock(), - info=async_mock.MagicMock(), - warning=async_mock.MagicMock(), - debug=async_mock.MagicMock(), - ) + responder = MockResponder() with async_mock.patch.object( test_module, "RoutingManager", autospec=True diff --git a/aries_cloudagent/resolver/tests/test_did_resolver.py b/aries_cloudagent/resolver/tests/test_did_resolver.py index a881c8b924..26d984a12b 100644 --- a/aries_cloudagent/resolver/tests/test_did_resolver.py +++ b/aries_cloudagent/resolver/tests/test_did_resolver.py @@ -113,7 +113,7 @@ async def test_match_did_to_resolver(profile, resolver, did, method): @pytest.mark.asyncio -async def test_match_did_to_resolver_x_not_supported(profile, resolver): +async def test_match_did_to_resolver_x_not_supported(resolver): with pytest.raises(DIDMethodNotSupported): await resolver._match_did_to_resolver( profile, "did:cowsay:EiDahaOGH-liLLdDtTxEAdc8i-cfCz-WUcQdRJheMVNn3A" diff --git a/demo/runners/agent_container.py b/demo/runners/agent_container.py index 879d01e104..3eb88f575b 100644 --- a/demo/runners/agent_container.py +++ b/demo/runners/agent_container.py @@ -57,10 +57,8 @@ def __init__( revocation: bool = False, anoncreds_legacy_revocation: str = None, log_file: str = None, - log_handler_config: str = None, - log_fmt_pattern: str = None, + log_config: str = None, log_level: str = None, - log_json_fmt: bool = False, **kwargs, ): extra_args = [] @@ -87,9 +85,7 @@ def __init__( revocation=revocation, extra_args=extra_args, log_file=log_file, - log_handler_config=log_handler_config, - log_fmt_pattern=log_fmt_pattern, - log_json_fmt=log_json_fmt, + log_config=log_config, log_level=log_level, **kwargs, ) @@ -690,9 +686,7 @@ def __init__( taa_accept: bool = False, anoncreds_legacy_revocation: str = None, log_file: str = None, - log_handler_config: str = None, - log_fmt_pattern: str = None, - log_json_fmt: bool = False, + log_config: str = None, log_level: str = None, ): # configuration parameters @@ -718,9 +712,7 @@ def __init__( self.endorser_role = endorser_role self.anoncreds_legacy_revocation = anoncreds_legacy_revocation self.log_file = log_file - self.log_handler_config = log_handler_config - self.log_fmt_pattern = log_fmt_pattern - self.log_json_fmt = log_json_fmt + self.log_config = log_config self.log_level = log_level if endorser_role: # endorsers and authors need public DIDs (assume cred_type is Indy) @@ -769,9 +761,7 @@ async def initialize( arg_file=self.arg_file, endorser_role=self.endorser_role, log_file=self.log_file, - log_handler_config=self.log_handler_config, - log_fmt_pattern=self.log_fmt_pattern, - log_json_fmt=self.log_json_fmt, + log_config=self.log_config, log_level=self.log_level, ) else: @@ -1312,6 +1302,12 @@ def arg_parser(ident: str = None, port: int = 8020): metavar="", help="Output destination for the root logger.", ) + parser.add_argument( + "--log-config", + type=str, + metavar="", + help="File path for logging configuration.", + ) parser.add_argument( "--log-level", type=str, @@ -1354,6 +1350,7 @@ async def create_agent_with_args(args, ident: str = None): arg_file_dict = yaml.safe_load(f) log_file = args.log_file or os.getenv("ACAPY_LOG_FILE") + log_config = args.log_config or os.getenv("ACAPY_LOG_CONFIG") log_level = args.log_level # if we don't have a tails server url then guess it if ("revocation" in args and args.revocation) and not tails_server_base_url: @@ -1433,6 +1430,7 @@ async def create_agent_with_args(args, ident: str = None): taa_accept=args.taa_accept, anoncreds_legacy_revocation=anoncreds_legacy_revocation, log_file=log_file, + log_config=log_config, log_level=log_level, ) diff --git a/demo/runners/alice.py b/demo/runners/alice.py index 32c9eebe0c..31f85d0bea 100644 --- a/demo/runners/alice.py +++ b/demo/runners/alice.py @@ -37,9 +37,7 @@ def __init__( aip: int = 20, endorser_role: str = None, log_file: str = None, - log_handler_config: str = None, - log_fmt_pattern: str = None, - log_json_fmt: bool = False, + log_config: str = None, log_level: str = None, **kwargs, ): @@ -53,9 +51,7 @@ def __init__( aip=aip, endorser_role=endorser_role, log_file=log_file, - log_handler_config=log_handler_config, - log_fmt_pattern=log_fmt_pattern, - log_json_fmt=log_json_fmt, + log_config=log_config, log_level=log_level, **kwargs, ) @@ -141,9 +137,7 @@ async def main(args): aip=alice_agent.aip, endorser_role=alice_agent.endorser_role, log_file=alice_agent.log_file, - log_handler_config=alice_agent.log_handler_config, - log_fmt_pattern=alice_agent.log_fmt_pattern, - log_json_fmt=alice_agent.log_json_fmt, + log_config=alice_agent.log_config, log_level=alice_agent.log_level, ) diff --git a/demo/runners/faber.py b/demo/runners/faber.py index 166e15254a..4d05c939ad 100644 --- a/demo/runners/faber.py +++ b/demo/runners/faber.py @@ -48,9 +48,7 @@ def __init__( revocation: bool = False, anoncreds_legacy_revocation: str = None, log_file: str = None, - log_handler_config: str = None, - log_fmt_pattern: str = None, - log_json_fmt: bool = False, + log_config: str = None, log_level: str = None, **kwargs, ): @@ -64,9 +62,7 @@ def __init__( revocation=revocation, anoncreds_legacy_revocation=anoncreds_legacy_revocation, log_file=log_file, - log_handler_config=log_handler_config, - log_fmt_pattern=log_fmt_pattern, - log_json_fmt=log_json_fmt, + log_config=log_config, log_level=log_level, **kwargs, ) @@ -414,9 +410,7 @@ async def main(args): endorser_role=faber_agent.endorser_role, anoncreds_legacy_revocation=faber_agent.anoncreds_legacy_revocation, log_file=faber_agent.log_file, - log_handler_config=faber_agent.log_handler_config, - log_fmt_pattern=faber_agent.log_fmt_pattern, - log_json_fmt=faber_agent.log_json_fmt, + log_config=faber_agent.log_config, log_level=faber_agent.log_level, ) diff --git a/demo/runners/performance.py b/demo/runners/performance.py index 9deba03609..26daf4a87d 100644 --- a/demo/runners/performance.py +++ b/demo/runners/performance.py @@ -33,9 +33,7 @@ def __init__( port: int, prefix: str = None, log_file: str = None, - log_handler_config: str = None, - log_fmt_pattern: str = None, - log_json_fmt: bool = False, + log_config: str = None, log_level: str = None, **kwargs, ): @@ -47,9 +45,7 @@ def __init__( port + 1, prefix=prefix, log_file=log_file, - log_handler_config=log_handler_config, - log_fmt_pattern=log_fmt_pattern, - log_json_fmt=log_json_fmt, + log_config=log_config, log_level=log_level, **kwargs, ) @@ -181,9 +177,7 @@ def __init__( self, port: int, log_file: str = None, - log_handler_config: str = None, - log_fmt_pattern: str = None, - log_json_fmt: bool = False, + log_config: str = None, log_level: str = None, **kwargs, ): @@ -192,9 +186,7 @@ def __init__( port, seed=None, log_file=log_file, - log_handler_config=log_handler_config, - log_fmt_pattern=log_fmt_pattern, - log_json_fmt=log_json_fmt, + log_config=log_config, log_level=log_level, **kwargs, ) @@ -237,9 +229,7 @@ def __init__( self, port: int, log_file: str = None, - log_handler_config: str = None, - log_fmt_pattern: str = None, - log_json_fmt: bool = False, + log_config: str = None, log_level: str = None, **kwargs, ): @@ -248,9 +238,7 @@ def __init__( port, seed="random", log_file=log_file, - log_handler_config=log_handler_config, - log_fmt_pattern=log_fmt_pattern, - log_json_fmt=log_json_fmt, + log_config=log_config, log_level=log_level, **kwargs, ) @@ -340,9 +328,7 @@ async def main( wallet_type: str = None, arg_file: str = None, log_file: str = None, - log_handler_config: str = None, - log_fmt_pattern: str = None, - log_json_fmt: bool = False, + log_config: str = None, log_level: str = None, ): if multi_ledger: @@ -373,9 +359,7 @@ async def main( wallet_type=wallet_type, arg_file=arg_file, log_file=log_file, - log_handler_config=log_handler_config, - log_fmt_pattern=log_fmt_pattern, - log_json_fmt=log_json_fmt, + log_config=log_config, log_level=log_level, ) await alice.listen_webhooks(start_port + 2) @@ -391,9 +375,7 @@ async def main( wallet_type=wallet_type, arg_file=arg_file, log_file=log_file, - log_handler_config=log_handler_config, - log_fmt_pattern=log_fmt_pattern, - log_json_fmt=log_json_fmt, + log_config=log_config, log_level=log_level, ) await faber.listen_webhooks(start_port + 5) @@ -760,6 +742,12 @@ async def check_received_pings(agent, issue_count, pb): metavar="", help=("Output destination for the root logger."), ) + parser.add_argument( + "--log-config", + type=str, + metavar="", + help=("File path for logging configuration."), + ) parser.add_argument( "--log-level", type=str, @@ -809,6 +797,7 @@ async def check_received_pings(agent, issue_count, pb): args.wallet_type, args.arg_file, args.log_file, + args.log_config, args.log_level, ) ) diff --git a/demo/runners/support/agent.py b/demo/runners/support/agent.py index b040361a5a..9011efd8ad 100644 --- a/demo/runners/support/agent.py +++ b/demo/runners/support/agent.py @@ -139,9 +139,7 @@ def __init__( endorser_role: str = None, extra_args=None, log_file: str = None, - log_handler_config: str = None, - log_fmt_pattern: str = None, - log_json_fmt: bool = False, + log_config: str = None, log_level: str = None, **params, ): @@ -175,9 +173,7 @@ def __init__( self.aip = aip self.arg_file = arg_file self.log_file = log_file - self.log_handler_config = log_handler_config - self.log_fmt_pattern = log_fmt_pattern - self.log_json_fmt = log_json_fmt + self.log_config = log_config self.log_level = log_level self.admin_url = f"http://{self.internal_host}:{admin_port}" @@ -361,6 +357,12 @@ def get_agent_args(self): ("--log-file", self.log_file), ] ) + if self.log_config: + result.extend( + [ + ("--log-config", self.log_config), + ] + ) if self.log_level: result.extend( [ diff --git a/demo/runners/support/utils.py b/demo/runners/support/utils.py index 45ef1b733e..77e5d7792f 100644 --- a/demo/runners/support/utils.py +++ b/demo/runners/support/utils.py @@ -127,6 +127,7 @@ def log_msg(*msg, color="fg:ansimagenta", **kwargs): except AssertionError: pass + def log_json(data, **kwargs): run_in_terminal(lambda: print_json(data, **kwargs)) From 202bf79466b7b715bcfa49c9ee7aa9de28aaacd7 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Fri, 8 Sep 2023 19:13:30 +0530 Subject: [PATCH 12/18] remove redundant code Signed-off-by: Shaanjot Gill --- aries_cloudagent/connections/base_manager.py | 6 +----- aries_cloudagent/core/event_bus.py | 1 + 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/aries_cloudagent/connections/base_manager.py b/aries_cloudagent/connections/base_manager.py index f1d2ce9fa8..d2659d5370 100644 --- a/aries_cloudagent/connections/base_manager.py +++ b/aries_cloudagent/connections/base_manager.py @@ -20,7 +20,6 @@ ) from ..cache.base import BaseCache from ..config.base import InjectionError -from ..config.logging import get_logger_inst from ..core.error import BaseError from ..core.profile import Profile from ..did.did_key import DIDKey @@ -71,10 +70,7 @@ def __init__(self, profile: Profile): """ self._profile = profile self._route_manager = profile.inject(RouteManager) - self._logger: logging.Logger = get_logger_inst( - profile=self._profile, - logger_name=__name__, - ) + self._logger = logging.getLogger(__name__) async def create_did_document( self, diff --git a/aries_cloudagent/core/event_bus.py b/aries_cloudagent/core/event_bus.py index d314bb3c3f..22d7c8f922 100644 --- a/aries_cloudagent/core/event_bus.py +++ b/aries_cloudagent/core/event_bus.py @@ -97,6 +97,7 @@ async def notify(self, profile: "Profile", event: Event): # TODO don't block notifier until subscribers have all been called? # TODO trigger each processor but don't await? # TODO log errors but otherwise ignore? + LOGGER.debug("Notifying subscribers: %s", event) partials = [] From 0daf2cbacfa398fca675a2365e4f6f554eedc855 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Sun, 10 Sep 2023 01:26:16 +0530 Subject: [PATCH 13/18] test fix Signed-off-by: Shaanjot Gill --- aries_cloudagent/config/logging.py | 2 ++ aries_cloudagent/config/tests/test_logging.py | 28 ------------------- aries_cloudagent/core/oob_processor.py | 1 - 3 files changed, 2 insertions(+), 29 deletions(-) diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index 953af10144..9a99a0ea76 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -40,9 +40,11 @@ class ContextFilter(logging.Filter): """Custom logging Filter to adapt logs with contextual wallet_id.""" def __init__(self): + """Initialize an instance of Custom logging.Filter.""" super(ContextFilter, self).__init__() def filter(self, record): + """Filter LogRecords and add wallet id to them.""" try: wallet_id = context_wallet_id.get() record.wallet_id = wallet_id diff --git a/aries_cloudagent/config/tests/test_logging.py b/aries_cloudagent/config/tests/test_logging.py index ef81af1404..0b8016fb13 100644 --- a/aries_cloudagent/config/tests/test_logging.py +++ b/aries_cloudagent/config/tests/test_logging.py @@ -1,5 +1,4 @@ import contextlib -import logging from io import StringIO @@ -8,11 +7,6 @@ from .. import logging as test_module -from ...core.in_memory import InMemoryProfile -from ...wallet.base import BaseWallet -from ...wallet.did_method import SOV, DIDMethods -from ...wallet.key_type import ED25519 - class TestLoggingConfigurator(AsyncTestCase): agent_label_arg_value = "Aries Cloud Agent" @@ -98,25 +92,3 @@ def test_load_resource(self): test_module.pkg_resources, "resource_stream", async_mock.MagicMock() ) as mock_res_stream: test_module.load_resource("abc:def", encoding=None) - - def test_get_logger_with_handlers(self): - profile = InMemoryProfile.test_profile() - profile.settings["log.file"] = "test_file.log" - logger = logging.getLogger(__name__) - logger = test_module.get_logger_with_handlers( - settings=profile.settings, - logger=logger, - at_when="m", - interval=1, - backup_count=1, - ) - assert logger - logger = test_module.get_logger_with_handlers( - settings=profile.settings, - logger=logger, - did_ident="tenant_did_123", - at_when="m", - interval=1, - backup_count=1, - ) - assert logger diff --git a/aries_cloudagent/core/oob_processor.py b/aries_cloudagent/core/oob_processor.py index c327b6d234..d1305aca3a 100644 --- a/aries_cloudagent/core/oob_processor.py +++ b/aries_cloudagent/core/oob_processor.py @@ -118,7 +118,6 @@ async def find_oob_record_for_inbound_message( """Find oob record for inbound message.""" message_type = context.message._type oob_record = None - profile = context.profile async with context.profile.session() as session: # First try to find the oob record based on the associated pthid if context.message_receipt.parent_thread_id: From 2d7cfb6da885b110f347bc7b7c7e53de9f45087a Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Sun, 10 Sep 2023 01:58:35 +0530 Subject: [PATCH 14/18] retrigger checks Signed-off-by: Shaanjot Gill From 5f1c374336e0cbd74fd1dc6a020fbb9061bc4a25 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Tue, 12 Sep 2023 01:18:40 +0530 Subject: [PATCH 15/18] update test Signed-off-by: Shaanjot Gill --- aries_cloudagent/config/tests/test_logging.py | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/aries_cloudagent/config/tests/test_logging.py b/aries_cloudagent/config/tests/test_logging.py index 0b8016fb13..848c8267bb 100644 --- a/aries_cloudagent/config/tests/test_logging.py +++ b/aries_cloudagent/config/tests/test_logging.py @@ -26,6 +26,62 @@ def test_configure_default(self, mock_file_config, mock_load_resource): mock_load_resource.return_value, disable_existing_loggers=False ) + def test_configure_with_per_tenant_config_file(self): + with async_mock.patch.object( + test_module, + "logging", + async_mock.MagicMock( + basicConfig=async_mock.MagicMock(), + FileHandler=async_mock.MagicMock(), + root=async_mock.MagicMock( + warning=async_mock.MagicMock(), + handlers=[], + ), + ), + ): + test_module.LoggingConfigurator.configure( + logging_config_path="aries_cloudagent.config:default_per_tenant_logging_config.ini", + log_file="test.log", + multitenant=True, + ) + + def test_configure_with_per_tenant_yml_file(self): + with async_mock.patch.object( + test_module, + "logging", + async_mock.MagicMock( + basicConfig=async_mock.MagicMock(), + FileHandler=async_mock.MagicMock(), + root=async_mock.MagicMock( + warning=async_mock.MagicMock(), + handlers=[], + ), + ), + ): + test_module.LoggingConfigurator.configure( + logging_config_path="aries_cloudagent/config/default_per_tenant_logging_config.yml", + log_file="test.log", + multitenant=True, + ) + + def test_configure_with_default_config(self): + with async_mock.patch.object( + test_module, + "logging", + async_mock.MagicMock( + basicConfig=async_mock.MagicMock(), + FileHandler=async_mock.MagicMock(), + root=async_mock.MagicMock( + warning=async_mock.MagicMock(), + handlers=[], + ), + ), + ): + test_module.LoggingConfigurator.configure( + log_file="test.log", + multitenant=True, + ) + def test_configure_default_no_resource(self): with async_mock.patch.object( test_module, "load_resource", async_mock.MagicMock() From 46b8083da728ea1504c36ed6a66ab76fa7cbca77 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Sun, 17 Sep 2023 02:48:57 +0530 Subject: [PATCH 16/18] optimization and test updates Signed-off-by: Shaanjot Gill --- aries_cloudagent/admin/server.py | 6 ++++ aries_cloudagent/config/logging.py | 9 ++--- .../indy/sdk/tests/test_profile.py | 25 ++++++++------ aries_cloudagent/multitenant/base.py | 4 --- .../handlers/tests/test_keylist_handler.py | 34 +++++++++++-------- .../messages/tests/test_problem_report.py | 12 ++++--- .../v1_0/tests/test_mediation_manager.py | 14 ++++---- .../messages/tests/test_problem_report.py | 11 ++++-- .../tests/test_credential_problem_report.py | 12 ++++--- .../tests/test_cred_problem_report.py | 10 ++++-- .../messages/tests/test_problem_report.py | 12 ++++--- 11 files changed, 91 insertions(+), 58 deletions(-) diff --git a/aries_cloudagent/admin/server.py b/aries_cloudagent/admin/server.py index 61b3b61630..9521a991b8 100644 --- a/aries_cloudagent/admin/server.py +++ b/aries_cloudagent/admin/server.py @@ -22,6 +22,7 @@ from marshmallow import fields from ..config.injection_context import InjectionContext +from ..config.logging import context_wallet_id from ..core.event_bus import Event, EventBus from ..core.plugin_registry import PluginRegistry from ..core.profile import Profile @@ -407,6 +408,11 @@ async def setup_context(request: web.Request, handler): ) = self.multitenant_manager.get_wallet_details_from_token( token=token ) + try: + context_wallet_id.get() + except LookupError: + wallet_id = profile.settings.get("wallet.id") + context_wallet_id.set(wallet_id) meta_data = { "wallet_id": walletid, "wallet_key": walletkey, diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index 9a99a0ea76..82eef5deaf 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -113,7 +113,7 @@ def configure( else: logging.basicConfig(level=logging.WARNING) logging.root.warning(f"Logging config file not found: {config_path}") - if log_file and multitenant: + if multitenant: file_handler_set = False handler_pattern = None # Create context filter to adapt wallet_id in logger messages @@ -128,7 +128,9 @@ def configure( _handler.setFormatter(jsonlogger.JsonFormatter(handler_pattern)) # Add context filter to handlers _handler.addFilter(_cf) - if not file_handler_set: + if log_level: + _handler.setLevel(log_level.upper()) + if not file_handler_set and log_file: file_path = os.path.join( os.path.dirname(os.path.realpath(__file__)).replace( "aries_cloudagent/config", "" @@ -156,8 +158,7 @@ def configure( logging.FileHandler(log_file, encoding="utf-8") ) if log_level: - log_level = log_level.upper() - logging.root.setLevel(log_level) + logging.root.setLevel(log_level.upper()) @classmethod def print_banner( diff --git a/aries_cloudagent/indy/sdk/tests/test_profile.py b/aries_cloudagent/indy/sdk/tests/test_profile.py index 9440adc605..0c9f2e2e94 100644 --- a/aries_cloudagent/indy/sdk/tests/test_profile.py +++ b/aries_cloudagent/indy/sdk/tests/test_profile.py @@ -1,5 +1,3 @@ -import logging - from asynctest import mock as async_mock import pytest @@ -11,6 +9,8 @@ from ..profile import IndySdkProfile from ..wallet_setup import IndyOpenWallet, IndyWalletConfig +from .. import profile as test_module + @pytest.fixture async def open_wallet(): @@ -118,12 +118,15 @@ def test_read_only(open_wallet): ro_profile = IndySdkProfile(open_wallet, context) -def test_finalizer(open_wallet, caplog): - def _smaller_scope(): - profile = IndySdkProfile(open_wallet) - assert profile - - with caplog.at_level(logging.DEBUG): - _smaller_scope() - - assert "finalizer called" in caplog.text +def test_finalizer(open_wallet): + profile = IndySdkProfile(open_wallet) + assert profile + with async_mock.patch.object( + test_module, "LOGGER", async_mock.MagicMock() + ) as mock_logger: + mock_logger.debug = async_mock.MagicMock() + profile._finalizer() + assert mock_logger.debug.call_count == 1 + mock_logger.debug.assert_called_once_with( + "Profile finalizer called; closing wallet" + ) diff --git a/aries_cloudagent/multitenant/base.py b/aries_cloudagent/multitenant/base.py index 832aaf9e7c..c71eb8ac8c 100644 --- a/aries_cloudagent/multitenant/base.py +++ b/aries_cloudagent/multitenant/base.py @@ -8,7 +8,6 @@ import jwt from ..config.injection_context import InjectionContext -from ..config.logging import context_wallet_id from ..core.error import BaseError from ..core.profile import Profile, ProfileSession from ..protocols.coordinate_mediation.v1_0.manager import ( @@ -202,9 +201,6 @@ async def create_wallet( await profile.inject(RouteManager).route_verkey( profile, public_did_info.verkey ) - # add wallet id contextVar for logging - wallet_id = profile.settings.get("wallet.id") - context_wallet_id.set(wallet_id) except Exception: await wallet_record.delete_record(session) raise diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_handler.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_handler.py index 695629cf91..62649002b2 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_handler.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/handlers/tests/test_keylist_handler.py @@ -1,8 +1,8 @@ """Test keylist handler.""" -import logging - import pytest +from asynctest import mock as async_mock + from ......connections.models.conn_record import ConnRecord from ......messaging.base_handler import HandlerException from ......messaging.request_context import RequestContext @@ -11,6 +11,8 @@ from ...models.mediation_record import MediationRecord from ..keylist_handler import KeylistHandler +from .. import keylist_handler as test_module + TEST_CONN_ID = "conn-id" pytestmark = pytest.mark.asyncio @@ -44,16 +46,20 @@ async def test_handler_no_active_connection(self, context): await handler.handle(context, responder) assert "inactive connection" in exc.value - async def test_handler_no_record(self, context, caplog): - caplog.set_level(logging.INFO) - handler, responder = KeylistHandler(), MockResponder() - await handler.handle(context, responder) - assert "not acting as mediator" in caplog.text - assert "Keylist received: " not in caplog.text + async def test_handler_no_record(self, context): + with async_mock.patch.object( + test_module, "LOG", async_mock.MagicMock() + ) as mock_logger: + handler, responder = KeylistHandler(), MockResponder() + await handler.handle(context, responder) + assert mock_logger.warning.call_count == 1 + assert mock_logger.info.call_count == 0 - async def test_handler(self, context, session, caplog): - caplog.set_level(logging.INFO) - handler, responder = KeylistHandler(), MockResponder() - await MediationRecord(connection_id=TEST_CONN_ID).save(session) - await handler.handle(context, responder) - assert "Keylist received: " in caplog.text + async def test_handler(self, context, session): + with async_mock.patch.object( + test_module, "LOG", async_mock.MagicMock() + ) as mock_logger: + handler, responder = KeylistHandler(), MockResponder() + await MediationRecord(connection_id=TEST_CONN_ID).save(session) + await handler.handle(context, responder) + assert mock_logger.info.call_count == 1 diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/tests/test_problem_report.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/tests/test_problem_report.py index 322ae27f5a..29a2da6595 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/tests/test_problem_report.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/messages/tests/test_problem_report.py @@ -1,7 +1,7 @@ """Test Problem Report Message.""" -import logging import pytest +from asynctest import mock as async_mock from unittest import TestCase from ......messaging.models.base import BaseModelError @@ -13,6 +13,8 @@ ValidationError, ) +from .. import problem_report as test_module + class TestCMProblemReportMessage(TestCase): """Test problem report.""" @@ -53,6 +55,8 @@ def test_validate_and_logger(self): "code": "invalid_code", }, ).serialize() - self._caplog.set_level(logging.WARNING) - CMProblemReportSchema().validate_fields(data) - assert "Unexpected error code received" in self._caplog.text + with async_mock.patch.object( + test_module, "LOGGER", async_mock.MagicMock() + ) as mock_logger: + CMProblemReportSchema().validate_fields(data) + assert mock_logger.warning.call_count == 1 diff --git a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py index 5ccab85c5f..69cdf9760f 100644 --- a/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py +++ b/aries_cloudagent/protocols/coordinate_mediation/v1_0/tests/test_mediation_manager.py @@ -1,5 +1,4 @@ """Test MediationManager.""" -import logging from typing import AsyncIterable, Iterable from asynctest import mock as async_mock @@ -454,9 +453,8 @@ async def test_store_update_results_exists_relay(self, session, manager): assert route.wallet_id == "test_wallet" assert route.connection_id == TEST_CONN_ID - async def test_store_update_results_errors(self, caplog, manager): + async def test_store_update_results_errors(self, manager): """test_store_update_results with errors.""" - caplog.set_level(logging.WARNING) results = [ KeylistUpdated( recipient_key=TEST_VERKEY, @@ -474,11 +472,11 @@ async def test_store_update_results_errors(self, caplog, manager): result=KeylistUpdated.RESULT_CLIENT_ERROR, ), ] - await manager.store_update_results(TEST_CONN_ID, results) - assert "no_change" in caplog.text - assert "client_error" in caplog.text - assert "server_error" in caplog.text - print(caplog.text) + with async_mock.patch.object( + test_module, "LOGGER", async_mock.MagicMock() + ) as mock_logger: + await manager.store_update_results(TEST_CONN_ID, results) + assert mock_logger.warning.call_count == 3 async def test_get_my_keylist(self, session, manager): """test_get_my_keylist.""" diff --git a/aries_cloudagent/protocols/didexchange/v1_0/messages/tests/test_problem_report.py b/aries_cloudagent/protocols/didexchange/v1_0/messages/tests/test_problem_report.py index 03af260b1a..34fa28421c 100644 --- a/aries_cloudagent/protocols/didexchange/v1_0/messages/tests/test_problem_report.py +++ b/aries_cloudagent/protocols/didexchange/v1_0/messages/tests/test_problem_report.py @@ -1,10 +1,13 @@ import pytest +from asynctest import mock as async_mock + from ......messaging.models.base import BaseModelError from .....didcomm_prefix import DIDCommPrefix from ...message_types import PROBLEM_REPORT from ..problem_report import DIDXProblemReport +from .. import problem_report as test_module THID = "dummy-thid" PTHID = "dummy-pthid" @@ -31,9 +34,11 @@ def test_missing_code(): DIDXProblemReport.deserialize({"description": {"en": "test"}}) -def test_unrecognized_code(caplog): - with caplog.at_level("DEBUG"): +def test_unrecognized_code(): + with async_mock.patch.object( + test_module, "LOGGER", async_mock.MagicMock() + ) as mock_logger: DIDXProblemReport.deserialize( {"description": {"code": "unknown", "en": "test"}} ) - assert "Unexpected error code received" in caplog.text + assert mock_logger.warning.call_count == 1 diff --git a/aries_cloudagent/protocols/issue_credential/v1_0/messages/tests/test_credential_problem_report.py b/aries_cloudagent/protocols/issue_credential/v1_0/messages/tests/test_credential_problem_report.py index fc87a911fa..97d14785d7 100644 --- a/aries_cloudagent/protocols/issue_credential/v1_0/messages/tests/test_credential_problem_report.py +++ b/aries_cloudagent/protocols/issue_credential/v1_0/messages/tests/test_credential_problem_report.py @@ -1,6 +1,6 @@ -import logging import pytest +from asynctest import mock as async_mock from unittest import mock, TestCase from ......messaging.models.base import BaseModelError @@ -16,6 +16,8 @@ ValidationError, ) +from .. import credential_problem_report as test_module + class TestCredentialProblemReport(TestCase): """Problem report tests.""" @@ -105,6 +107,8 @@ def test_validate_and_logger(self): "code": "invalid_code", }, ).serialize() - self._caplog.set_level(logging.WARNING) - CredentialProblemReportSchema().validate_fields(data) - assert "Unexpected error code received" in self._caplog.text + with async_mock.patch.object( + test_module, "LOGGER", async_mock.MagicMock() + ) as mock_logger: + CredentialProblemReportSchema().validate_fields(data) + assert mock_logger.warning.call_count == 1 diff --git a/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_problem_report.py b/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_problem_report.py index 2389668065..aff6f7f798 100644 --- a/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_problem_report.py +++ b/aries_cloudagent/protocols/issue_credential/v2_0/messages/tests/test_cred_problem_report.py @@ -1,6 +1,7 @@ import logging import pytest +from asynctest import mock as async_mock from unittest import mock, TestCase from ......messaging.models.base import BaseModelError @@ -16,6 +17,8 @@ ValidationError, ) +from .. import cred_problem_report as test_module + class TestCredProblemReport(TestCase): """Problem report tests.""" @@ -100,8 +103,11 @@ def test_validate_and_logger(self): }, ).serialize() self._caplog.set_level(logging.WARNING) - V20CredProblemReportSchema().validate_fields(data) - assert "Unexpected error code received" in self._caplog.text + with async_mock.patch.object( + test_module, "LOGGER", async_mock.MagicMock() + ) as mock_logger: + V20CredProblemReportSchema().validate_fields(data) + assert mock_logger.warning.call_count == 1 def test_validate_x(self): """Exercise validation requirements.""" diff --git a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_problem_report.py b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_problem_report.py index 831d109b9f..17dc35ef4e 100644 --- a/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_problem_report.py +++ b/aries_cloudagent/protocols/out_of_band/v1_0/messages/tests/test_problem_report.py @@ -1,7 +1,7 @@ """Test Problem Report Message.""" -import logging import pytest +from asynctest import mock as async_mock from unittest import TestCase from ......messaging.models.base import BaseModelError @@ -13,6 +13,8 @@ ValidationError, ) +from .. import problem_report as test_module + class TestOOBProblemReportMessage(TestCase): """Test problem report.""" @@ -70,9 +72,11 @@ def test_validate_and_logger(self): ) data.assign_thread_id(thid="test_thid", pthid="test_pthid") data = data.serialize() - self._caplog.set_level(logging.WARNING) - OOBProblemReportSchema().validate_fields(data) - assert "Unexpected error code received" in self._caplog.text + with async_mock.patch.object( + test_module, "LOGGER", async_mock.MagicMock() + ) as mock_logger: + OOBProblemReportSchema().validate_fields(data) + assert mock_logger.warning.call_count == 1 def test_assign_msg_type_version_to_model_inst(self): test_msg = OOBProblemReport() From cffa9cee879bafce5240be589fe30b59191f27ac Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Mon, 18 Sep 2023 19:20:12 +0530 Subject: [PATCH 17/18] doc update Signed-off-by: Shaanjot Gill --- Logging.md | 76 +++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 67 insertions(+), 9 deletions(-) diff --git a/Logging.md b/Logging.md index 7892409afc..cef5268668 100644 --- a/Logging.md +++ b/Logging.md @@ -12,16 +12,15 @@ Other log levels fall back to `WARNING`. * `--log-level` - The log level to log on std out. * `--log-file` - Path to a file to log to. +* `--log-config` - Specifies a custom logging configuration file -## WIP - add config file details -* `--log-handler-config` - Specifies `when`, `interval`, `backupCount` for the `TimedRotatingFileMultiProcessHandler`. These 3 attributes are passed as a `;` seperated string. For example, `when` of d (days), `interval` of 7 and `backupCount` of 1 will be passed as `D;7;1`. Note: `backupCount` of 0 will mean all backup log files will be retained and not deleted at all. More details about these attributes can be found [here](https://docs.python.org/3/library/logging.handlers.html#timedrotatingfilehandler). `TimedRotatingFileMultiProcessHandler` supports the ability to cleanup logs by time and mantain backup logs and a custom JSON formatter for logs. -* `--log-fmt-pattern` - Specifies logging.Formatter pattern to override default patterns. -* `--log-json-fmt` - Specifies whether to use JSON logging formatter or text logging formatter. Defaults to `False`. Example: ```sh -./bin/aca-py start --log-level debug --log-file acapy.log --log-handler-config "d;7;1" --log-fmt-pattern "%(asctime)s %(wallet_id)s %(filename)s %(lineno)d %(message)s" --log-json-fmt +./bin/aca-py start --log-level debug --log-file acapy.log --log-config aries_cloudagent.config:default_per_tenant_logging_config.ini + +./bin/aca-py start --log-level debug --log-file acapy.log --log-config ./aries_cloudagent/config/default_per_tenant_logging_config.yml ``` ## Environment Variables @@ -29,14 +28,11 @@ Example: The log level can be configured using the environment variable `ACAPY_LOG_LEVEL`. The log file can be set by `ACAPY_LOG_FILE`. The log config can be set by `ACAPY_LOG_CONFIG`. -The log rotating file handler config can be set by `ACAPY_LOG_HANDLER_CONFIG`. -The log formatter pattern can be set by `ACAPY_LOG_FMT_PATTERN`. -The log json formatter flag can be set by `ACAPY_LOG_JSON_FMT`. Example: ```sh -ACAPY_LOG_LEVEL=info ACAPY_LOG_FILE=./acapy.log ACAPY_LOG_CONFIG=./acapy_log.ini ACAPY_LOG_HANDLER_CONFIG="d;7;1" ./bin/aca-py start +ACAPY_LOG_LEVEL=info ACAPY_LOG_FILE=./acapy.log ACAPY_LOG_CONFIG=./acapy_log.ini ./bin/aca-py start ``` ## Acapy Config File @@ -54,7 +50,69 @@ Both parameters are independent of the log level, which means: Also if log-level is set to WARNING, connections and presentations will be logged like in debug log level. ## Log config file +The path to config file is provided via `--log-config`. Find an example in [default_logging_config.ini](aries_cloudagent/config/default_logging_config.ini). You can find more detail description in the [logging documentation](https://docs.python.org/3/howto/logging.html#configuring-logging). + + +For per tenant logging, find an example in [default_per_tenant_logging_config.ini](aries_cloudagent/config/default_per_tenant_logging_config.ini), which sets up `TimedRotatingFileMultiProcessHandler` and `StreamHandler` handlers. Custom `TimedRotatingFileMultiProcessHandler` handler supports the ability to cleanup logs by time and mantain backup logs and a custom JSON formatter for logs. The arguments for it such as `file name`, `when`, `interval` and `backupCount` can be passed as `args=('acapy.log', 'd', 7, 1,)` [also shown below]. Note: `backupCount` of 0 will mean all backup log files will be retained and not deleted at all. More details about these attributes can be found [here](https://docs.python.org/3/library/logging.handlers.html#timedrotatingfilehandler) + +``` +[loggers] +keys=root + +[handlers] +keys=stream_handler, timed_file_handler + +[formatters] +keys=formatter + +[logger_root] +level=ERROR +handlers=stream_handler, timed_file_handler + +[handler_stream_handler] +class=StreamHandler +level=DEBUG +formatter=formatter +args=(sys.stderr,) + +[handler_timed_file_handler] +class=logging.handlers.TimedRotatingFileMultiProcessHandler +level=DEBUG +formatter=formatter +args=('acapy.log', 'd', 7, 1,) + +[formatter_formatter] +format=%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s +``` + +For `DictConfig` [`dict` logging config file], find an example in [default_per_tenant_logging_config.yml](aries_cloudagent/config/default_per_tenant_logging_config.yml) with same attributes as `default_per_tenant_logging_config.ini` file. + +``` +version: 1 +formatters: + default: + format: '%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s' +handlers: + console: + class: logging.StreamHandler + level: DEBUG + formatter: default + stream: ext://sys.stderr + rotating_file: + class: logging.handlers.TimedRotatingFileMultiProcessHandler + level: DEBUG + filename: 'acapy.log' + when: 'd' + interval: 7 + backupCount: 1 + formatter: default +root: + level: INFO + handlers: + - console + - rotating_file +``` From 8d8859f460a19b0c4949224bf5c3d7e564f11578 Mon Sep 17 00:00:00 2001 From: Shaanjot Gill Date: Mon, 16 Oct 2023 21:09:19 +0530 Subject: [PATCH 18/18] updates based on feedback Signed-off-by: Shaanjot Gill --- aries_cloudagent/config/logging.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/aries_cloudagent/config/logging.py b/aries_cloudagent/config/logging.py index 82eef5deaf..7c31996963 100644 --- a/aries_cloudagent/config/logging.py +++ b/aries_cloudagent/config/logging.py @@ -23,15 +23,15 @@ from .banner import Banner DEFAULT_LOGGING_CONFIG_PATH = "aries_cloudagent.config:default_logging_config.ini" -DEFAULT_PER_TENANT_LOGGING_CONFIG_PATH = ( - "./aries_cloudagent/config/default_per_tenant_logging_config.yml" +# DEFAULT_PER_TENANT_LOGGING_CONFIG_PATH_YAML = ( +# "./aries_cloudagent/config/default_per_tenant_logging_config.yml" +# ) +DEFAULT_PER_TENANT_LOGGING_CONFIG_PATH_INI = ( + "aries_cloudagent.config:default_per_tenant_logging_config.ini" ) LOG_FORMAT_FILE_ALIAS_PATTERN = ( "%(asctime)s %(wallet_id)s %(levelname)s %(pathname)s:%(lineno)d %(message)s" ) -LOG_FORMAT_STREAM_PATTERN = ( - "%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(message)s" -) context_wallet_id: ContextVar[str] = ContextVar("context_wallet_id") @@ -97,7 +97,10 @@ def configure( if logging_config_path is not None: config_path = logging_config_path else: - config_path = DEFAULT_LOGGING_CONFIG_PATH + if multitenant: + config_path = DEFAULT_PER_TENANT_LOGGING_CONFIG_PATH_INI + else: + config_path = DEFAULT_LOGGING_CONFIG_PATH if ".yml" in config_path or ".yaml" in config_path: is_dict_config = True with open(config_path, "r") as stream: