Skip to content

Commit

Permalink
Convert print -> logging (#327)
Browse files Browse the repository at this point in the history
* print to logging

* limit error message details to class name + print -> logging

* .gitignore for me

---------

Co-authored-by: Willard Nilges <[email protected]>
  • Loading branch information
james-otten and WillNilges authored Apr 7, 2024
1 parent 47a9e22 commit d19206b
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 28 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,6 @@ loadenv.sh

# Spreadsheet data
spreadsheet_data

# vs code
.devcontainer.json
37 changes: 18 additions & 19 deletions src/meshapi/views/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,17 +119,16 @@ def join_form(request):
# If the user has given us an invalid address. Tell them to buzz
# off.
except AddressError as e:
print(e)
logging.exception("AddressError when validating address")
return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
# If we get any other error, then there was probably an issue
# using the API, and we should wait a bit and re-try
except (AddressAPIError, Exception) as e:
print(e)
print("(NYC) Something went wrong validating the address. Re-trying...")
except (AddressAPIError, Exception):
logging.exception("(NYC) Something went wrong validating the address. Re-trying...")
time.sleep(3)
# If we run out of tries, bail.
if nyc_addr_info is None:
print(f"Could not parse address: {r.street_address}, {r.city}, {r.state}, {r.zip}")
logging.warn(f"Could not parse address: {r.street_address}, {r.city}, {r.state}, {r.zip}")
return Response(
{"detail": "Your address could not be validated."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
Expand Down Expand Up @@ -215,8 +214,8 @@ def join_form(request):

try:
join_form_member.save()
except IntegrityError as e:
print(e)
except IntegrityError:
logging.exception("Error saving member from join form")
return Response(
{"detail": "There was a problem saving your Member information"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
Expand All @@ -230,8 +229,8 @@ def join_form(request):
# association with the existing nodes
for node in existing_nodes_for_structure:
join_form_building.nodes.add(node)
except IntegrityError as e:
print(e)
except IntegrityError:
logging.exception("Error saving building from join form")
# Delete the member and bail
join_form_member.delete()
return Response(
Expand All @@ -240,8 +239,8 @@ def join_form(request):

try:
join_form_install.save()
except IntegrityError as e:
print(e)
except IntegrityError:
logging.exception("Error saving install from join form")
# Delete the member, building (if we just created it), and bail
join_form_member.delete()
if len(existing_exact_buildings) == 0:
Expand All @@ -250,7 +249,7 @@ def join_form(request):
{"detail": "There was a problem saving your Install information"}, status=status.HTTP_400_BAD_REQUEST
)

print(
logging.info(
f"JoinForm submission success. building_id: {join_form_building.id}, member_id: {join_form_member.id}, install_number: {join_form_install.install_number}"
)

Expand Down Expand Up @@ -388,23 +387,23 @@ def network_number_assignment(request):
del request_json["password"]

r = NetworkNumberAssignmentRequest(**request_json)
except (TypeError, JSONDecodeError) as e:
print(f"NN Request failed. Could not decode request: {e}")
except (TypeError, JSONDecodeError):
logging.exception("NN Request failed. Could not decode request")
return Response({"detail": "Got incomplete request"}, status=status.HTTP_400_BAD_REQUEST)

try:
# Here we use select_for_update() and select_related() to ensure we acquire a lock on all
# rows related to the Install object at hand, so that for example, the attached building
# isn't changed underneath us
nn_install = Install.objects.select_for_update().select_related().get(install_number=r.install_number)
except Exception as e:
print(f'NN Request failed. Could not get Install w/ Install Number "{r.install_number}": {e}')
except Exception:
logging.exception(f'NN Request failed. Could not get Install w/ Install Number "{r.install_number}"')
return Response({"detail": "Install Number not found"}, status=status.HTTP_404_NOT_FOUND)

# Check if the install already has a network number
if nn_install.node is not None:
message = f"This Install Number ({r.install_number}) already has a Network Number ({nn_install.node.network_number}) associated with it!"
print(message)
logging.warn(message)
return Response(
{
"detail": message,
Expand Down Expand Up @@ -446,8 +445,8 @@ def network_number_assignment(request):
nn_install.node.save()
nn_building.save()
nn_install.save()
except IntegrityError as e:
print(e)
except IntegrityError:
logging.exception("NN Request failed. Could not save node number.")
return Response(
{"detail": "NN Request failed. Could not save node number."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
Expand Down
19 changes: 10 additions & 9 deletions src/meshapi/views/panoramas.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import os
from pathlib import Path

Expand Down Expand Up @@ -44,8 +45,8 @@ def update_panoramas(request):
status=status.HTTP_200_OK,
)
except (ValueError, GitHubError) as e:
print(e)
return Response({"detail": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
logging.exception("Error when syncing panoramas")
return Response({"detail": str(type(e).__name__)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@advisory_lock("update_panoramas_lock")
Expand Down Expand Up @@ -83,7 +84,7 @@ def set_panoramas(panos: dict[str, list[str]]) -> tuple[int, list[str]]:
install: Install = Install.objects.get(install_number=int(install_number))
panoramas = []
if not install:
print(
logging.warn(
f"Warning: Could not add panorama to building (Install #{install_number}). Install does not exist."
)
warnings.append(install_number)
Expand All @@ -98,8 +99,8 @@ def set_panoramas(panos: dict[str, list[str]]) -> tuple[int, list[str]]:
install.building.panoramas.append(p)
install.building.save()
panoramas_saved += len(filenames)
except Exception as e:
print(f"Warning: Could not add panorama to building (Install #{install_number}): {e}")
except Exception:
logging.exception(f"Warning: Could not add panorama to building (Install #{install_number})")
warnings.append(install_number)
return panoramas_saved, warnings

Expand All @@ -109,8 +110,8 @@ def build_pano_dict(files: list[str]):
for f in files:
try:
number, label = parse_pano_title(Path(f).stem)
except BadPanoramaTitle as e:
print(e)
except BadPanoramaTitle:
logging.exception("Error due to panorama title")
continue
if number not in panos:
panos[number] = [f]
Expand Down Expand Up @@ -164,7 +165,7 @@ def get_head_tree_sha(owner, repo, branch, token: str = ""):
url, headers={"Authorization": f"Bearer {token}"}, timeout=DEFAULT_EXTERNAL_API_TIMEOUT_SECONDS
)
if master.status_code != 200:
print(f"Error: Got status {master.status_code} from GitHub trying to get SHA.")
logging.error(f"Error: Got status {master.status_code} from GitHub trying to get SHA.")
return None
master = master.json()
return master["commit"]["commit"]["tree"]["sha"]
Expand All @@ -177,7 +178,7 @@ def list_files_in_git_directory(owner: str, repo: str, directory: str, tree, tok
url, headers={"Authorization": f"Bearer {token}"}, timeout=DEFAULT_EXTERNAL_API_TIMEOUT_SECONDS
)
if response.status_code != 200:
print(f"Error: Failed to fetch GitHub directory contents. Status code: {response.status_code}")
logging.error(f"Error: Failed to fetch GitHub directory contents. Status code: {response.status_code}")
return None
files = []
tree = response.json()
Expand Down

0 comments on commit d19206b

Please sign in to comment.