Skip to content

Commit 795ecc3

Browse files
adding log messages with pkg_infra.logger
1 parent 4844d34 commit 795ecc3

7 files changed

Lines changed: 211 additions & 36 deletions

File tree

omnipath_client/_client.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,18 @@
33
from __future__ import annotations
44

55
from typing import Any
6-
import logging
76

8-
from omnipath_client._query import QueryBuilder
9-
from omnipath_client._types import BackendType
10-
from omnipath_client._download import Downloader
11-
from omnipath_client._response import parse_response
127
from omnipath_client._constants import DEFAULT_BASE_URL
8+
from omnipath_client._download import Downloader
139
from omnipath_client._endpoints import ParamDef, EndpointDef
1410
from omnipath_client._inventory import Inventory
11+
from omnipath_client._query import QueryBuilder
12+
from omnipath_client._response import parse_response
13+
from omnipath_client._session import get_logger, get_session
14+
from omnipath_client._types import BackendType
1515

1616

17-
logger = logging.getLogger(__name__)
17+
logger = get_logger(__name__)
1818

1919

2020
class OmniPath:
@@ -36,12 +36,20 @@ def __init__(
3636
cache: bool = True,
3737
) -> None:
3838

39+
get_session()
40+
3941
self._base_url = base_url.rstrip('/')
4042
self._backend = backend
4143
self._inventory = Inventory(base_url=self._base_url)
4244
self._inventory.load()
4345
self._query_builder = QueryBuilder(self._inventory)
4446
self._downloader = Downloader(use_cache=cache)
47+
logger.info(
48+
'Initialized OmniPath client with base_url=%s backend=%s cache=%s',
49+
self._base_url,
50+
self._backend,
51+
cache,
52+
)
4553

