Skip to content

Commit

Permalink
Merge pull request #165 from djotaku/issue161
Browse files Browse the repository at this point in the history
Issue161 - switch from print statements to logging
  • Loading branch information
djotaku authored Jul 21, 2021
2 parents 48ed573 + cde8447 commit e3a07f8
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 72 deletions.
3 changes: 2 additions & 1 deletion changelog.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#v6.1.2
## Release Notes
### User-Facing Changes
- None
- Should not overwrite your text files if the API can't be reached
- changed many of the print statements to log output using Rich's logging

### Developer-Facing or API Changes

Expand Down
17 changes: 12 additions & 5 deletions eldonationtracker/api/participant.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
"""Grabs Participant JSON data and outputs to files."""

from dataclasses import dataclass, field
import logging
from rich import print # type ignore

from rich.logging import RichHandler # type ignore
import time

import eldonationtracker.utils.extralife_io
from eldonationtracker.api import donor as donor, team as team, donation as donation, badge
from eldonationtracker.utils import extralife_io as extralife_io
from eldonationtracker import base_api_url

# logging
LOG_FORMAT = '%(name)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, handlers=[RichHandler(markup=True, show_path=False)])
participant_log = logging.getLogger("Participant")


class Participant:
"""Owns all the attributes under the participant API.
Expand Down Expand Up @@ -278,7 +284,7 @@ def _get_participant_info(self):
"""
participant_json = extralife_io.get_json(self.participant_url)
if not participant_json:
print("[bold red]Couldn't access participant JSON.[/bold red]")
participant_log.warning("[bold red]Couldn't access participant JSON.[/bold red]")
return self.total_raised, self.number_of_donations, self.goal, self.avatar_image_url, self.event_name, \
self.donation_link_url, self.stream_url, self.extra_life_page_url, self.created_date_utc,\
self.stream_is_live, self.sum_pledges, self.team_name, self.is_team_captain, self.display_name
Expand Down Expand Up @@ -438,7 +444,7 @@ def output_donation_data(self) -> None:
if self._top_donation is not None:
self.write_text_files(self._top_donation_formatted_output)
elif not self._text_files_exist:
print("[bold blue]No donations, writing default data to files.[/bold blue]")
participant_log.info("[bold blue]No donations, writing default data to files.[/bold blue]")
self.write_text_files(self._donation_formatted_output)

def output_donor_data(self) -> None:
Expand All @@ -454,7 +460,8 @@ def output_donor_data(self) -> None:
if self._top_donor is not None:
self.write_text_files(self._top_donor_formatted_output)
elif not self._text_files_exist:
print("[bold blue]No donors or only anonymous donors, writing default data to files.[/bold blue]")
participant_log.info("[bold blue]No donors or only anonymous donors, writing default data to files.[/bold "
"blue]")
self.write_text_files(self._top_donor_formatted_output)

def output_milestone_data(self) -> None: # pragma: no cover
Expand Down Expand Up @@ -523,7 +530,7 @@ def run(self) -> None:
self.my_team.team_run()
##########################################################
self._first_run = False
print(time.strftime("%H:%M:%S"))
participant_log.info("Finished checking API and updating text files!")

