Skip to content

Commit

Permalink
Allow enabling debug logging
Browse files Browse the repository at this point in the history
  • Loading branch information
itssimon committed Oct 31, 2023
1 parent 263ee3f commit 91f0423
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 6 deletions.
9 changes: 7 additions & 2 deletions apitally/client/asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@
ApitallyClientBase,
ApitallyKeyCacheBase,
)
from apitally.client.logging import get_logger


logger = logging.getLogger(__name__)
logger = get_logger(__name__)
retry = partial(
backoff.on_exception,
backoff.expo,
httpx.HTTPError,
max_tries=3,
logger=logger,
giveup_log_level=logging.WARNING,
)

Expand Down Expand Up @@ -116,7 +118,7 @@ async def get_keys(self, client: httpx.AsyncClient) -> None:
self.handle_keys_response(response_data)
self._keys_updated_at = time.time()
elif self.key_registry.salt is None: # pragma: no cover
logger.error("Initial Apitally API key sync failed")
logger.critical("Initial Apitally API key sync failed")
# Exit because the application will not be able to authenticate requests
sys.exit(1)
elif (self._keys_updated_at is not None and time.time() - self._keys_updated_at > MAX_QUEUE_TIME) or (
Expand All @@ -126,6 +128,7 @@ async def get_keys(self, client: httpx.AsyncClient) -> None:

@retry(raise_on_giveup=False)
async def _send_app_info(self, client: httpx.AsyncClient, payload: Dict[str, Any]) -> None:
logger.debug("Sending app info")
response = await client.post(url="/info", json=payload, timeout=REQUEST_TIMEOUT)
if response.status_code == 404 and "Client ID" in response.text:
self.stop_sync_loop()
Expand All @@ -137,11 +140,13 @@ async def _send_app_info(self, client: httpx.AsyncClient, payload: Dict[str, Any

@retry()
async def _send_requests_data(self, client: httpx.AsyncClient, payload: Dict[str, Any]) -> None:
logger.debug("Sending requests data")
response = await client.post(url="/requests", json=payload)
response.raise_for_status()

@retry(raise_on_giveup=False)
async def _get_keys(self, client: httpx.AsyncClient) -> Dict[str, Any]:
logger.debug("Updating API keys")
response = await client.get(url="/keys")
response.raise_for_status()
return response.json()
5 changes: 3 additions & 2 deletions apitally/client/base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import json
import logging
import os
import re
import threading
Expand All @@ -15,8 +14,10 @@
from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union, cast
from uuid import UUID, uuid4

from apitally.client.logging import get_logger

logger = logging.getLogger(__name__)

logger = get_logger(__name__)

HUB_BASE_URL = os.getenv("APITALLY_HUB_BASE_URL") or "https://hub.apitally.io"
HUB_VERSION = "v1"
Expand Down
17 changes: 17 additions & 0 deletions apitally/client/logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import logging
import os


debug = os.getenv("APITALLY_DEBUG", "false").lower() in {"true", "yes", "y", "1"}
root_logger = logging.getLogger("apitally")

if debug:
root_logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s [%(name)s] %(levelname)s: %(message)s")
console_handler.setFormatter(formatter)
root_logger.addHandler(console_handler)


def get_logger(name: str) -> logging.Logger:
return logging.getLogger(name)
9 changes: 7 additions & 2 deletions apitally/client/threading.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@
ApitallyClientBase,
ApitallyKeyCacheBase,
)
from apitally.client.logging import get_logger


logger = logging.getLogger(__name__)
logger = get_logger(__name__)
retry = partial(
backoff.on_exception,
backoff.expo,
requests.RequestException,
max_tries=3,
logger=logger,
giveup_log_level=logging.WARNING,
)

Expand Down Expand Up @@ -132,7 +134,7 @@ def get_keys(self, session: requests.Session) -> None:
self.handle_keys_response(response_data)
self._keys_updated_at = time.time()
elif self.key_registry.salt is None: # pragma: no cover
logger.error("Initial Apitally API key sync failed")
logger.critical("Initial Apitally API key sync failed")
# Exit because the application will not be able to authenticate requests
sys.exit(1)
elif (self._keys_updated_at is not None and time.time() - self._keys_updated_at > MAX_QUEUE_TIME) or (
Expand All @@ -142,6 +144,7 @@ def get_keys(self, session: requests.Session) -> None:

@retry(raise_on_giveup=False)
def _send_app_info(self, session: requests.Session, payload: Dict[str, Any]) -> None:
logger.debug("Sending app info")
response = session.post(url=f"{self.hub_url}/info", json=payload, timeout=REQUEST_TIMEOUT)
if response.status_code == 404 and "Client ID" in response.text:
self.stop_sync_loop()
Expand All @@ -153,11 +156,13 @@ def _send_app_info(self, session: requests.Session, payload: Dict[str, Any]) ->

@retry()
def _send_requests_data(self, session: requests.Session, payload: Dict[str, Any]) -> None:
logger.debug("Sending requests data")
response = session.post(url=f"{self.hub_url}/requests", json=payload, timeout=REQUEST_TIMEOUT)
response.raise_for_status()

@retry(raise_on_giveup=False)
def _get_keys(self, session: requests.Session) -> Dict[str, Any]:
logger.debug("Updating API keys")
response = session.get(url=f"{self.hub_url}/keys", timeout=REQUEST_TIMEOUT)
response.raise_for_status()
return response.json()

0 comments on commit 91f0423

Please sign in to comment.