Skip to content

Commit 994358c

Browse files
Do not raise exception on flusher stop (#19)
Co-authored-by: Šimon Let <[email protected]>
1 parent 24034a0 commit 994358c

File tree

2 files changed

+23
-7
lines changed

2 files changed

+23
-7
lines changed

logtail/flusher.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# coding: utf-8
22
from __future__ import print_function, unicode_literals
3-
import sys
4-
import time
3+
54
import threading
5+
import time
66

77
from .compat import queue
88

@@ -17,9 +17,10 @@ def __init__(self, upload, pipe, buffer_capacity, flush_interval):
1717
self.pipe = pipe
1818
self.buffer_capacity = buffer_capacity
1919
self.flush_interval = flush_interval
20+
self.should_run = True
2021

2122
def run(self):
22-
while True:
23+
while self.should_run:
2324
self.step()
2425

2526
def step(self):
@@ -68,7 +69,7 @@ def step(self):
6869
print('Failed to send logs to Better Stack after {} retries: {}'.format(len(RETRY_SCHEDULE), response.exception))
6970

7071
if shutdown and self.pipe.empty():
71-
sys.exit(0)
72+
self.should_run = False
7273

7374

7475
def _initial_time_remaining(flush_interval):

tests/test_flusher.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# coding: utf-8
22
from __future__ import print_function, unicode_literals
33
import mock
4+
import sys
45
import time
56
import threading
67
import unittest
@@ -120,8 +121,7 @@ def sleep(time):
120121
self.assertEqual(self.uploader_calls, len(RETRY_SCHEDULE) + 1)
121122
self.assertEqual(self.sleep_calls, len(RETRY_SCHEDULE))
122123

123-
@mock.patch('logtail.flusher.sys.exit')
124-
def test_shutdown_condition_empties_queue_and_calls_exit(self, mock_exit):
124+
def test_shutdown_condition_empties_queue_and_shuts_down(self):
125125
self.buffer_capacity = 10
126126
num_items = 5
127127
first_frame = list(range(self.buffer_capacity))
@@ -141,4 +141,19 @@ def uploader(frame):
141141

142142
fw.step()
143143
self.assertEqual(self.upload_calls, 1)
144-
self.assertEqual(mock_exit.call_count, 1)
144+
self.assertFalse(fw.should_run)
145+
146+
# test relies on overriding excepthook which is available from 3.8+
147+
@unittest.skipIf(sys.version_info < (3, 8), "Test skipped because overriding excepthook is only available on Python 3.8+")
148+
def test_shutdown_dont_raise_exception_in_thread(self):
149+
original_excepthook = threading.excepthook
150+
threading.excepthook = mock.Mock()
151+
152+
_, _, fw = self._setup_worker()
153+
fw.parent_thread = mock.MagicMock(is_alive=lambda: False)
154+
fw.step()
155+
156+
self.assertFalse(fw.should_run)
157+
self.assertFalse(threading.excepthook.called)
158+
159+
threading.excepthook = original_excepthook

0 commit comments

Comments
 (0)