Skip to content

Commit b86cbd2

Browse files
jaygel179darinhoward
authored andcommitted
Clean up - remove redundancy and clean up code (#5)
* Clean up - remove redundancy and explicitly use stackify for internal logging * Add note when using stackify api python logging * disable stackify logging by default * update internal logging instructions * asign internal logging to a variable
1 parent 8f4c531 commit b86cbd2

File tree

5 files changed

+33
-30
lines changed

5 files changed

+33
-30
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ logger.warning('Something happened')
2727
```python
2828
import logging
2929
import stackify
30-
logger = logging.getLogger()
30+
logger = logging.getLogger(__name__)
3131
stackify_handler = stackify.StackifyHandler(application="Python Application", environment="Production", api_key="***")
3232
logger.addHandler(stackify_handler)
3333
logger.warning('Something happened')
@@ -68,7 +68,9 @@ This library has an internal logger it uses for debugging and messaging.
6868
For example, if you want to enable debug messages:
6969
```python
7070
import logging
71-
logging.getLogger('stackify').setLevel(logging.DEBUG)
71+
logger = logging.getLogger('stackify')
72+
logger.setLevel(logging.DEBUG)
73+
logger.addHandler(logging.FileHandler('stackify.log')) # or any handler you want
7274
```
7375

7476
By default, it will enable the default logging settings via `logging.basicConfig()`

stackify/__init__.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@ def emit(self, record):
1717
pass
1818

1919

20-
logging.getLogger(__name__).addHandler(NullHandler())
20+
internal_logger = logging.getLogger(__name__)
21+
internal_logger.addHandler(NullHandler())
22+
internal_logger.propagate = False
23+
internal_logger.setLevel(DEFAULT_LEVEL)
2124

2225

2326
def getLogger(name=None, auto_shutdown=True, basic_config=True, **kwargs):
@@ -52,8 +55,7 @@ def getLogger(name=None, auto_shutdown=True, basic_config=True, **kwargs):
5255

5356
logger = logging.getLogger(name)
5457

55-
if not [isinstance(x, StackifyHandler) for x in logger.handlers]:
56-
internal_logger = logging.getLogger(__name__)
58+
if not any([isinstance(x, StackifyHandler) for x in logger.handlers]):
5759
internal_logger.debug('Creating handler for logger %s', name)
5860

5961
if auto_shutdown:
@@ -66,8 +68,6 @@ def getLogger(name=None, auto_shutdown=True, basic_config=True, **kwargs):
6668
handler = StackifyHandler(ensure_at_exit=not auto_shutdown, **kwargs)
6769
logger.addHandler(handler)
6870

69-
handler.listener.start()
70-
7171
return logger
7272

7373

@@ -77,7 +77,7 @@ def stopLogging(logger):
7777
Shut down the StackifyHandler on a given logger. This will block
7878
and wait for the queue to finish uploading.
7979
'''
80-
internal_logger = logging.getLogger(__name__)
80+
8181
internal_logger.debug('Shutting down all handlers')
8282
for handler in getHandlers(logger):
8383
handler.listener.stop()

stackify/application.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ def arg_or_env(name, args, default=None):
3636

3737

3838
def get_configuration(**kwargs):
39-
return ApiConfiguration(
40-
application=arg_or_env('application', kwargs),
41-
environment=arg_or_env('environment', kwargs),
42-
api_key=arg_or_env('api_key', kwargs),
43-
api_url=arg_or_env('api_url', kwargs, API_URL))
39+
return ApiConfiguration(
40+
application=arg_or_env('application', kwargs),
41+
environment=arg_or_env('environment', kwargs),
42+
api_key=arg_or_env('api_key', kwargs),
43+
api_url=arg_or_env('api_url', kwargs, API_URL))

stackify/handler.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020
from stackify.timer import RepeatedTimer
2121

2222

23+
internal_logger = logging.getLogger(__name__)
24+
25+
2326
class StackifyHandler(QueueHandler):
2427
'''
2528
A handler class to format and queue log messages for later
@@ -39,6 +42,7 @@ def __init__(self, queue_=None, listener=None, ensure_at_exit=True, **kwargs):
3942
self.listener.start()
4043

4144
if ensure_at_exit:
45+
internal_logger.debug('Registering atexit callback')
4246
atexit.register(self.listener.stop)
4347

4448
def enqueue(self, record):
@@ -48,8 +52,7 @@ def enqueue(self, record):
4852
try:
4953
self.queue.put_nowait(record)
5054
except queue.Full:
51-
logger = logging.getLogger(__name__)
52-
logger.warning('StackifyHandler queue is full, evicting oldest record')
55+
internal_logger.warning('StackifyHandler queue is full, evicting oldest record')
5356
self.queue.get_nowait()
5457
self.queue.put_nowait(record)
5558

@@ -74,8 +77,7 @@ def __init__(self, queue_, max_batch=MAX_BATCH, config=None, **kwargs):
7477

7578
def handle(self, record):
7679
if not self.http.identified:
77-
logger = logging.getLogger(__name__)
78-
logger.debug('Identifying application')
80+
internal_logger.debug('Identifying application')
7981
self.http.identify_application()
8082

8183
msg = LogMsg()
@@ -93,22 +95,19 @@ def send_group(self):
9395
try:
9496
self.http.send_log_group(group)
9597
except Exception:
96-
logger = logging.getLogger(__name__)
97-
logger.exception('Could not send {} log messages, discarding'.format(len(self.messages)))
98+
internal_logger.exception('Could not send {} log messages, discarding'.format(len(self.messages)))
9899
del self.messages[:]
99100

100101
def start(self):
101-
logger = logging.getLogger(__name__)
102-
logger.debug('Starting up listener')
102+
internal_logger.debug('Starting up listener')
103103

104104
if not self._started:
105105
super(StackifyListener, self).start()
106106
self.timer.start()
107107
self._started = True
108108

109109
def stop(self):
110-
logger = logging.getLogger(__name__)
111-
logger.debug('Shutting down listener')
110+
internal_logger.debug('Shutting down listener')
112111

113112
if self._started:
114113
super(StackifyListener, self).stop()
@@ -117,5 +116,5 @@ def stop(self):
117116

118117
# send any remaining messages
119118
if self.messages:
120-
logger.debug('{} messages left on shutdown, uploading'.format(len(self.messages)))
119+
internal_logger.debug('{} messages left on shutdown, uploading'.format(len(self.messages)))
121120
self.send_group()

stackify/http.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
from stackify.constants import READ_TIMEOUT
1818

1919

20+
internal_logger = logging.getLogger(__name__)
21+
22+
2023
def gzip_compress(data):
2124
if hasattr(gzip, 'compress'):
2225
return gzip.compress(bytes(data, 'utf-8')) # python 3
@@ -41,8 +44,7 @@ def __init__(self, api_config):
4144

4245
def POST(self, url, json_object, use_gzip=False):
4346
request_url = self.api_config.api_url + url
44-
logger = logging.getLogger(__name__)
45-
logger.debug('Request URL: {}'.format(request_url))
47+
internal_logger.debug('Request URL: {}'.format(request_url))
4648

4749
headers = {
4850
'Content-Type': 'application/json',
@@ -52,7 +54,7 @@ def POST(self, url, json_object, use_gzip=False):
5254

5355
try:
5456
payload_data = json_object.toJSON()
55-
logger.debug('POST data: {}'.format(payload_data))
57+
internal_logger.debug('POST data: {}'.format(payload_data))
5658

5759
if use_gzip:
5860
headers['Content-Encoding'] = 'gzip'
@@ -62,13 +64,13 @@ def POST(self, url, json_object, use_gzip=False):
6264
data=payload_data,
6365
headers=headers,
6466
timeout=READ_TIMEOUT)
65-
logger.debug('Response: {}'.format(response.text))
67+
internal_logger.debug('Response: {}'.format(response.text))
6668
return response.json()
6769
except requests.exceptions.RequestException:
68-
logger.exception('HTTP exception')
70+
internal_logger.exception('HTTP exception')
6971
except ValueError:
7072
# could not read json response
71-
logger.exception('Cannot decode JSON response')
73+
internal_logger.exception('Cannot decode JSON response')
7274

7375
@retrying.retry(wait_exponential_multiplier=1000, stop_max_delay=10000)
7476
def identify_application(self):

0 commit comments

Comments
 (0)