Skip to content

Commit bb545c4

Browse files
author
Ludwig Schneider
authored
Fix log (#427)
1 parent e2704e7 commit bb545c4

File tree

2 files changed

+21
-69
lines changed

2 files changed

+21
-69
lines changed

src/cript/api/api.py

Lines changed: 12 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,7 @@ class API:
5555
"""
5656

5757
# dictates whether the user wants to see terminal log statements or not
58-
_verbose: bool = True
59-
logger: logging.Logger = None # type: ignore
58+
_logger: logging.Logger = None # type: ignore
6059

6160
_host: str = ""
6261
_api_token: str = ""
@@ -77,7 +76,7 @@ class API:
7776
# trunk-ignore-end(cspell)
7877

7978
@beartype
80-
def __init__(self, host: Union[str, None] = None, api_token: Union[str, None] = None, storage_token: Union[str, None] = None, config_file_path: Union[str, Path] = ""):
79+
def __init__(self, host: Union[str, None] = None, api_token: Union[str, None] = None, storage_token: Union[str, None] = None, config_file_path: Union[str, Path] = "", default_log_level=logging.INFO):
8180
"""
8281
Initialize CRIPT API client with host and token.
8382
Additionally, you can use a config.json file and specify the file path.
@@ -220,8 +219,8 @@ def __init__(self, host: Union[str, None] = None, api_token: Union[str, None] =
220219
self._check_initial_host_connection()
221220

222221
# set a logger instance to use for the class logs
223-
self._set_logger()
224-
self._db_schema = DataSchema(self.host)
222+
self._init_logger(default_log_level)
223+
self._db_schema = DataSchema(self.host, self.logger)
225224

226225
def __str__(self) -> str:
227226
"""
@@ -244,15 +243,15 @@ def __str__(self) -> str:
244243
"""
245244
return f"CRIPT API Client - Host URL: '{self.host}'"
246245

247-
def _set_logger(self, verbose: bool = True) -> None:
246+
def _init_logger(self, log_level=logging.INFO) -> None:
248247
"""
249248
Prepare and configure the logger for the API class.
250249
251250
This function creates and configures a logger instance associated with the current module (class).
252251
253252
Parameters
254253
----------
255-
verbose: bool default True
254+
log_level: logging.LEVEL default logging.INFO
256255
set if you want `cript.API` to give logs to console or not
257256
258257
Returns
@@ -263,11 +262,7 @@ def _set_logger(self, verbose: bool = True) -> None:
263262
# Create a logger instance associated with the current module
264263
logger = logging.getLogger(__name__)
265264

266-
# Set the logger's level based on the verbose flag
267-
if verbose:
268-
logger.setLevel(logging.INFO) # Display INFO logs
269-
else:
270-
logger.setLevel(logging.CRITICAL) # Display no logs
265+
logger.setLevel(log_level)
271266

272267
# Create a console handler
273268
console_handler = logging.StreamHandler()
@@ -282,58 +277,11 @@ def _set_logger(self, verbose: bool = True) -> None:
282277
logger.addHandler(console_handler)
283278

284279
# set logger for the class
285-
self.logger = logger
280+
self._logger = logger
286281

287282
@property
288-
def verbose(self) -> bool:
289-
"""
290-
A boolean flag that controls whether verbose logging is enabled or not.
291-
292-
When `verbose` is set to `True`, the class will provide additional detailed logging
293-
to the terminal. This can be useful for debugging and understanding the internal
294-
workings of the class.
295-
296-
```bash
297-
INFO: Validating Project graph...
298-
```
299-
300-
When `verbose` is set to `False`, the class will only provide essential logging information,
301-
making the terminal output less cluttered and more user-friendly.
302-
303-
Examples
304-
--------
305-
>>> import cript
306-
>>> with cript.API(
307-
... host="https://api.criptapp.org/",
308-
... api_token=os.getenv("CRIPT_TOKEN"),
309-
... storage_token=os.getenv("CRIPT_STORAGE_TOKEN")
310-
... ) as api:
311-
... # turn off the terminal logs
312-
... api.verbose = False
313-
314-
Returns
315-
-------
316-
bool
317-
verbose boolean value
318-
"""
319-
return self._verbose
320-
321-
@verbose.setter
322-
def verbose(self, new_verbose_value: bool) -> None:
323-
"""
324-
sets the verbose value and then sets a new logger for the class
325-
326-
Parameters
327-
----------
328-
new_verbose_value: bool
329-
new verbose value to turn the logging ON or OFF
330-
331-
Returns
332-
-------
333-
None
334-
"""
335-
self._verbose = new_verbose_value
336-
self._set_logger(verbose=new_verbose_value)
283+
def logger(self):
284+
return self._logger
337285

338286
@beartype
339287
def _prepare_host(self, host: str) -> str:
@@ -932,7 +880,7 @@ def delete(self, node) -> None:
932880
933881
Notes
934882
-----
935-
After the node has been successfully deleted, a log is written to the terminal if `cript.API.verbose = True`
883+
After the node has been successfully deleted, a log is written to the terminal
936884
937885
```bash
938886
INFO: Deleted 'Material' with UUID of '80bfc642-157e-4692-a547-97c470725397' from CRIPT API.
@@ -1010,7 +958,7 @@ def delete_node_by_uuid(self, node_type: str, node_uuid: str) -> None:
1010958
1011959
Notes
1012960
-----
1013-
After the node has been successfully deleted, a log is written to the terminal if `cript.API.verbose = True`
961+
After the node has been successfully deleted, a log is written
1014962
1015963
```bash
1016964
INFO: Deleted 'Material' with UUID of '80bfc642-157e-4692-a547-97c470725397' from CRIPT API.

src/cript/api/data_schema.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import json
2-
import logging
32
from typing import Union
43

54
import jsonschema
@@ -21,6 +20,7 @@ class DataSchema:
2120

2221
_vocabulary: dict = {}
2322
_db_schema: dict = {}
23+
_logger = None
2424
# Advanced User Tip: Disabling Node Validation
2525
# For experienced users, deactivating node validation during creation can be a time-saver.
2626
# Note that the complete node graph will still undergo validation before being saved to the back end.
@@ -45,13 +45,15 @@ def _get_db_schema(self, host: str) -> dict:
4545
return self._db_schema
4646

4747
# fetch db_schema from API
48-
logging.info(f"Loading node validation schema from {host}/schema/")
48+
if self._logger:
49+
self._logger.info(f"Loading node validation schema from {host}/schema/")
4950
# fetch db schema from API
5051
response: requests.Response = requests.get(url=f"{host}/schema/", timeout=_API_TIMEOUT)
5152

5253
# raise error if not HTTP 200
5354
response.raise_for_status()
54-
logging.info(f"Loading node validation schema from {host}/schema/ was successful.")
55+
if self._logger:
56+
self._logger.info(f"Loading node validation schema from {host}/schema/ was successful.")
5557

5658
# if no error, take the JSON from the API response
5759
response_dict: dict = response.json()
@@ -61,7 +63,7 @@ def _get_db_schema(self, host: str) -> dict:
6163

6264
return db_schema
6365

64-
def __init__(self, host: str):
66+
def __init__(self, host: str, logger=None):
6567
"""
6668
Initialize DataSchema class with a full hostname to fetch the node validation schema.
6769
@@ -75,6 +77,7 @@ def __init__(self, host: str):
7577

7678
self._db_schema = self._get_db_schema(host)
7779
self._vocabulary = self._get_vocab(host)
80+
self._logger = logger
7881

7982
def _get_vocab(self, host: str) -> dict:
8083
"""
@@ -244,7 +247,8 @@ def is_node_schema_valid(self, node_json: str, is_patch: bool = False, force_val
244247
else:
245248
log_message += " (Can be disabled by setting `cript.API.skip_validation = True`.)"
246249

247-
logging.info(log_message)
250+
if self._logger:
251+
self._logger.info(log_message)
248252

249253
# set the schema to test against http POST or PATCH of DB Schema
250254
schema_http_method: str

0 commit comments

Comments
 (0)