Skip to content
This repository was archived by the owner on Sep 17, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions contrib/opencensus-ext-django/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Unreleased

- Add exception tracing to django middleware
([#885](https://github.com/census-instrumentation/opencensus-python/pull/885))

## 0.7.4
Released 2021-01-19

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
import six

import logging
import sys
import traceback

import django
import django.conf
Expand All @@ -42,6 +44,9 @@
HTTP_ROUTE = attributes_helper.COMMON_ATTRIBUTES['HTTP_ROUTE']
HTTP_URL = attributes_helper.COMMON_ATTRIBUTES['HTTP_URL']
HTTP_STATUS_CODE = attributes_helper.COMMON_ATTRIBUTES['HTTP_STATUS_CODE']
ERROR_MESSAGE = attributes_helper.COMMON_ATTRIBUTES['ERROR_MESSAGE']
ERROR_NAME = attributes_helper.COMMON_ATTRIBUTES['ERROR_NAME']
STACKTRACE = attributes_helper.COMMON_ATTRIBUTES['STACKTRACE']

REQUEST_THREAD_LOCAL_KEY = 'django_request'
SPAN_THREAD_LOCAL_KEY = 'django_span'
Expand Down Expand Up @@ -267,3 +272,29 @@ def process_response(self, request, response):
log.error('Failed to trace request', exc_info=True)
finally:
return response

def process_exception(self, request, exception):
# Do not trace if the url is excluded
if utils.disable_tracing_url(request.path, self.excludelist_paths):
return

try:
if hasattr(exception, '__traceback__'):
tb = exception.__traceback__
else:
_, _, tb = sys.exc_info()

span = _get_django_span()
span.add_attribute(
attribute_key=ERROR_NAME,
attribute_value=exception.__class__.__name__)
span.add_attribute(
attribute_key=ERROR_MESSAGE,
attribute_value=str(exception))
span.add_attribute(
attribute_key=STACKTRACE,
attribute_value='\n'.join(traceback.format_tb(tb)))

_set_django_attributes(span, request)
except Exception: # pragma: NO COVER
log.error('Failed to trace request', exc_info=True)
69 changes: 69 additions & 0 deletions contrib/opencensus-ext-django/tests/test_django_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
import traceback
import unittest

import mock
Expand Down Expand Up @@ -291,6 +293,73 @@ def test_process_response_unfinished_child_span(self):

self.assertEqual(span.attributes, expected_attributes)

def test_process_exception(self):
from opencensus.ext.django import middleware

trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'
span_id = '6e0c63257de34c92'
django_trace_id = '00-{}-{}-00'.format(trace_id, span_id)

django_request = RequestFactory().get('/wiki/Rabbit', **{
'traceparent': django_trace_id,
})

# Force the test request to be sampled
settings = type('Test', (object,), {})
settings.OPENCENSUS = {
'TRACE': {
'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()', # noqa
}
}
patch_settings = mock.patch(
'django.conf.settings',
settings)

with patch_settings:
middleware_obj = middleware.OpencensusMiddleware()

tb = None
try:
raise RuntimeError("bork bork bork")
except Exception as exc:
test_exception = exc
if hasattr(exc, "__traceback__"):
tb = exc.__traceback__
else:
_, _, tb = sys.exc_info()

middleware_obj.process_request(django_request)
tracer = middleware._get_current_tracer()
span = tracer.current_span()

exporter_mock = mock.Mock()
tracer.exporter = exporter_mock

django_response = mock.Mock()
django_response.status_code = 200

expected_attributes = {
'http.host': u'testserver',
'http.method': 'GET',
'http.path': u'/wiki/Rabbit',
'http.route': u'/wiki/Rabbit',
'http.url': u'http://testserver/wiki/Rabbit',
'django.user.id': '123',
'django.user.name': 'test_name',
'error.name': "RuntimeError",
'error.message': 'bork bork bork',
'stacktrace': '\n'.join(traceback.format_tb(tb))
}

mock_user = mock.Mock()
mock_user.pk = 123
mock_user.get_username.return_value = 'test_name'
django_request.user = mock_user

middleware_obj.process_exception(django_request, test_exception)

self.assertEqual(span.attributes, expected_attributes)


class Test__set_django_attributes(unittest.TestCase):
class Span(object):
Expand Down
2 changes: 1 addition & 1 deletion contrib/opencensus-ext-sqlalchemy/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
long_description=open('README.rst').read(),
install_requires=[
'opencensus >= 0.8.dev0, < 1.0.0',
'SQLAlchemy >= 1.1.14, < 2.0.0',
'SQLAlchemy >= 1.1.14, < 1.3.24', # https://github.com/sqlalchemy/sqlalchemy/issues/6168 # noqa: E501
],
extras_require={},
license='Apache-2.0',
Expand Down