logtail-python 0.4.0__tar.gz → 0.4.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {logtail_python-0.4.0/logtail_python.egg-info → logtail_python-0.4.1}/PKG-INFO +2 -2
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail/__init__.py +1 -1
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail/flusher.py +19 -2
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail/handler.py +28 -2
- logtail_python-0.4.1/logtail/rq.py +29 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1/logtail_python.egg-info}/PKG-INFO +2 -2
- logtail_python-0.4.1/logtail_python.egg-info/SOURCES.txt +29 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/setup.py +1 -1
- {logtail_python-0.4.0 → logtail_python-0.4.1}/test-requirements.txt +1 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/tests/test_flusher.py +43 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/tests/test_handler.py +102 -0
- logtail_python-0.4.1/tests/test_rq.py +81 -0
- logtail_python-0.4.0/logtail_python.egg-info/SOURCES.txt +0 -42
- logtail_python-0.4.0/tests/__pycache__/__init__.cpython-311.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/__init__.cpython-314.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_flusher.cpython-311.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_flusher.cpython-314-pytest-9.1.1.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_flusher.cpython-314.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_formatter.cpython-311.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_formatter.cpython-314-pytest-9.1.1.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_frame.cpython-311.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_frame.cpython-314-pytest-9.1.1.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_handler.cpython-311.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_handler.cpython-314-pytest-9.1.1.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_helpers.cpython-311.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_helpers.cpython-314-pytest-9.1.1.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_uploader.cpython-311.pyc +0 -0
- logtail_python-0.4.0/tests/__pycache__/test_uploader.cpython-314-pytest-9.1.1.pyc +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/LICENSE.md +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/MANIFEST.in +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/README.md +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail/compat.py +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail/formatter.py +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail/frame.py +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail/helpers.py +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail/uploader.py +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail_python.egg-info/dependency_links.txt +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail_python.egg-info/requires.txt +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/logtail_python.egg-info/top_level.txt +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/requirements.txt +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/setup.cfg +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/tests/__init__.py +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/tests/test_formatter.py +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/tests/test_frame.py +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/tests/test_helpers.py +0 -0
- {logtail_python-0.4.0 → logtail_python-0.4.1}/tests/test_uploader.py +0 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: logtail-python
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.1
|
|
4
4
|
Summary: Better Stack client library
|
|
5
5
|
Home-page: https://github.com/logtail/logtail-python
|
|
6
|
-
Download-URL: https://github.com/logtail/logtail-python/tarball/0.4.
|
|
6
|
+
Download-URL: https://github.com/logtail/logtail-python/tarball/0.4.1
|
|
7
7
|
Author: Logtail
|
|
8
8
|
Author-email: hello@logtail.com
|
|
9
9
|
License: ISC
|
|
@@ -9,6 +9,14 @@ from .compat import queue
|
|
|
9
9
|
RETRY_SCHEDULE = (1, 10, 60) # seconds
|
|
10
10
|
|
|
11
11
|
|
|
12
|
+
class TransportFrame(dict):
|
|
13
|
+
"""A record logged by a flush worker itself, i.e. urllib3 describing our own upload.
|
|
14
|
+
|
|
15
|
+
It rides along with the next batch of regular records but never triggers an upload
|
|
16
|
+
on its own, since that upload would log again and the queue would never drain.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
|
|
12
20
|
class FlushWorker(threading.Thread):
|
|
13
21
|
def __init__(self, upload, pipe, buffer_capacity, flush_interval, check_interval):
|
|
14
22
|
threading.Thread.__init__(self)
|
|
@@ -71,7 +79,7 @@ class FlushWorker(threading.Thread):
|
|
|
71
79
|
# count) and sends them to the Better Stack endpoint all at once. If the
|
|
72
80
|
# request fails in a way that can be retried, it is retried with an
|
|
73
81
|
# exponential backoff in between attempts.
|
|
74
|
-
if frame:
|
|
82
|
+
if frame and not all(isinstance(entry, TransportFrame) for entry in frame):
|
|
75
83
|
response = None
|
|
76
84
|
for delay in RETRY_SCHEDULE + (None, ):
|
|
77
85
|
response = self.upload(frame)
|
|
@@ -80,7 +88,12 @@ class FlushWorker(threading.Thread):
|
|
|
80
88
|
if delay is not None:
|
|
81
89
|
time.sleep(delay)
|
|
82
90
|
|
|
83
|
-
|
|
91
|
+
# A network error surfaces as a Fake500 that carries an `exception`
|
|
92
|
+
# attribute; a genuine server HTTP 500 is a real `requests.Response`
|
|
93
|
+
# that has no such attribute. Use a default so the latter doesn't
|
|
94
|
+
# raise AttributeError here and kill the flush thread (dropping all
|
|
95
|
+
# subsequent logs for the life of the process).
|
|
96
|
+
if response.status_code == 500 and getattr(response, "exception", None) is not None:
|
|
84
97
|
print('Failed to send logs to Better Stack after {} retries: {}'.format(len(RETRY_SCHEDULE), response.exception))
|
|
85
98
|
|
|
86
99
|
self._clean = True
|
|
@@ -93,6 +106,10 @@ class FlushWorker(threading.Thread):
|
|
|
93
106
|
time.sleep(self.check_interval)
|
|
94
107
|
self._flushing = False
|
|
95
108
|
|
|
109
|
+
def in_flush_worker():
|
|
110
|
+
return isinstance(threading.current_thread(), FlushWorker)
|
|
111
|
+
|
|
112
|
+
|
|
96
113
|
def _initial_time_remaining(flush_interval):
|
|
97
114
|
return flush_interval
|
|
98
115
|
|
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
from __future__ import print_function, unicode_literals
|
|
3
3
|
import logging
|
|
4
4
|
import json
|
|
5
|
+
import os
|
|
6
|
+
import weakref
|
|
5
7
|
|
|
6
8
|
from .compat import queue
|
|
7
9
|
from .helpers import DEFAULT_CONTEXT
|
|
8
|
-
from .flusher import FlushWorker
|
|
10
|
+
from .flusher import FlushWorker, TransportFrame, in_flush_worker
|
|
9
11
|
from .uploader import Uploader
|
|
10
12
|
from .frame import create_frame
|
|
11
13
|
|
|
@@ -18,6 +20,8 @@ DEFAULT_DROP_EXTRA_EVENTS = True
|
|
|
18
20
|
DEFAULT_INCLUDE_EXTRA_ATTRIBUTES = True
|
|
19
21
|
DEFAULT_TIMEOUT = 30
|
|
20
22
|
|
|
23
|
+
_handlers = weakref.WeakSet()
|
|
24
|
+
|
|
21
25
|
|
|
22
26
|
class LogtailHandler(logging.Handler):
|
|
23
27
|
def __init__(self,
|
|
@@ -50,6 +54,7 @@ class LogtailHandler(logging.Handler):
|
|
|
50
54
|
self.dropcount = 0
|
|
51
55
|
# Do not initialize the flush thread yet because it causes issues on Render.
|
|
52
56
|
self.flush_thread = None
|
|
57
|
+
_handlers.add(self)
|
|
53
58
|
|
|
54
59
|
def ensure_flush_thread_alive(self):
|
|
55
60
|
if self.flush_thread and self.flush_thread.is_alive():
|
|
@@ -71,8 +76,12 @@ class LogtailHandler(logging.Handler):
|
|
|
71
76
|
message = self.format(record)
|
|
72
77
|
frame = create_frame(record, message, self.context, include_extra_attributes=self.include_extra_attributes)
|
|
73
78
|
serializable_frame = json.loads(json.dumps(frame, default=str))
|
|
79
|
+
transport = in_flush_worker()
|
|
80
|
+
if transport:
|
|
81
|
+
serializable_frame = TransportFrame(serializable_frame)
|
|
74
82
|
try:
|
|
75
|
-
|
|
83
|
+
# The flush worker must never block on its own queue, so its records are dropped when full.
|
|
84
|
+
self.pipe.put(serializable_frame, block=(not self.drop_extra_events) and not transport)
|
|
76
85
|
except queue.Full:
|
|
77
86
|
# Only raised when not blocking, which means that extra events
|
|
78
87
|
# should be dropped.
|
|
@@ -84,3 +93,20 @@ class LogtailHandler(logging.Handler):
|
|
|
84
93
|
def flush(self):
|
|
85
94
|
if self.flush_thread and self.flush_thread.is_alive():
|
|
86
95
|
self.flush_thread.flush()
|
|
96
|
+
|
|
97
|
+
def _reset_after_fork(self):
|
|
98
|
+
# A forked child inherits the parent's queue with whatever was still buffered in it,
|
|
99
|
+
# a flush thread object whose thread does not exist in the child, and an HTTP session
|
|
100
|
+
# whose socket it shares with the parent, so it starts over with fresh ones.
|
|
101
|
+
self.pipe = queue.Queue(maxsize=self.buffer_capacity)
|
|
102
|
+
self.flush_thread = None
|
|
103
|
+
self.uploader = Uploader(self.source_token, self.host, self.uploader.timeout)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _reset_handlers_after_fork():
|
|
107
|
+
for handler in _handlers:
|
|
108
|
+
handler._reset_after_fork()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if hasattr(os, 'register_at_fork'):
|
|
112
|
+
os.register_at_fork(after_in_child=_reset_handlers_after_fork)
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
from __future__ import print_function, unicode_literals
|
|
3
|
+
import logging
|
|
4
|
+
|
|
5
|
+
import rq
|
|
6
|
+
|
|
7
|
+
from .handler import LogtailHandler
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Worker(rq.Worker):
|
|
11
|
+
"""An RQ worker that sends buffered log records after every job.
|
|
12
|
+
|
|
13
|
+
RQ runs each job in a forked work horse and ends it with os._exit(), which skips the
|
|
14
|
+
interpreter shutdown that would otherwise let LogtailHandler flush. Use it with
|
|
15
|
+
`rq worker --worker-class logtail.rq.Worker` or `RQ = {"WORKER_CLASS": "logtail.rq.Worker"}`
|
|
16
|
+
in django-rq.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def perform_job(self, job, queue):
|
|
20
|
+
try:
|
|
21
|
+
return super(Worker, self).perform_job(job, queue)
|
|
22
|
+
finally:
|
|
23
|
+
for handler in _logtail_handlers():
|
|
24
|
+
handler.flush()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _logtail_handlers():
|
|
28
|
+
loggers = [logging.getLogger()] + [logger for logger in logging.Logger.manager.loggerDict.values() if isinstance(logger, logging.Logger)]
|
|
29
|
+
return {handler for logger in loggers for handler in logger.handlers if isinstance(handler, LogtailHandler)}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: logtail-python
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.1
|
|
4
4
|
Summary: Better Stack client library
|
|
5
5
|
Home-page: https://github.com/logtail/logtail-python
|
|
6
|
-
Download-URL: https://github.com/logtail/logtail-python/tarball/0.4.
|
|
6
|
+
Download-URL: https://github.com/logtail/logtail-python/tarball/0.4.1
|
|
7
7
|
Author: Logtail
|
|
8
8
|
Author-email: hello@logtail.com
|
|
9
9
|
License: ISC
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
LICENSE.md
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
requirements.txt
|
|
5
|
+
setup.cfg
|
|
6
|
+
setup.py
|
|
7
|
+
test-requirements.txt
|
|
8
|
+
logtail/__init__.py
|
|
9
|
+
logtail/compat.py
|
|
10
|
+
logtail/flusher.py
|
|
11
|
+
logtail/formatter.py
|
|
12
|
+
logtail/frame.py
|
|
13
|
+
logtail/handler.py
|
|
14
|
+
logtail/helpers.py
|
|
15
|
+
logtail/rq.py
|
|
16
|
+
logtail/uploader.py
|
|
17
|
+
logtail_python.egg-info/PKG-INFO
|
|
18
|
+
logtail_python.egg-info/SOURCES.txt
|
|
19
|
+
logtail_python.egg-info/dependency_links.txt
|
|
20
|
+
logtail_python.egg-info/requires.txt
|
|
21
|
+
logtail_python.egg-info/top_level.txt
|
|
22
|
+
tests/__init__.py
|
|
23
|
+
tests/test_flusher.py
|
|
24
|
+
tests/test_formatter.py
|
|
25
|
+
tests/test_frame.py
|
|
26
|
+
tests/test_handler.py
|
|
27
|
+
tests/test_helpers.py
|
|
28
|
+
tests/test_rq.py
|
|
29
|
+
tests/test_uploader.py
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# coding: utf-8
|
|
2
2
|
from __future__ import print_function, unicode_literals
|
|
3
3
|
import mock
|
|
4
|
+
import requests
|
|
4
5
|
import time
|
|
5
6
|
import threading
|
|
6
7
|
import unittest
|
|
@@ -123,6 +124,48 @@ class TestFlushWorker(unittest.TestCase):
|
|
|
123
124
|
self.assertEqual(self.uploader_calls, len(RETRY_SCHEDULE) + 1)
|
|
124
125
|
self.assertEqual(self.sleep_calls, len(RETRY_SCHEDULE))
|
|
125
126
|
|
|
127
|
+
@patch('logtail.flusher.time.sleep')
|
|
128
|
+
def test_step_does_not_crash_on_real_server_500(self, _mock_sleep):
|
|
129
|
+
# Regression: a genuine server HTTP 500 returns a real requests.Response,
|
|
130
|
+
# which (unlike the network-error Fake500) has no `.exception` attribute.
|
|
131
|
+
# `getattr(response, "exception")` without a default raised AttributeError
|
|
132
|
+
# here, which propagates out of step()/run() and kills the flush thread —
|
|
133
|
+
# every subsequent log is then queued but never sent. (Note: MagicMock
|
|
134
|
+
# would auto-vivify `.exception` and hide the bug, so use a real Response.)
|
|
135
|
+
first_frame = list(range(self.buffer_capacity))
|
|
136
|
+
|
|
137
|
+
def uploader(frame):
|
|
138
|
+
resp = requests.models.Response()
|
|
139
|
+
resp.status_code = 500
|
|
140
|
+
return resp
|
|
141
|
+
|
|
142
|
+
pipe, _, fw = self._setup_worker(uploader)
|
|
143
|
+
for log in first_frame:
|
|
144
|
+
pipe.put(log, block=False)
|
|
145
|
+
|
|
146
|
+
fw.step() # must not raise AttributeError
|
|
147
|
+
|
|
148
|
+
self.assertTrue(fw._clean)
|
|
149
|
+
|
|
150
|
+
@patch('logtail.flusher.time.sleep')
|
|
151
|
+
def test_step_still_logs_network_error_fake500(self, _mock_sleep):
|
|
152
|
+
# The network-error path (Fake500 carrying an exception) must still log.
|
|
153
|
+
from logtail.uploader import Fake500
|
|
154
|
+
|
|
155
|
+
first_frame = list(range(self.buffer_capacity))
|
|
156
|
+
|
|
157
|
+
def uploader(frame):
|
|
158
|
+
return Fake500(Exception('network is down'))
|
|
159
|
+
|
|
160
|
+
pipe, _, fw = self._setup_worker(uploader)
|
|
161
|
+
for log in first_frame:
|
|
162
|
+
pipe.put(log, block=False)
|
|
163
|
+
|
|
164
|
+
with patch('builtins.print') as mock_print:
|
|
165
|
+
fw.step()
|
|
166
|
+
|
|
167
|
+
mock_print.assert_called_once()
|
|
168
|
+
|
|
126
169
|
def test_shutdown_condition_empties_queue_and_shuts_down(self):
|
|
127
170
|
self.buffer_capacity = 10
|
|
128
171
|
num_items = 5
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# coding: utf-8
|
|
2
2
|
from __future__ import print_function, unicode_literals
|
|
3
3
|
import mock
|
|
4
|
+
import os
|
|
4
5
|
import time
|
|
5
6
|
import threading
|
|
6
7
|
import unittest
|
|
@@ -277,6 +278,107 @@ class TestLogtailHandler(unittest.TestCase):
|
|
|
277
278
|
self.assertEqual(log_entry['context']['data']['egg']['chicken']['egg'], "<omitted circular reference>")
|
|
278
279
|
self.assertTrue(handler.pipe.empty())
|
|
279
280
|
|
|
281
|
+
@patch('logtail.handler.FlushWorker')
|
|
282
|
+
def test_forked_child_starts_with_a_fresh_queue_thread_and_session(self, MockWorker):
|
|
283
|
+
handler = LogtailHandler(source_token=self.source_token)
|
|
284
|
+
logger = logging.getLogger(__name__)
|
|
285
|
+
logger.handlers = []
|
|
286
|
+
logger.addHandler(handler)
|
|
287
|
+
logger.critical('queued in the parent')
|
|
288
|
+
parent_session = handler.uploader.session
|
|
289
|
+
|
|
290
|
+
pid = os.fork()
|
|
291
|
+
if pid == 0:
|
|
292
|
+
fresh = handler.pipe.empty() and handler.flush_thread is None and handler.uploader.session is not parent_session
|
|
293
|
+
os._exit(0 if fresh else 1)
|
|
294
|
+
_, status = os.waitpid(pid, 0)
|
|
295
|
+
|
|
296
|
+
self.assertEqual(os.waitstatus_to_exitcode(status), 0)
|
|
297
|
+
self.assertEqual(handler.pipe.get(block=False)['message'], 'queued in the parent')
|
|
298
|
+
|
|
299
|
+
def test_flush_returns_when_the_upload_itself_logs_to_the_handler(self):
|
|
300
|
+
logger = logging.getLogger(__name__)
|
|
301
|
+
logger.handlers = []
|
|
302
|
+
logger.setLevel(logging.DEBUG)
|
|
303
|
+
handler = LogtailHandler(source_token=self.source_token, flush_interval=0.01, check_interval=0.01)
|
|
304
|
+
uploads = []
|
|
305
|
+
|
|
306
|
+
def upload(frame):
|
|
307
|
+
uploads.append(frame)
|
|
308
|
+
# urllib3 logs every request it makes at DEBUG, and a handler on the
|
|
309
|
+
# root logger receives that record.
|
|
310
|
+
logger.debug('http://in.logs.betterstack.com:443 "POST / HTTP/1.1" 202 0')
|
|
311
|
+
return mock.MagicMock(status_code=202)
|
|
312
|
+
|
|
313
|
+
handler.uploader = upload
|
|
314
|
+
logger.addHandler(handler)
|
|
315
|
+
logger.info('hello')
|
|
316
|
+
self.addCleanup(self._stop_flush_worker, handler)
|
|
317
|
+
|
|
318
|
+
flushed = threading.Event()
|
|
319
|
+
threading.Thread(target=lambda: (handler.flush(), flushed.set()), daemon=True).start()
|
|
320
|
+
|
|
321
|
+
self.assertTrue(flushed.wait(2), 'flush() did not return')
|
|
322
|
+
self.assertEqual([f['message'] for frame in uploads for f in frame], ['hello'])
|
|
323
|
+
|
|
324
|
+
def test_records_logged_by_the_upload_ride_along_with_the_next_batch(self):
|
|
325
|
+
logger = logging.getLogger(__name__)
|
|
326
|
+
logger.handlers = []
|
|
327
|
+
logger.setLevel(logging.DEBUG)
|
|
328
|
+
# Only a full buffer sends a batch within the test.
|
|
329
|
+
handler = LogtailHandler(source_token=self.source_token, buffer_capacity=2, flush_interval=1000, check_interval=0.01)
|
|
330
|
+
uploads = []
|
|
331
|
+
|
|
332
|
+
def upload(frame):
|
|
333
|
+
logger.debug('POST / 202') # what urllib3 does, still inside the request
|
|
334
|
+
uploads.append([f['message'] for f in frame])
|
|
335
|
+
return mock.MagicMock(status_code=202)
|
|
336
|
+
|
|
337
|
+
handler.uploader = upload
|
|
338
|
+
logger.addHandler(handler)
|
|
339
|
+
self.addCleanup(self._stop_flush_worker, handler)
|
|
340
|
+
|
|
341
|
+
logger.info('hello')
|
|
342
|
+
logger.info('hello again')
|
|
343
|
+
self._wait_until(lambda: len(uploads) == 1)
|
|
344
|
+
logger.info('world')
|
|
345
|
+
self._wait_until(lambda: len(uploads) == 2)
|
|
346
|
+
|
|
347
|
+
self.assertEqual(uploads, [['hello', 'hello again'], ['POST / 202', 'world']])
|
|
348
|
+
|
|
349
|
+
def test_a_batch_of_only_the_uploads_own_records_is_dropped_not_sent(self):
|
|
350
|
+
logger = logging.getLogger(__name__)
|
|
351
|
+
logger.handlers = []
|
|
352
|
+
logger.setLevel(logging.DEBUG)
|
|
353
|
+
handler = LogtailHandler(source_token=self.source_token, flush_interval=0.01, check_interval=0.01)
|
|
354
|
+
uploads = []
|
|
355
|
+
|
|
356
|
+
def upload(frame):
|
|
357
|
+
logger.debug('POST / 202')
|
|
358
|
+
uploads.append([f['message'] for f in frame])
|
|
359
|
+
return mock.MagicMock(status_code=202)
|
|
360
|
+
|
|
361
|
+
handler.uploader = upload
|
|
362
|
+
logger.addHandler(handler)
|
|
363
|
+
self.addCleanup(self._stop_flush_worker, handler)
|
|
364
|
+
|
|
365
|
+
logger.info('hello')
|
|
366
|
+
self._wait_until(lambda: len(uploads) == 1)
|
|
367
|
+
time.sleep(0.1) # several flush intervals, enough for the loop to show if it existed
|
|
368
|
+
|
|
369
|
+
self.assertEqual(uploads, [['hello']])
|
|
370
|
+
self.assertTrue(handler.pipe.empty())
|
|
371
|
+
|
|
372
|
+
def _wait_until(self, condition):
|
|
373
|
+
deadline = time.time() + 2
|
|
374
|
+
while not condition() and time.time() < deadline:
|
|
375
|
+
time.sleep(0.01)
|
|
376
|
+
self.assertTrue(condition())
|
|
377
|
+
|
|
378
|
+
def _stop_flush_worker(self, handler):
|
|
379
|
+
handler.flush_thread.should_run = False
|
|
380
|
+
handler.flush_thread.join(1)
|
|
381
|
+
|
|
280
382
|
|
|
281
383
|
class UnserializableObject(object):
|
|
282
384
|
""" Because this is a custom class, it cannot be serialized into JSON. """
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
from __future__ import print_function, unicode_literals
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import mock
|
|
6
|
+
import os
|
|
7
|
+
import unittest
|
|
8
|
+
|
|
9
|
+
from unittest.mock import patch
|
|
10
|
+
|
|
11
|
+
import rq
|
|
12
|
+
|
|
13
|
+
from logtail import LogtailHandler
|
|
14
|
+
from logtail.rq import Worker
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TestWorker(unittest.TestCase):
|
|
18
|
+
source_token = 'dummy_source_token'
|
|
19
|
+
|
|
20
|
+
def setUp(self):
|
|
21
|
+
self.logger = logging.getLogger(__name__)
|
|
22
|
+
self.logger.handlers = []
|
|
23
|
+
self.logger.setLevel(logging.DEBUG)
|
|
24
|
+
self.uploads = []
|
|
25
|
+
# Only an explicit flush can send anything within the test.
|
|
26
|
+
self.handler = LogtailHandler(source_token=self.source_token, flush_interval=1000, check_interval=0.01)
|
|
27
|
+
self.handler.uploader = self._upload
|
|
28
|
+
self.logger.addHandler(self.handler)
|
|
29
|
+
connection = mock.MagicMock()
|
|
30
|
+
connection.connection_pool.connection_kwargs = {}
|
|
31
|
+
self.worker = Worker(['default'], connection=connection, prepare_for_work=False)
|
|
32
|
+
|
|
33
|
+
def tearDown(self):
|
|
34
|
+
if self.handler.flush_thread:
|
|
35
|
+
self.handler.flush_thread.should_run = False
|
|
36
|
+
self.handler.flush_thread.join(1)
|
|
37
|
+
|
|
38
|
+
def _upload(self, frame):
|
|
39
|
+
self.uploads.append([f['message'] for f in frame])
|
|
40
|
+
return mock.MagicMock(status_code=202)
|
|
41
|
+
|
|
42
|
+
def test_is_an_rq_worker(self):
|
|
43
|
+
self.assertIsInstance(self.worker, rq.Worker)
|
|
44
|
+
|
|
45
|
+
@patch.object(rq.Worker, 'perform_job')
|
|
46
|
+
def test_flushes_logtail_handlers_after_the_job(self, perform_job):
|
|
47
|
+
perform_job.side_effect = lambda job, queue: self.logger.info('inside the job') or True
|
|
48
|
+
|
|
49
|
+
self.assertTrue(self.worker.perform_job(mock.sentinel.job, mock.sentinel.queue))
|
|
50
|
+
|
|
51
|
+
perform_job.assert_called_once_with(mock.sentinel.job, mock.sentinel.queue)
|
|
52
|
+
self.assertEqual(self.uploads, [['inside the job']])
|
|
53
|
+
|
|
54
|
+
@patch.object(rq.Worker, 'perform_job')
|
|
55
|
+
def test_flushes_logtail_handlers_when_the_job_raises(self, perform_job):
|
|
56
|
+
def fail(job, queue):
|
|
57
|
+
self.logger.error('the job blew up')
|
|
58
|
+
raise ValueError('boom')
|
|
59
|
+
perform_job.side_effect = fail
|
|
60
|
+
|
|
61
|
+
with self.assertRaises(ValueError):
|
|
62
|
+
self.worker.perform_job(mock.sentinel.job, mock.sentinel.queue)
|
|
63
|
+
|
|
64
|
+
self.assertEqual(self.uploads, [['the job blew up']])
|
|
65
|
+
|
|
66
|
+
@patch.object(rq.Worker, 'perform_job')
|
|
67
|
+
def test_records_logged_in_the_work_horse_are_sent_before_it_exits(self, perform_job):
|
|
68
|
+
# RQ forks a work horse per job and ends it with os._exit(), which skips
|
|
69
|
+
# the interpreter shutdown that would otherwise flush the handler.
|
|
70
|
+
perform_job.side_effect = lambda job, queue: self.logger.info('inside the work horse')
|
|
71
|
+
read_end, write_end = os.pipe()
|
|
72
|
+
self.handler.uploader = lambda frame: os.write(write_end, json.dumps([f['message'] for f in frame]).encode()) and mock.MagicMock(status_code=202)
|
|
73
|
+
|
|
74
|
+
pid = os.fork()
|
|
75
|
+
if pid == 0:
|
|
76
|
+
self.worker.main_work_horse(mock.MagicMock(), mock.MagicMock())
|
|
77
|
+
os.waitpid(pid, 0)
|
|
78
|
+
os.close(write_end)
|
|
79
|
+
os.set_blocking(read_end, False)
|
|
80
|
+
|
|
81
|
+
self.assertEqual(json.loads(os.read(read_end, 4096)), ['inside the work horse'])
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
LICENSE.md
|
|
2
|
-
MANIFEST.in
|
|
3
|
-
README.md
|
|
4
|
-
requirements.txt
|
|
5
|
-
setup.cfg
|
|
6
|
-
setup.py
|
|
7
|
-
test-requirements.txt
|
|
8
|
-
logtail/__init__.py
|
|
9
|
-
logtail/compat.py
|
|
10
|
-
logtail/flusher.py
|
|
11
|
-
logtail/formatter.py
|
|
12
|
-
logtail/frame.py
|
|
13
|
-
logtail/handler.py
|
|
14
|
-
logtail/helpers.py
|
|
15
|
-
logtail/uploader.py
|
|
16
|
-
logtail_python.egg-info/PKG-INFO
|
|
17
|
-
logtail_python.egg-info/SOURCES.txt
|
|
18
|
-
logtail_python.egg-info/dependency_links.txt
|
|
19
|
-
logtail_python.egg-info/requires.txt
|
|
20
|
-
logtail_python.egg-info/top_level.txt
|
|
21
|
-
tests/__init__.py
|
|
22
|
-
tests/test_flusher.py
|
|
23
|
-
tests/test_formatter.py
|
|
24
|
-
tests/test_frame.py
|
|
25
|
-
tests/test_handler.py
|
|
26
|
-
tests/test_helpers.py
|
|
27
|
-
tests/test_uploader.py
|
|
28
|
-
tests/__pycache__/__init__.cpython-311.pyc
|
|
29
|
-
tests/__pycache__/__init__.cpython-314.pyc
|
|
30
|
-
tests/__pycache__/test_flusher.cpython-311.pyc
|
|
31
|
-
tests/__pycache__/test_flusher.cpython-314-pytest-9.1.1.pyc
|
|
32
|
-
tests/__pycache__/test_flusher.cpython-314.pyc
|
|
33
|
-
tests/__pycache__/test_formatter.cpython-311.pyc
|
|
34
|
-
tests/__pycache__/test_formatter.cpython-314-pytest-9.1.1.pyc
|
|
35
|
-
tests/__pycache__/test_frame.cpython-311.pyc
|
|
36
|
-
tests/__pycache__/test_frame.cpython-314-pytest-9.1.1.pyc
|
|
37
|
-
tests/__pycache__/test_handler.cpython-311.pyc
|
|
38
|
-
tests/__pycache__/test_handler.cpython-314-pytest-9.1.1.pyc
|
|
39
|
-
tests/__pycache__/test_helpers.cpython-311.pyc
|
|
40
|
-
tests/__pycache__/test_helpers.cpython-314-pytest-9.1.1.pyc
|
|
41
|
-
tests/__pycache__/test_uploader.cpython-311.pyc
|
|
42
|
-
tests/__pycache__/test_uploader.cpython-314-pytest-9.1.1.pyc
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|