Skip to content

Commit

Permalink
chore(core): improve logging control and experience (#610)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dacksus authored Jan 22, 2025
1 parent 3b7969e commit 229cae0
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 8 deletions.
6 changes: 4 additions & 2 deletions python/src/uagents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
RestMethod,
RestPostHandler,
)
from uagents.utils import get_logger
from uagents.utils import get_logger, set_global_log_level


async def _run_interval(
Expand Down Expand Up @@ -329,6 +329,8 @@ def __init__(

# initialize wallet and identity
self._initialize_wallet_and_identity(seed, name, wallet_key_derivation_index)
if log_level != logging.INFO:
set_global_log_level(log_level)
self._logger = get_logger(self.name, level=log_level)

self._agentverse = parse_agentverse_config(agentverse)
Expand Down Expand Up @@ -379,7 +381,6 @@ def __init__(
self._wallet,
self._almanac_contract,
self._test,
logger=self._logger,
almanac_api=self._almanac_api_url,
)
self._metadata = self._initialize_metadata(metadata)
Expand Down Expand Up @@ -726,6 +727,7 @@ def sign_digest(self, digest: bytes) -> str:
"""
return self._identity.sign_digest(digest)

# TODO this is not used anywhere in the framework
def sign_registration(
self, timestamp: int, sender_wallet_address: Optional[str] = None
) -> str:
Expand Down
11 changes: 7 additions & 4 deletions python/src/uagents/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,11 @@ def check_version(self) -> bool:
"Update uAgents to the latest version to enable contract interactions.",
)
return False
except Exception:
except Exception as e:
logger.error(
"Failed to query contract version. Contract interactions will be disabled."
)
logger.debug(e)
return False
return True

Expand All @@ -210,7 +211,8 @@ def query_contract(self, query_msg: Dict[str, Any]) -> Any:
raise ValueError("Invalid response format")
return response
except Exception as e:
logger.error(f"Query failed: {e}")
logger.error(f"Query failed with error: {e.__class__.__name__}.")
logger.debug(e)
raise

def get_contract_version(self) -> str:
Expand Down Expand Up @@ -528,15 +530,16 @@ def query_contract(self, query_msg: Dict[str, Any]) -> Any:
Any: The query response.
Raises:
RuntimeError: If the contract address is not set or the query fails.
ValueError: If the response from contract is not a dict.
"""
try:
response = self.query(query_msg)
if not isinstance(response, dict):
raise ValueError("Invalid response format")
return response
except Exception as e:
logger.error(f"Query failed: {e}")
logger.error(f"Querying NameServiceContract failed for query {query_msg}.")
logger.debug(e)
raise

def is_name_available(self, name: str, domain: str) -> bool:
Expand Down
15 changes: 13 additions & 2 deletions python/src/uagents/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,8 +440,12 @@ async def register(
self._logger.warning(
f"Failed to register on Almanac API: {e.__class__.__name__}"
)
self._logger.debug(e)

if self._ledger_policy is None:
self._logger.info(
"No Ledger available. Skipping registration on Almanac contract."
)
return

# schedule the ledger registration
Expand All @@ -455,7 +459,10 @@ async def register(
)
raise
except Exception as e:
self._logger.error(f"Failed to register on Almanac contract: {e}")
self._logger.error(
f"Failed to register on Almanac contract: {e.__class__.__name__}"
)
self._logger.debug(e)
raise


Expand Down Expand Up @@ -504,6 +511,7 @@ async def register(self):
self._logger.warning(
f"Failed to batch register on Almanac API: {e.__class__.__name__}"
)
self._logger.debug(e)

if self._ledger_policy is None:
return
Expand All @@ -517,5 +525,8 @@ async def register(self):
)
raise
except Exception as e:
self._logger.error(f"Failed to batch register on Almanac contract: {e}")
self._logger.error(
f"Failed to batch register on Almanac contract: {e.__class__.__name__}"
)
self._logger.debug(e)
raise
15 changes: 15 additions & 0 deletions python/src/uagents/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,19 @@ def log(logger: Optional[logging.Logger], level: int, message: str):
BACKUP_LOGGER.log(level, message)


def set_global_log_level(level: Union[int, str]):
"""
Set the log level for all modules globally. Can still be overruled manually.
Args:
level (Union[int, str]): The logging level as defined in _logging_.
"""
logging.basicConfig(level=level)
# the manager of the root logger should be its only instance and contain
# all loggers of the process. Update the new log level in all of them.
for name in logging.Logger.manager.loggerDict:
# TODO only apply to framework loggers?
logging.getLogger(name).setLevel(level)


BACKUP_LOGGER = get_logger("uagents", logging.INFO)

0 comments on commit 229cae0

Please sign in to comment.