Skip to content

Commit

Permalink
chore: adds logger
Browse files Browse the repository at this point in the history
  • Loading branch information
chloelbn committed May 4, 2021
1 parent 5f7273f commit 8c67ee0
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 15 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ build/
dist/
htmlcov
venv/
debug.log
57 changes: 42 additions & 15 deletions algoliasearch/http/transporter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import time
import logging
import os

from typing import Optional, Union, Dict, Any, List
from algoliasearch.exceptions import AlgoliaUnreachableHostException, RequestException
Expand All @@ -22,8 +23,22 @@ def __init__(self, requester, config):
self._requester = requester
self._config = config
self._retry_strategy = RetryStrategy()
self._logger = logging.getLogger('algolia')
self._logger.setLevel(logging.DEBUG)
if os.getenv('DEBUG'):
self._logger = logging.getLogger('algolia')
self._logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('debug.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
self._logger.addHandler(fh)
self._logger.addHandler(ch)

def write(self, verb, path, data, request_options):
# type: (str, str, Optional[Union[dict, list]], Optional[Union[dict, RequestOptions]]) -> dict # noqa: E501
Expand Down Expand Up @@ -72,7 +87,8 @@ def request(self, verb, hosts, path, data, request_options, timeout):
self._config.proxies,
)

self._logger.info('Sending request:' + str(request))
if os.getenv('DEBUG'):
self._logger.info('Sending request:' + str(request))

return self.retry(hosts, request, relative_url)

Expand All @@ -88,10 +104,12 @@ def retry(self, hosts, request, relative_url):
decision = self._retry_strategy.decide(host, response)

if decision == RetryOutcome.SUCCESS:
self._logger.info('Response received: ' + str(response))
if os.getenv('DEBUG'):
self._logger.info('Response received: ' + str(response))
return response.content if response.content is not None else {}
elif decision == RetryOutcome.FAIL:
self._logger.info('Host failed: ' + str(response))
if os.getenv('DEBUG'):
self._logger.info('Host failed: ' + str(response))
content = response.error_message
if response.content and "message" in response.content:
content = response.content["message"]
Expand All @@ -108,7 +126,7 @@ def close(self):

class Request(object):
def __init__(
self, verb, headers, data, connect_timeout, timeout, proxies={}
self, verb, headers, data, connect_timeout, timeout, proxies={}
): # noqa: E501
# type: (str, dict, Optional[Union[dict, list]], int, int, dict) -> None # noqa: E501

Expand Down Expand Up @@ -143,12 +161,12 @@ def __eq__(self, other):

class Response(object):
def __init__(
self,
status_code=None,
content=None,
error_message="",
is_timed_out_error=False,
is_network_error=False,
self,
status_code=None,
content=None,
error_message="",
is_timed_out_error=False,
is_network_error=False,
):
# type: (int, Optional[Dict[str, Any]], str, bool, bool) -> None

Expand All @@ -158,6 +176,15 @@ def __init__(
self.is_timed_out_error = is_timed_out_error
self.is_network_error = is_network_error

def __str__(self):
return "Response({}, {}, {}, {}, {})".format(
self.status_code,
self.content,
self.error_message,
self.is_timed_out_error,
self.is_network_error,
)


class RetryStrategy(object):
def valid_hosts(self, hosts):
Expand Down Expand Up @@ -205,9 +232,9 @@ def _is_retryable(self, response):
return True

return (
response.status_code is not None
and (response.status_code // 100) != 2
and (response.status_code // 100) != 4
response.status_code is not None
and (response.status_code // 100) != 2
and (response.status_code // 100) != 4
)


Expand Down
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ passenv =
ALGOLIA_ADMIN_KEY_2
ALGOLIA_APPLICATION_ID_MCM
ALGOLIA_ADMIN_KEY_MCM
DEBUG
commands =
py27-sync: python -m unittest discover -v
py27-async: python -c 'print "No asynchronous tests for Python 2.7, skipping."'
Expand Down

0 comments on commit 8c67ee0

Please sign in to comment.