4654
def _fetch(
4755
self,
@@ -51,16 +59,29 @@ def _fetch(
5159
) -> Any:
5260
"""Internal: build query, download, parse response."""
5361

62+
logger.info(
63+
'Starting request workflow for endpoint=%s backend=%s',
64+
endpoint,
65+
backend or self._backend,
66+
)
5467
query = self._query_builder.build(endpoint, **params)
5568
result = self._downloader.fetch(query)
5669
fmt = query.endpoint.response_format
5770

58-
return parse_response(
71+
parsed = parse_response(
5972
result,
6073
response_format=fmt,
6174
backend=backend or self._backend,
6275
)
6376

77+
logger.info(
78+
'Completed request workflow for endpoint=%s format=%s',
79+
endpoint,
80+
fmt,
81+
)
82+
83+
return parsed
84+
6485
# --- Export endpoints ---
6586

6687
def entities(
@@ -285,6 +306,7 @@ def _get_default() -> OmniPath:
285306
global _default_client
286307

287308
if _default_client is None:
309+
logger.info('Creating default OmniPath client singleton')
288310
_default_client = OmniPath()
289311

290312
return _default_client

omnipath_client/_download.py

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,18 @@
33
from __future__ import annotations
44

55
import io
6-
from typing import Any
7-
import logging
86
from pathlib import Path
7+
from typing import Any
98

10-
from omnipath_client._query import Query
119
from omnipath_client._errors import (
1210
OmniPathAPIError,
1311
OmniPathConnectionError,
1412
)
13+
from omnipath_client._query import Query
14+
from omnipath_client._session import get_logger
1515

1616

17-
logger = logging.getLogger(__name__)
17+
logger = get_logger(__name__)
1818

1919

2020
class Downloader:
@@ -41,6 +41,11 @@ def __init__(
4141

4242
self._dm = DownloadManager(**dm_kwargs)
4343
self._use_cache = use_cache
44+
logger.info(
45+
'Initialized downloader with cache=%s cache_dir=%s',
46+
use_cache,
47+
cache_dir,
48+
)
4449

4550
def fetch(self, query: Query) -> str | io.BytesIO:
4651
"""Download the response for a query.
@@ -62,38 +67,58 @@ def fetch(self, query: Query) -> str | io.BytesIO:
6267

6368
url = query.resolved_url
6469
method = query.endpoint.method
70+
payload = query.json_body if method == 'POST' else query.query_params
71+
72+
logger.info(
73+
'Fetching %s %s with parameter keys=%s',
74+
method,
75+
url,
76+
sorted(payload.keys()) if payload else [],
77+
)
6578

6679
try:
6780
dl_kwargs: dict[str, Any] = {}
6881

6982
if method == 'POST':
7083
dl_kwargs['post'] = True
7184
dl_kwargs['json'] = True
72-
dl_kwargs['query'] = query.json_body or {}
73-
elif query.query_params:
74-
dl_kwargs['query'] = query.query_params
85+
dl_kwargs['query'] = payload or {}
86+
elif payload:
87+
dl_kwargs['query'] = payload
7588

7689
dest = None if self._use_cache else False
7790
result = self._dm.download(url, dest=dest, **dl_kwargs)
7891

7992
except Exception as e:
80-
raise OmniPathConnectionError(
81-
f'Failed to download from {url}: {e}',
82-
) from e
93+
message = f'Failed to download from {url}: {e}'
94+
logger.exception(message)
95+
raise OmniPathConnectionError(message) from e
8396

8497
# Check for HTTP errors via the downloader's state
8598
if hasattr(self._dm, '_last_downloader'):
8699
dl = self._dm._last_downloader
87100

88101
if hasattr(dl, 'http_code') and dl.http_code >= 400:
102+
logger.error(
103+
'HTTP error while fetching %s: status_code=%s',
104+
url,
105+
dl.http_code,
106+
)
89107
raise OmniPathAPIError(
90108
status_code=dl.http_code,
91109
detail=f'Request to {url} failed',
92110
)
93111

94112
if result is None:
113+
logger.error('Downloader returned no data for %s', url)
95114
raise OmniPathConnectionError(
96115
f'Download returned None for {url}',
97116
)
98117

118+
logger.info(
119+
'Fetched response for %s into %s',
120+
url,
121+
type(result).__name__,
122+
)
123+
99124
return result

omnipath_client/_graph.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
from __future__ import annotations
44

55
from typing import Any
6-
import logging
76

7+
from omnipath_client._session import get_logger
88

9-
logger = logging.getLogger(__name__)
9+
10+
logger = get_logger(__name__)
1011

1112

1213
def interactions_to_graph(df: Any) -> Any:
@@ -33,12 +34,15 @@ def interactions_to_graph(df: Any) -> Any:
3334

3435
import polars as pl
3536

37+
logger.info('Converting interactions DataFrame to annnet graph')
38+
3639
# Convert to polars if needed (annnet is polars-backed)
3740
if not isinstance(df, pl.DataFrame):
3841
import narwhals as nw
3942

4043
nw_df = nw.from_native(df, eager_only=True)
4144
df = nw_df.to_native()
45+
logger.debug('Converted interactions frame to polars backend')
4246

4347
g = annnet.Graph(directed=True)
4448

@@ -60,6 +64,7 @@ def interactions_to_graph(df: Any) -> Any:
6064
directed=row.get('is_directed', True),
6165
)
6266

67+
logger.info('Created interaction graph with %d edges', df.height)
6368
return g
6469

6570

@@ -87,11 +92,14 @@ def associations_to_graph(df: Any) -> Any:
8792

8893
import polars as pl
8994

95+
logger.info('Converting associations DataFrame to annnet graph')
96+
9097
if not isinstance(df, pl.DataFrame):
9198
import narwhals as nw
9299

93100
nw_df = nw.from_native(df, eager_only=True)
94101
df = nw_df.to_native()
102+
logger.debug('Converted associations frame to polars backend')
95103

96104
g = annnet.Graph(directed=True)
97105

@@ -112,4 +120,5 @@ def associations_to_graph(df: Any) -> Any:
112120
row['member_entity_id'],
113121
)
114122

123+
logger.info('Created association graph with %d edges', df.height)
115124
return g

omnipath_client/_inventory.py

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,17 @@
88

99
import json
1010
from typing import Any
11-
import logging
1211

1312
from omnipath_client._constants import (
14-
OPENAPI_PATH,
1513
DEFAULT_BASE_URL,
14+
OPENAPI_PATH,
1615
STATIC_ENDPOINTS,
1716
)
1817
from omnipath_client._endpoints import ParamDef, EndpointDef
18+
from omnipath_client._session import get_logger
1919

2020

21-
logger = logging.getLogger(__name__)
21+
logger = get_logger(__name__)
2222

2323

2424
def _param_type_from_schema(schema: dict) -> str:
@@ -155,6 +155,12 @@ def parse_openapi(spec: dict[str, Any]) -> dict[str, EndpointDef]:
155155
paths = spec.get('paths', {})
156156
endpoints: dict[str, EndpointDef] = {}
157157

158+
logger.debug(
159+
'Parsing OpenAPI spec with %d path(s) and %d schema(s)',
160+
len(paths),
161+
len(schemas),
162+
)
163+
158164
for path, methods in paths.items():
159165
for method, details in methods.items():
160166
key = path.lstrip('/')
@@ -250,6 +256,7 @@ def __init__(self, base_url: str = DEFAULT_BASE_URL) -> None:
250256
self._base_url = base_url.rstrip('/')
251257
self._endpoints: dict[str, EndpointDef] = {}
252258
self._loaded = False
259+
logger.debug('Created inventory for base_url=%s', self._base_url)
253260

254261
def load(self, force_refresh: bool = False) -> None:
255262
"""Load the inventory from the server or static fallback.
@@ -260,6 +267,10 @@ def load(self, force_refresh: bool = False) -> None:
260267
"""
261268

262269
if self._loaded and not force_refresh:
270+
logger.debug(
271+
'Inventory already loaded for %s; skipping refresh',
272+
self._base_url,
273+
)
263274
return
264275

265276
try:
@@ -272,6 +283,10 @@ def load(self, force_refresh: bool = False) -> None:
272283
exc_info=True,
273284
)
274285
self._endpoints = _build_static_fallback()
286+
logger.info(
287+
'Loaded %d endpoints from static fallback',
288+
len(self._endpoints),
289+
)
275290

276291
self._loaded = True
277292

@@ -299,6 +314,10 @@ def endpoints(self) -> dict[str, EndpointDef]:
299314
"""All registered endpoints."""
300315

301316
if not self._loaded:
317+
logger.debug(
318+
'Inventory access triggered lazy load for %s',
319+
self._base_url,
320+
)
302321
self.load()
303322

304323
return self._endpoints

0 commit comments

Comments
 (0)