Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Logging #185

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion docs/src/other_guides.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Other Guides

Request Errors
--------------
The package will raise all HTTP and timeout erros using
The package will raise all HTTP and timeout errors using
the ``HTTPError`` and ``Timeout`` classes of the
``requests`` package. Whenever an HTTP error is raised,
proper description of the error will be printed to
Expand All @@ -25,3 +25,25 @@ output. You can also access the response's status code.
print(e.args[1]) # error message
except Timeout:
pass


Logging
-------
LyricsGenius uses Python's ``logging`` module to log
relevant messages including the progress of searching
for a song and much more. If you use LyricsGenius from
the command line, just add the ``--verbose`` parameter.
Otherwise, follow this example:

.. code:: python

import logging

from lyricsgenius import Genius

logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger("lyricsgenius")
logger.setLevel(logging.INFO)

genius = Genius(GENIUS_ACCESS_TOKEN)
song = genius.search_song("To You", "Andy Shauf")
22 changes: 13 additions & 9 deletions lyricsgenius/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import os
import argparse
import logging

from . import Genius
from .utils import safe_unicode
Expand Down Expand Up @@ -34,33 +35,36 @@ def main(args=None):
msg = "Must declare environment variable: GENIUS_ACCESS_TOKEN"
assert access_token, msg
api = Genius(access_token)
api._cli = True
if args.quiet:
api.verbose = False
log_level = logging.NOTSET
else:
log_level = logging.INFO
# Set up logging
logging.basicConfig(format="%(message)s")
logger = logging.getLogger(__package__)
logger.setLevel(log_level)

# Handle the command-line inputs
if args.search_type == "song":
song = api.search_song(*args.terms)
if not song:
if not args.quiet:
print("Could not find specified song. Check spelling?")
logger.info("Could not find specified song. Check spelling?")
return
if args.save:
if not args.quiet:
print("Saving lyrics to '{s}'...".format(s=safe_unicode(song.title)))
logger.info("Saving lyrics to '%s'...", safe_unicode(song.title))
song.save_lyrics()
elif args.search_type == "artist":
artist = api.search_artist(args.terms[0],
max_songs=args.max_songs,
sort='popularity')
if args.save:
if not args.quiet:
print("Saving '{a}'' lyrics...".format(a=safe_unicode(artist.name)))
logger.info("Saving '%s' lyrics...", safe_unicode(artist.name))
api.save_artists(artist)
elif args.search_type == "album":
album = api.search_album(*args.terms)
if args.save:
if not args.quiet:
print("Saving '{a}'' lyrics...".format(a=safe_unicode(album.name)))
logger.info("Saving '%s' lyrics...", safe_unicode(album.name))
album.save_lyrics()


Expand Down
12 changes: 10 additions & 2 deletions lyricsgenius/api/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import time
import os
import logging
from json.decoder import JSONDecodeError

import requests
Expand All @@ -22,19 +23,21 @@
retries=0,
public_api_constructor=False,
):
self.logger = logging.getLogger(__name__)
self._session = requests.Session()
self._session.headers = {
'application': 'LyricsGenius',
'User-Agent': 'https://github.com/johnwmillr/LyricsGenius'
}
if access_token is None:
self.logger.info("No token provided. Trying to get it from ENV.")
access_token = os.environ.get('GENIUS_ACCESS_TOKEN')

if public_api_constructor:
self.authorization_header = {}
else:
if not access_token or not isinstance(access_token, str):
raise TypeError('Invalid token')

Check failure on line 40 in lyricsgenius/api/base.py

View workflow job for this annotation

GitHub Actions / build (3.7)

Invalid token
self.access_token = 'Bearer ' + access_token
self.authorization_header = {'authorization': self.access_token}

Expand Down Expand Up @@ -77,17 +80,22 @@
params=params_,
headers=header,
**kwargs)
self.logger.debug("%d status code for %s on try %d.",
response.status_code,
uri,
tries)
response.raise_for_status()
except Timeout as e:
error = "Request timed out:\n{e}".format(e=e)
if tries > self.retries:
raise Timeout(error)
raise Timeout(error) from e
except HTTPError as e:
error = get_description(e)
if response.status_code < 500 or tries > self.retries:
raise HTTPError(response.status_code, error)
raise HTTPError(response.status_code, error) from e

# Enforce rate limiting
self.logger.debug("Sleeping for %2fs.", self.sleep_time)
time.sleep(self.sleep_time)

if web:
Expand Down
4 changes: 4 additions & 0 deletions lyricsgenius/auth.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from urllib.parse import urlencode
import webbrowser
import logging

from .utils import parse_redirected_url
from .api import Sender
Expand Down Expand Up @@ -47,6 +48,7 @@ def __init__(self, client_id, redirect_uri,
self.state = state
self.flow = 'token' if client_only_app else 'code'
self.client_only_app = client_only_app
self.logger = logging.getLogger(__name__)

@property
def url(self):
Expand Down Expand Up @@ -99,6 +101,7 @@ def get_user_token(self, code=None, url=None, state=None, **kwargs):
raise InvalidStateError('States do not match.')

if code:
logging.info('Requesting token from Genius using code.')
payload = {'code': code,
'client_id': self.client_id,
'client_secret': self.client_secret,
Expand All @@ -109,6 +112,7 @@ def get_user_token(self, code=None, url=None, state=None, **kwargs):
res = self._make_request(url, 'POST', data=payload, **kwargs)
token = res['access_token']
else:
logging.info('Getting token from url query parameters.')
token = parse_redirected_url(url, self.flow)
return token

Expand Down
Loading
Loading