Skip to content

Commit 98a0549

Browse files
botanicalJennifer Tranchuckwondo
authored
Replace print statements with logger (#566)
Co-authored-by: Jennifer Tran <tranjennif@gmail.com> Co-authored-by: Chuck Daniels <cjdaniels4@gmail.com>
1 parent 43fd711 commit 98a0549

File tree

8 files changed

+53
-41
lines changed

8 files changed

+53
-41
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
intended use cases.
1212
* [#555](https://github.com/nsidc/earthaccess/issues/555): YAML formatting is
1313
now performed with `yamlfmt` instead of `prettier`.
14+
* [#511](https://github.com/nsidc/earthaccess/issues/511): Replaced `print`
15+
calls with `logging` calls where appropriate and added T20 Ruff rule.
1416

1517
* Enhancements
1618

earthaccess/api.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import logging
2+
13
import requests
24
import s3fs
35
from fsspec import AbstractFileSystem
@@ -12,6 +14,8 @@
1214
from .system import PROD, System
1315
from .utils import _validation as validate
1416

17+
logger = logging.getLogger(__name__)
18+
1519

1620
def _normalize_location(location: Optional[str]) -> Optional[str]:
1721
"""Handle user-provided `daac` and `provider` values.
@@ -64,16 +68,14 @@ def search_datasets(count: int = -1, **kwargs: Any) -> List[DataCollection]:
6468
```
6569
"""
6670
if not validate.valid_dataset_parameters(**kwargs):
67-
print(
68-
"Warning: a valid set of parameters is needed to search for datasets on CMR"
69-
)
71+
logger.warn("A valid set of parameters is needed to search for datasets on CMR")
7072
return []
7173
if earthaccess.__auth__.authenticated:
7274
query = DataCollections(auth=earthaccess.__auth__).parameters(**kwargs)
7375
else:
7476
query = DataCollections().parameters(**kwargs)
7577
datasets_found = query.hits()
76-
print(f"Datasets found: {datasets_found}")
78+
logger.info(f"Datasets found: {datasets_found}")
7779
if count > 0:
7880
return query.get(count)
7981
return query.get_all()
@@ -120,7 +122,7 @@ def search_data(count: int = -1, **kwargs: Any) -> List[DataGranule]:
120122
else:
121123
query = DataGranules().parameters(**kwargs)
122124
granules_found = query.hits()
123-
print(f"Granules found: {granules_found}")
125+
logger.info(f"Granules found: {granules_found}")
124126
if count > 0:
125127
return query.get(count)
126128
return query.get_all()
@@ -199,8 +201,9 @@ def download(
199201
try:
200202
results = earthaccess.__store__.get(granules, local_path, provider, threads)
201203
except AttributeError as err:
202-
print(err)
203-
print("You must call earthaccess.login() before you can download data")
204+
logger.error(
205+
f"{err}: You must call earthaccess.login() before you can download data"
206+
)
204207
return []
205208
return results
206209

earthaccess/auth.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ def refresh_tokens(self) -> bool:
177177
)
178178
return True
179179
else:
180-
print(resp_tokens)
180+
logger.info(resp_tokens)
181181
return False
182182

183183
return False
@@ -222,10 +222,10 @@ def get_s3_credentials(
222222
cumulus_resp.url, allow_redirects=True, timeout=15
223223
)
224224
if not (auth_resp.ok):
225-
print(
225+
logger.error(
226226
f"Authentication with Earthdata Login failed with:\n{auth_resp.text[0:1000]}"
227227
)
228-
print(
228+
logger.error(
229229
f"Consider accepting the EULAs available at {self._eula_url} and applications at {self._apps_url}"
230230
)
231231
return {}
@@ -235,10 +235,12 @@ def get_s3_credentials(
235235
else:
236236
# This happens if the cloud provider doesn't list the S3 credentials or the DAAC
237237
# does not have cloud collections yet
238-
print(f"Credentials for the cloud provider {daac} are not available")
238+
logger.info(
239+
f"Credentials for the cloud provider {daac} are not available"
240+
)
239241
return {}
240242
else:
241-
print("We need to authenticate with EDL first")
243+
logger.info("We need to authenticate with EDL first")
242244
return {}
243245

244246
def get_session(self, bearer_token: bool = True) -> requests.Session:
@@ -266,7 +268,7 @@ def _interactive(self, persist_credentials: bool = False) -> bool:
266268
if authenticated:
267269
logger.debug("Using user provided credentials for EDL")
268270
if persist_credentials:
269-
print("Persisting credentials to .netrc")
271+
logger.info("Persisting credentials to .netrc")
270272
self._persist_user_credentials(username, password)
271273
return authenticated
272274

@@ -307,7 +309,7 @@ def _get_credentials(
307309
token_resp = self._get_user_tokens(username, password)
308310

309311
if not (token_resp.ok): # type: ignore
310-
print(
312+
logger.info(
311313
f"Authentication with Earthdata Login failed with:\n{token_resp.text}"
312314
)
313315
return False
@@ -376,7 +378,7 @@ def _persist_user_credentials(self, username: str, password: str) -> bool:
376378
netrc_path.touch(exist_ok=True)
377379
netrc_path.chmod(0o600)
378380
except Exception as e:
379-
print(e)
381+
logger.error(e)
380382
return False
381383
my_netrc = Netrc(str(netrc_path))
382384
my_netrc[self.system.edl_hostname] = {

earthaccess/search.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import datetime as dt
2+
import logging
23
from inspect import getmembers, ismethod
34

45
import requests
@@ -21,6 +22,8 @@
2122
from .daac import find_provider, find_provider_by_shortname
2223
from .results import DataCollection, DataGranule
2324

25+
logger = logging.getLogger(__name__)
26+
2427
FloatLike: TypeAlias = Union[str, SupportsFloat]
2528
PointLike: TypeAlias = Tuple[FloatLike, FloatLike]
2629

@@ -306,8 +309,8 @@ def parameters(self, **kwargs: Any) -> Self:
306309

307310
def print_help(self, method: str = "fields") -> None:
308311
"""Prints the help information for a given method."""
309-
print("Class components: \n")
310-
print([method for method in dir(self) if method.startswith("_") is False])
312+
print("Class components: \n") # noqa: T201
313+
print([method for method in dir(self) if method.startswith("_") is False]) # noqa: T201
311314
help(getattr(self, method))
312315

313316
def fields(self, fields: Optional[List[str]] = None) -> Self:
@@ -978,7 +981,7 @@ def doi(self, doi: str) -> Self:
978981
else:
979982
# TODO consider removing this print statement since we don't print such
980983
# a message in other cases where no results are found. Seems arbitrary.
981-
print(
984+
logger.info(
982985
f"earthaccess couldn't find any associated collections with the DOI: {doi}"
983986
)
984987

earthaccess/store.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import datetime
2+
import logging
23
import shutil
34
import traceback
45
from functools import lru_cache
@@ -21,6 +22,8 @@
2122
from .results import DataGranule
2223
from .search import DataCollections
2324

25+
logger = logging.getLogger(__name__)
26+
2427

2528
class EarthAccessFile(fsspec.spec.AbstractBufferedFile):
2629
def __init__(self, f: fsspec.AbstractFileSystem, granule: DataGranule) -> None:
@@ -110,7 +113,7 @@ def __init__(self, auth: Any, pre_authorize: bool = False) -> None:
110113
self.set_requests_session(url)
111114

112115
else:
113-
print("Warning: the current session is not authenticated with NASA")
116+
logger.warn("The current session is not authenticated with NASA")
114117
self.auth = None
115118
self.in_region = self._running_in_us_west_2()
116119

@@ -339,7 +342,7 @@ def _open_granules(
339342
) -> List[Any]:
340343
fileset: List = []
341344
total_size = round(sum([granule.size() for granule in granules]) / 1024, 2)
342-
print(f"Opening {len(granules)} granules, approx size: {total_size} GB")
345+
logger.info(f"Opening {len(granules)} granules, approx size: {total_size} GB")
343346

344347
if self.auth is None:
345348
raise ValueError(
@@ -353,10 +356,10 @@ def _open_granules(
353356
# if the data has its own S3 credentials endpoint, we will use it
354357
endpoint = self._own_s3_credentials(granules[0]["umm"]["RelatedUrls"])
355358
if endpoint is not None:
356-
print(f"using endpoint: {endpoint}")
359+
logger.info(f"using endpoint: {endpoint}")
357360
s3_fs = self.get_s3fs_session(endpoint=endpoint)
358361
else:
359-
print(f"using provider: {provider}")
362+
logger.info(f"using provider: {provider}")
360363
s3_fs = self.get_s3fs_session(provider=provider)
361364
else:
362365
access = "on_prem"
@@ -425,7 +428,7 @@ def _open_urls(
425428
f"Exception: {traceback.format_exc()}"
426429
) from e
427430
else:
428-
print(f"Provider {provider} has no valid cloud credentials")
431+
logger.info(f"Provider {provider} has no valid cloud credentials")
429432
return fileset
430433
else:
431434
raise ValueError(
@@ -523,13 +526,13 @@ def _get_urls(
523526
"we need to use one from earthaccess.list_cloud_providers()"
524527
)
525528
if self.in_region and data_links[0].startswith("s3"):
526-
print(f"Accessing cloud dataset using provider: {provider}")
529+
logger.info(f"Accessing cloud dataset using provider: {provider}")
527530
s3_fs = self.get_s3fs_session(provider=provider)
528531
# TODO: make this parallel or concurrent
529532
for file in data_links:
530533
s3_fs.get(file, str(local_path))
531534
file_name = local_path / Path(file).name
532-
print(f"Downloaded: {file_name}")
535+
logger.info(f"Downloaded: {file_name}")
533536
downloaded_files.append(file_name)
534537
return downloaded_files
535538

@@ -559,17 +562,17 @@ def _get_granules(
559562
)
560563
)
561564
total_size = round(sum([granule.size() for granule in granules]) / 1024, 2)
562-
print(
565+
logger.info(
563566
f" Getting {len(granules)} granules, approx download size: {total_size} GB"
564567
)
565568
if access == "direct":
566569
if endpoint is not None:
567-
print(
570+
logger.info(
568571
f"Accessing cloud dataset using dataset endpoint credentials: {endpoint}"
569572
)
570573
s3_fs = self.get_s3fs_session(endpoint=endpoint)
571574
else:
572-
print(f"Accessing cloud dataset using provider: {provider}")
575+
logger.info(f"Accessing cloud dataset using provider: {provider}")
573576
s3_fs = self.get_s3fs_session(provider=provider)
574577

575578
local_path.mkdir(parents=True, exist_ok=True)
@@ -578,7 +581,7 @@ def _get_granules(
578581
for file in data_links:
579582
s3_fs.get(file, str(local_path))
580583
file_name = local_path / Path(file).name
581-
print(f"Downloaded: {file_name}")
584+
logger.info(f"Downloaded: {file_name}")
582585
downloaded_files.append(file_name)
583586
return downloaded_files
584587
else:
@@ -615,11 +618,10 @@ def _download_file(self, url: str, directory: Path) -> str:
615618
# https://docs.python-requests.org/en/latest/user/quickstart/#raw-response-content
616619
shutil.copyfileobj(r.raw, f, length=1024 * 1024)
617620
except Exception:
618-
print(f"Error while downloading the file {local_filename}")
619-
print(traceback.format_exc())
621+
logger.exception(f"Error while downloading the file {local_filename}")
620622
raise Exception
621623
else:
622-
print(f"File {local_filename} already downloaded")
624+
logger.info(f"File {local_filename} already downloaded")
623625
return str(path)
624626

625627
def _download_onprem_granules(
@@ -663,8 +665,7 @@ def _open_urls_https(
663665
try:
664666
fileset = _open_files(url_mapping, https_fs, threads)
665667
except Exception:
666-
print(
667-
"An exception occurred while trying to access remote files via HTTPS: "
668-
f"Exception: {traceback.format_exc()}"
668+
logger.exception(
669+
"An exception occurred while trying to access remote files via HTTPS"
669670
)
670671
return fileset

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ line-length = 88
125125
src = ["earthaccess", "stubs", "tests"]
126126

127127
[tool.ruff.lint]
128-
extend-select = ["I"]
128+
extend-select = ["I", "T20"]
129129

130130
[tool.ruff.lint.isort]
131131
combine-as-imports = true

tests/integration/test_auth.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,9 @@ def test_auth_can_read_from_netrc_file():
5959
def test_auth_throws_exception_if_netrc_is_not_present():
6060
activate_environment()
6161
delete_netrc()
62-
with pytest.raises(Exception) as e_info:
62+
with pytest.raises(Exception):
6363
earthaccess.login(strategy="netrc")
6464
assertions.assertRaises(FileNotFoundError)
65-
print(e_info)
6665

6766

6867
def test_auth_populates_attrs():
@@ -87,12 +86,12 @@ def test_auth_can_fetch_s3_credentials():
8786
for daac in earthaccess.daac.DAACS:
8887
if len(daac["s3-credentials"]) > 0:
8988
try:
90-
print(f"Testing S3 credentials for {daac['short-name']}")
89+
logger.info(f"Testing S3 credentials for {daac['short-name']}")
9190
credentials = earthaccess.get_s3_credentials(daac["short-name"])
9291
assertions.assertIsInstance(credentials, dict)
9392
assertions.assertTrue("accessKeyId" in credentials)
9493
except Exception as e:
95-
print(
94+
logger.error(
9695
f"An error occured while trying to fetch S3 credentials for {daac['short-name']}: {e}"
9796
)
9897

tests/unit/test_auth.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
# package imports
2+
import logging
23
import unittest
34
from unittest import mock
45

56
import pytest
67
import responses
78
from earthaccess import Auth
89

10+
logger = logging.getLogger(__name__)
11+
912

1013
class TestCreateAuth(unittest.TestCase):
1114
@responses.activate
@@ -107,7 +110,6 @@ def test_auth_fails_for_wrong_credentials(self, user_input, user_password):
107110
auth = Auth()
108111
auth.login(strategy="interactive")
109112
with pytest.raises(Exception) as e_info:
110-
print(e_info)
111113
self.assertEqual(auth.authenticated, False)
112114
self.assertEqual(e_info, Exception)
113115
self.assertEqual(auth.password, "password")

0 commit comments

Comments
 (0)