Skip to content

Commit d98f812

Browse files
authored
print error message when submit fails in Django test command (#855)
Due to a refactor in the past, the Django test command did not print an error anymore when sending a message to the APM Server failed. Added a fix and test.
1 parent 321a344 commit d98f812

File tree

7 files changed

+48
-32
lines changed

7 files changed

+48
-32
lines changed

elasticapm/contrib/django/management/commands/elasticapm.py

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131

3232
from __future__ import absolute_import
3333

34+
import logging
3435
import sys
3536

3637
from django.conf import settings
@@ -132,6 +133,19 @@ def handle(self, *args, **options):
132133
def handle_test(self, command, **options):
133134
"""Send a test error to APM Server"""
134135
# can't be async for testing
136+
137+
class LogCaptureHandler(logging.Handler):
138+
def __init__(self, level=logging.NOTSET):
139+
self.logs = []
140+
super(LogCaptureHandler, self).__init__(level)
141+
142+
def handle(self, record):
143+
self.logs.append(record)
144+
145+
handler = LogCaptureHandler()
146+
logger = logging.getLogger("elasticapm.transport")
147+
logger.addHandler(handler)
148+
135149
config = {"async_mode": False}
136150
for key in ("service_name", "secret_token"):
137151
if options.get(key):
@@ -150,14 +164,17 @@ def handle_test(self, command, **options):
150164
raise TestException("Hi there!")
151165
except TestException:
152166
client.capture_exception()
153-
if not client.error_logger.errors:
154-
self.write(
155-
"Success! We tracked the error successfully! \n"
156-
"You should see it in the APM app in Kibana momentarily. \n"
157-
'Look for "TestException: Hi there!" in the Errors tab of the %s app' % client.config.service_name
158-
)
159-
finally:
160-
client.close()
167+
client.close()
168+
if not handler.logs:
169+
self.write(
170+
"Success! We tracked the error successfully! \n"
171+
"You should see it in the APM app in Kibana momentarily. \n"
172+
'Look for "TestException: Hi there!" in the Errors tab of the %s app' % client.config.service_name
173+
)
174+
else:
175+
self.write("Oops. That didn't work. The following error occured: \n\n", red)
176+
for entry in handler.logs:
177+
self.write(entry.getMessage(), red)
161178

162179
def handle_check(self, command, **options):
163180
"""Check your settings for common misconfigurations"""

elasticapm/transport/base.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,6 @@
4545
logger = get_logger("elasticapm.transport")
4646

4747

48-
class TransportException(Exception):
49-
def __init__(self, message, data=None, print_trace=True):
50-
super(TransportException, self).__init__(message)
51-
self.data = data
52-
self.print_trace = print_trace
53-
54-
5548
class Transport(ThreadManager):
5649
"""
5750
All transport implementations need to subclass this class

elasticapm/transport/exceptions.py

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,8 @@
3232
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3333

3434

35-
class InvalidScheme(ValueError):
36-
"""
37-
Raised when a transport is constructed using a URI which is not
38-
handled by the transport
39-
"""
40-
41-
42-
class DuplicateScheme(Exception):
43-
"""
44-
Raised when registering a handler for a particular scheme which
45-
is already registered
46-
"""
47-
48-
pass
35+
class TransportException(Exception):
36+
def __init__(self, message, data=None, print_trace=True):
37+
super(TransportException, self).__init__(message)
38+
self.data = data
39+
self.print_trace = print_trace

elasticapm/transport/http.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
import urllib3
3939
from urllib3.exceptions import MaxRetryError, TimeoutError
4040

41-
from elasticapm.transport.base import TransportException
41+
from elasticapm.transport.exceptions import TransportException
4242
from elasticapm.transport.http_base import HTTPTransportBase
4343
from elasticapm.utils import compat, json_encoder, read_pem_file
4444
from elasticapm.utils.logging import get_logger

tests/contrib/django/django_tests.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1291,6 +1291,20 @@ def test_test_exception(urlopen_mock):
12911291
assert "Success! We tracked the error successfully!" in output
12921292

12931293

1294+
@pytest.mark.parametrize(
1295+
"django_elasticapm_client", [{"transport_class": "elasticapm.transport.http.Transport"}], indirect=True
1296+
)
1297+
def test_test_exception_fails(django_elasticapm_client):
1298+
stdout = compat.StringIO()
1299+
with override_settings(
1300+
ELASTIC_APM={"TRANSPORT_CLASS": "elasticapm.transport.http.Transport"},
1301+
**middleware_setting(django.VERSION, ["foo", "elasticapm.contrib.django.middleware.TracingMiddleware"])
1302+
):
1303+
call_command("elasticapm", "test", stdout=stdout, stderr=stdout)
1304+
output = stdout.getvalue()
1305+
assert "Oops" in output
1306+
1307+
12941308
def test_tracing_middleware_uses_test_client(client, django_elasticapm_client):
12951309
with override_settings(
12961310
**middleware_setting(django.VERSION, ["elasticapm.contrib.django.middleware.TracingMiddleware"])

tests/transports/test_base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@
3737
import mock
3838
import pytest
3939

40-
from elasticapm.transport.base import Transport, TransportException, TransportState
40+
from elasticapm.transport.base import Transport, TransportState
41+
from elasticapm.transport.exceptions import TransportException
4142
from elasticapm.utils import compat
4243
from tests.fixtures import DummyTransport, TempStoreClient
4344
from tests.utils import assert_any_record_contains

tests/transports/test_urllib3.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
from urllib3.exceptions import MaxRetryError, TimeoutError
3838

3939
from elasticapm.conf import constants
40-
from elasticapm.transport.base import TransportException
40+
from elasticapm.transport.exceptions import TransportException
4141
from elasticapm.transport.http import Transport
4242
from elasticapm.utils import compat
4343

0 commit comments

Comments
 (0)