def __str__(self):
if self.my_team:
Expand Down
13 changes: 10 additions & 3 deletions eldonationtracker/api/team.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Contains classes pertaining to teams."""
import logging
from rich import print
from rich.logging import RichHandler
from typing import Tuple, List

import eldonationtracker.utils.extralife_io
Expand All @@ -9,6 +11,11 @@
from eldonationtracker.api.team_participant import TeamParticipant
from eldonationtracker.api import donation as donation

# logging
LOG_FORMAT = '%(name)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, handlers=[RichHandler(markup=True, show_path=False)])
team_log = logging.getLogger("Team:")


class Team:
"""Hold Team API Data."""
Expand Down Expand Up @@ -142,7 +149,7 @@ def _get_team_json(self) -> Tuple:
"""
team_json = extralife_io.get_json(self.team_url)
if not team_json:
print("[bold magenta]Could not get team JSON[/bold magenta]")
team_log.warning("[bold magenta]Could not get team JSON[/bold magenta]")
return self.team_goal, self.team_captain, self.total_raised, self.num_donations, self.team_avatar_image
else:
return team_json.get("fundraisingGoal"), team_json.get("captainDisplayName"), \
Expand All @@ -164,7 +171,7 @@ def _get_participants(self, top5: bool) -> List[TeamParticipant]:
"""
team_participant_json = extralife_io.get_json(self.team_participant_url, top5)
if not team_participant_json:
print("[bold magenta]Couldn't get to URL or possibly no participants.[/bold magenta]")
team_log.warning("[bold magenta]Couldn't get to URL or possibly no participants.[/bold magenta]")
if top5:
return self._top_5_participant_list
else:
Expand All @@ -180,7 +187,7 @@ def _top_participant(self) -> str:
:returns: String formatted information about the top participant.
"""
if len(self._top_5_participant_list) == 0:
print("[bold blue] No participants[/bold blue] ")
team_log.info("[bold blue] No participants[/bold blue] ")
return "No participants."
else:
return (f"{self._top_5_participant_list[0].name} - $"
Expand Down
35 changes: 22 additions & 13 deletions eldonationtracker/ui/call_main_gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@

"""The main GUI window."""

import logging

from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox, QInputDialog

from PyQt5 import QtCore

from rich import print
from rich.logging import RichHandler
import sys
import webbrowser

Expand All @@ -16,6 +19,11 @@
from eldonationtracker.utils import extralife_io as extralife_io
import eldonationtracker.utils.update_available

# logging
LOG_FORMAT = '%(name)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, handlers=[RichHandler(markup=True, show_path=False)])
GUI_log = logging.getLogger("main GUI")


class ELDonationGUI(QMainWindow, design.Ui_MainWindow):
"""The main ui Window."""
Expand Down Expand Up @@ -84,25 +92,25 @@ def __init__(self):
self.actionAbout.triggered.connect(self.show_about)

def version_check(self):
print("[bold blue]Participant.conf version check![/bold blue]")
GUI_log.debug("[bold blue]Participant.conf version check![/bold blue]")
if self.version_mismatch is True:
print("[bold magenta]There is a version mismatch[/bold magenta]")
GUI_log.debug("[bold magenta]There is a version mismatch[/bold magenta]")
choices = ("Replace with Defaults", "Update on Save")
choice, ok = QInputDialog.getItem(self, "Input Dialog",
"You are using an old version of the configuration file.\n Choose "
"what you would like to do.\n If you choose Update on Save, please "
"click on teh settings button, review the new options, and hit save.",
"click on the settings button, review the new options, and hit save.",
choices, 0, False)
if ok and choice:
print(f"[bold blue]You have chosen {choice}[/bold blue]")
GUI_log.debug(f"[bold blue]You have chosen {choice}[/bold blue]")
if choice == "Replace with Defaults":
self.participant_conf.get_github_config()
print("[bold blue]Settings have been replaced with the repo defaults.[/bold blue]")
GUI_log.info("[bold blue]Settings have been replaced with the repo defaults.[/bold blue]")
self.participant_conf.reload_json()
if choice == "Update on Save":
print("[bold blue]When you save the settings, you will be up to date[/bold blue]")
GUI_log.info("[bold blue]When you save the settings, you will be up to date[/bold blue]")
else:
print("[bold green]Version is correct[/bold green] ")
GUI_log.debug("[bold green]Version is correct[/bold green] ")

def test_alert(self):
self.tracker.load_and_unload_test()
Expand All @@ -118,7 +126,7 @@ def call_settings_button(self):
# this is used for buttons that I haven't yet implemented
@staticmethod
def dead_button():
print("[bold blue]not working yet[/bold blue]")
GUI_log.info("[bold blue]not working yet[/bold blue]")

@staticmethod
def read_files(folders, files):
Expand All @@ -128,7 +136,7 @@ def read_files(folders, files):
f.close()
return text
except FileNotFoundError:
print(f"""[bold magenta]GUI Error:
GUI_log.error(f"""[bold magenta]GUI Error:
{folders}/{files} does not exist.
Did you update the settings?
Did you hit the 'run' button?[/bold magenta]
Expand All @@ -150,7 +158,7 @@ def get_some_text(self):
avatar_url = QtCore.QUrl.fromLocalFile(self.folders + '/Participant_Avatar.html')
self.participant_avatar.setUrl(avatar_url)
except FileNotFoundError:
print("[bold blue] Participant Avatar not found. After running you should have it.[/bold blue]")
GUI_log.warning("[bold blue] Participant Avatar not found. After running you should have it.[/bold blue]")

# Team Info
if self.participant_conf.get_if_in_team():
Expand All @@ -162,7 +170,7 @@ def get_some_text(self):
self.textBrowser_TeamTop5.setPlainText(self.read_files(self.folders, 'Team_Top5Participants.txt'))

def run_button(self):
print(f"[bold blue]Starting the participant run. But first, reloading config file.[/bold blue]")
GUI_log.info(f"[bold blue]Starting the participant run. But first, reloading config file.[/bold blue]")
self.participant_conf.reload_json()
# reload participant.conf in participant in case the user has changed settings
self.my_participant.set_config_values()
Expand All @@ -181,9 +189,10 @@ def load_documentation(self):
try:
webbrowser.open("https://eldonationtracker.readthedocs.io/en/latest/index.html", new=2)
except webbrowser.Error:
print("[bold red]Couldn't open documentation[/bold red]")
GUI_log.error("[bold red]Couldn't open documentation[/bold red]")
message_box = QMessageBox.warning(self, "Documentation",
"Could not load documentation. You may access in your browser at https://eldonationtracker.readthedocs.io/en/latest/index.html")
"Could not load documentation. You may access in your browser at "
"https://eldonationtracker.readthedocs.io/en/latest/index.html")

def check_for_update(self):
if eldonationtracker.utils.update_available.main():
Expand Down
9 changes: 8 additions & 1 deletion eldonationtracker/ui/call_settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Contains the programming logic for the settings window in the GUI."""

import logging
from rich.logging import RichHandler
from rich import print

from PyQt5.QtWidgets import QDialog, QFileDialog, QFontDialog, QColorDialog, QMessageBox
Expand All @@ -9,6 +11,11 @@
from eldonationtracker import base_api_url
from eldonationtracker.utils import extralife_io

# logging
LOG_FORMAT = '%(name)s: %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT, handlers=[RichHandler(markup=True, show_path=False)])
call_settings_log = logging.getLogger("call settings")


class MyForm(QDialog):
"""Class for the settings Window."""
Expand Down Expand Up @@ -193,7 +200,7 @@ def _get_tracker_assets(self, asset):
self.ui.label_sound.setText(file)

def _validate_id(self, id_type: str):
print("[bold blue]Validating URL[/bold blue]")
call_settings_log.debug("[bold blue]Validating URL[/bold blue]")
if id_type == "participant":
url = f"{base_api_url}/participants/{self.ui.lineEditParticipantID.text()}"
valid_url = extralife_io.validate_url(url)
Expand Down
Loading

0 comments on commit e3a07f8

Please sign in to comment.