├── .editorconfig ├── .gitignore ├── .travis.yml ├── CHANGES ├── LICENSE ├── Makefile ├── README.rst ├── docs ├── Makefile ├── _static │ └── aws-xray-dashboard.png ├── _templates │ └── sidebar-intro.html ├── conf.py ├── index.rst ├── make.bat └── requirements.txt ├── setup.cfg ├── setup.py ├── src └── django_aws_xray │ ├── __init__.py │ ├── apps.py │ ├── connection.py │ ├── middleware.py │ ├── patches │ ├── __init__.py │ ├── cache.py │ ├── db.py │ ├── redis.py │ ├── requests.py │ ├── templates.py │ └── utils.py │ ├── records.py │ ├── traces.py │ └── xray.py ├── tests ├── __init__.py ├── app │ ├── urls.py │ └── views.py ├── conftest.py ├── test_connection.py ├── test_functional.py └── test_trace.py └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*.py] 4 | line_length = 79 5 | multi_line_output = 4 6 | balanced_wrapping = true 7 | known_first_party = django_xray,tests 8 | use_parentheses = true 9 | 10 | [*.yml] 11 | indent_size = 2 12 | 13 | 14 | [Makefile] 15 | indent_style = tab 16 | indent_size = 4 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info 2 | *.pyc 3 | .tox 4 | .coverage 5 | .coverage.* 6 | .eggs 7 | .cache 8 | .python-version 9 | .venv 10 | .idea/ 11 | 12 | /build/ 13 | /dist/ 14 | /docs/_build/ 15 | /htmlcov/ 16 | 17 | /xray_mac 18 | /cfg.yaml 19 | 20 | 21 | 22 | # Editors 23 | .idea/ 24 | .vscode/ 25 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | --- 2 | sudo: false 3 | language: python 4 | 5 | matrix: 6 | include: 7 | - python: 3.6 8 | env: TOXENV=py36-django111 9 | 10 | before_cache: 11 | - rm -rf $HOME/.cache/pip/log 12 | 13 | cache: 14 | directories: 15 | - $HOME/.cache/pip 16 | 17 | deps: 18 | - codecov 19 | 20 | install: 21 | - pip install tox codecov 22 | 23 | script: 24 | - tox -e $TOXENV 25 | 26 | after_success: 27 | - tox -e coverage-report 28 | - codecov 29 | 30 | notifications: 31 | email: false 32 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | 0.0.1 (unreleased) 2 | ================== 3 | - Created package 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Michael van Tellingen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | 24 | This project contains code from github.com/django-statsd/django-statsd:: 25 | 26 | BSD and MPL 27 | 28 | Portions of this are from commonware: 29 | 30 | https://github.com/jsocol/commonware/blob/master/LICENSE 31 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: install test upload docs 2 | 3 | 4 | install: 5 | pip install -e .[docs,test] 6 | 7 | test: 8 | py.test 9 | 10 | retest: 11 | py.test -vvv --lf 12 | 13 | coverage: 14 | py.test --cov=django_aws_xray --cov-report=term-missing --cov-report=html 15 | 16 | docs: 17 | $(MAKE) -C docs html 18 | 19 | release: 20 | rm -rf dist/* 21 | python setup.py sdist bdist_wheel 22 | twine upload dist/* 23 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. start-no-pypi 2 | 3 | .. image:: https://travis-ci.org/mvantellingen/django-aws-xray.svg?branch=master 4 | :target: https://travis-ci.org/mvantellingen/django-aws-xray 5 | 6 | .. image:: http://codecov.io/github/mvantellingen/django-aws-xray/coverage.svg?branch=master 7 | :target: http://codecov.io/github/mvantellingen/django-aws-xray?branch=master 8 | 9 | .. image:: https://img.shields.io/pypi/v/django-aws-xray.svg 10 | :target: https://pypi.python.org/pypi/django-aws-xray/ 11 | 12 | .. end-no-pypi 13 | 14 | =============== 15 | django-aws-xray 16 | =============== 17 | 18 | **N.B.**: AWS have released a beta version of their official X-Ray Python SDK which supports 19 | Django, you might want to consider using that: 20 | https://aws.amazon.com/about-aws/whats-new/2017/08/aws-x-ray-sdk-for-python-beta/ 21 | 22 | Leverage AWS X-Ray for your Django projects! This Django app instruments your code 23 | to send traces to the `X-Ray daemon`_. 24 | 25 | .. _`X-Ray daemon`: http://docs.aws.amazon.com/xray/latest/devguide/xray-daemon.html 26 | 27 | .. image:: docs/_static/aws-xray-dashboard.png 28 | 29 | 30 | Installation 31 | ============ 32 | 33 | .. code-block:: shell 34 | 35 | pip install django-aws-xray 36 | 37 | 38 | 39 | Update your Django settings: 40 | 41 | .. code-block:: python 42 | 43 | 44 | INSTALLED_APPS += [ 45 | 'django_aws_xray' 46 | ] 47 | 48 | MIDDLEWARE.insert(0, 'django_aws_xray.middleware.XRayMiddleware') 49 | 50 | # Enable various instrumentation monkeypatches 51 | AWS_XRAY_PATCHES = [ 52 | 'django_aws_xray.patches.cache', 53 | 'django_aws_xray.patches.redis', 54 | 'django_aws_xray.patches.db', 55 | 'django_aws_xray.patches.requests', 56 | 'django_aws_xray.patches.templates', 57 | ] 58 | 59 | 60 | Settings 61 | ======== 62 | 63 | ========================= ===================== ========== 64 | Setting Name Default 65 | ========================= ===================== ========== 66 | `AWS_XRAY_SAMPLING_RATE` Sampling rate 100 67 | `AWS_XRAY_EXCLUDED_PATHS` Exclude paths `[]` 68 | `AWS_XRAY_HOST` IP of X-Ray Daemon 127.0.0.1 69 | `AWS_XRAY_PORT` Port of X-Ray Daemon 2000 70 | `AWS_XRAY_PATCHES` Patches ``[]`` 71 | ========================= ===================== ========== 72 | 73 | 74 | Credits 75 | ======= 76 | The database and cache instrumention code was based on the code from django-statsd 77 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help 18 | help: 19 | @echo "Please use \`make ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " singlehtml to make a single large HTML file" 23 | @echo " pickle to make pickle files" 24 | @echo " json to make JSON files" 25 | @echo " htmlhelp to make HTML files and a HTML help project" 26 | @echo " qthelp to make HTML files and a qthelp project" 27 | @echo " applehelp to make an Apple Help Book" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " epub3 to make an epub3" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " xml to make Docutils-native XML files" 41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 42 | @echo " linkcheck to check all external links for integrity" 43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 44 | @echo " coverage to run coverage check of the documentation (if enabled)" 45 | @echo " dummy to check syntax errors of document sources" 46 | 47 | .PHONY: clean 48 | clean: 49 | rm -rf $(BUILDDIR)/* 50 | 51 | .PHONY: html 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | .PHONY: dirhtml 58 | dirhtml: 59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 60 | @echo 61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 62 | 63 | .PHONY: singlehtml 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | .PHONY: pickle 70 | pickle: 71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 72 | @echo 73 | @echo "Build finished; now you can process the pickle files." 74 | 75 | .PHONY: json 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | .PHONY: htmlhelp 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | .PHONY: qthelp 89 | qthelp: 90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 91 | @echo 92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django_aws_xray.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django_aws_xray.qhc" 97 | 98 | .PHONY: applehelp 99 | applehelp: 100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 101 | @echo 102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 103 | @echo "N.B. You won't be able to view it unless you put it in" \ 104 | "~/Library/Documentation/Help or install it in your application" \ 105 | "bundle." 106 | 107 | .PHONY: devhelp 108 | devhelp: 109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 110 | @echo 111 | @echo "Build finished." 112 | @echo "To view the help file:" 113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/django_aws_xray" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django_aws_xray" 115 | @echo "# devhelp" 116 | 117 | .PHONY: epub 118 | epub: 119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 120 | @echo 121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 122 | 123 | .PHONY: epub3 124 | epub3: 125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 126 | @echo 127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 128 | 129 | .PHONY: latex 130 | latex: 131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 132 | @echo 133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 135 | "(use \`make latexpdf' here to do that automatically)." 136 | 137 | .PHONY: latexpdf 138 | latexpdf: 139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 140 | @echo "Running LaTeX files through pdflatex..." 141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 143 | 144 | .PHONY: latexpdfja 145 | latexpdfja: 146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 147 | @echo "Running LaTeX files through platex and dvipdfmx..." 148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 150 | 151 | .PHONY: text 152 | text: 153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 154 | @echo 155 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 156 | 157 | .PHONY: man 158 | man: 159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 160 | @echo 161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 162 | 163 | .PHONY: texinfo 164 | texinfo: 165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 166 | @echo 167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 168 | @echo "Run \`make' in that directory to run these through makeinfo" \ 169 | "(use \`make info' here to do that automatically)." 170 | 171 | .PHONY: info 172 | info: 173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 174 | @echo "Running Texinfo files through makeinfo..." 175 | make -C $(BUILDDIR)/texinfo info 176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 177 | 178 | .PHONY: gettext 179 | gettext: 180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 181 | @echo 182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 183 | 184 | .PHONY: changes 185 | changes: 186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 187 | @echo 188 | @echo "The overview file is in $(BUILDDIR)/changes." 189 | 190 | .PHONY: linkcheck 191 | linkcheck: 192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 193 | @echo 194 | @echo "Link check complete; look for any errors in the above output " \ 195 | "or in $(BUILDDIR)/linkcheck/output.txt." 196 | 197 | .PHONY: doctest 198 | doctest: 199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 200 | @echo "Testing of doctests in the sources finished, look at the " \ 201 | "results in $(BUILDDIR)/doctest/output.txt." 202 | 203 | .PHONY: coverage 204 | coverage: 205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 206 | @echo "Testing of coverage in the sources finished, look at the " \ 207 | "results in $(BUILDDIR)/coverage/python.txt." 208 | 209 | .PHONY: xml 210 | xml: 211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 212 | @echo 213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 214 | 215 | .PHONY: pseudoxml 216 | pseudoxml: 217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 218 | @echo 219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 220 | 221 | .PHONY: dummy 222 | dummy: 223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 224 | @echo 225 | @echo "Build finished. Dummy builder generates no files." 226 | -------------------------------------------------------------------------------- /docs/_static/aws-xray-dashboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mvantellingen/django-aws-xray/03e43fa39fe898a14133cdf2d67a8a8eb633eacd/docs/_static/aws-xray-dashboard.png -------------------------------------------------------------------------------- /docs/_templates/sidebar-intro.html: -------------------------------------------------------------------------------- 1 |

Links

2 |

3 | 5 |

6 | 11 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # django-aws-xray documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Aug 10 17:06:14 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | # If extensions (or modules to document with autodoc) are in another directory, 16 | # add these directories to sys.path here. If the directory is relative to the 17 | # documentation root, use os.path.abspath to make it absolute, like shown here. 18 | # 19 | # import os 20 | # import sys 21 | # sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | # 27 | # needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be 30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 31 | # ones. 32 | extensions = ['sphinx.ext.autodoc'] 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ['_templates'] 36 | 37 | # The suffix(es) of source filenames. 38 | # You can specify multiple suffix as a list of string: 39 | # 40 | # source_suffix = ['.rst', '.md'] 41 | source_suffix = '.rst' 42 | 43 | # The encoding of source files. 44 | # 45 | # source_encoding = 'utf-8-sig' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # General information about the project. 51 | project = u'django-aws-xray' 52 | copyright = u'2017, Michael van Tellingen' 53 | author = u'Michael van Tellingen' 54 | 55 | # The version info for the project you're documenting, acts as replacement for 56 | # |version| and |release|, also used in various other places throughout the 57 | # built documents. 58 | # 59 | version = '0.2.2' 60 | release = version 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | # 65 | # This is also used if you do content translation via gettext catalogs. 66 | # Usually you set "language" from the command line for these cases. 67 | language = None 68 | 69 | # There are two options for replacing |today|: either, you set today to some 70 | # non-false value, then it is used: 71 | # 72 | # today = '' 73 | # 74 | # Else, today_fmt is used as the format for a strftime call. 75 | # 76 | # today_fmt = '%B %d, %Y' 77 | 78 | # List of patterns, relative to source directory, that match files and 79 | # directories to ignore when looking for source files. 80 | # This patterns also effect to html_static_path and html_extra_path 81 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 82 | 83 | # The reST default role (used for this markup: `text`) to use for all 84 | # documents. 85 | # 86 | # default_role = None 87 | 88 | # If true, '()' will be appended to :func: etc. cross-reference text. 89 | # 90 | # add_function_parentheses = True 91 | 92 | # If true, the current module name will be prepended to all description 93 | # unit titles (such as .. function::). 94 | # 95 | # add_module_names = True 96 | 97 | # If true, sectionauthor and moduleauthor directives will be shown in the 98 | # output. They are ignored by default. 99 | # 100 | # show_authors = False 101 | 102 | # The name of the Pygments (syntax highlighting) style to use. 103 | pygments_style = 'sphinx' 104 | 105 | # A list of ignored prefixes for module index sorting. 106 | # modindex_common_prefix = [] 107 | 108 | # If true, keep warnings as "system message" paragraphs in the built documents. 109 | # keep_warnings = False 110 | 111 | # If true, `todo` and `todoList` produce output, else they produce nothing. 112 | todo_include_todos = False 113 | 114 | 115 | # -- Options for HTML output ---------------------------------------------- 116 | 117 | # The theme to use for HTML and HTML Help pages. See the documentation for 118 | # a list of builtin themes. 119 | # 120 | html_theme = 'alabaster' 121 | 122 | # Theme options are theme-specific and customize the look and feel of a theme 123 | # further. For a list of options available for each theme, see the 124 | # documentation. 125 | # 126 | # html_theme_options = {} 127 | html_theme_options = { 128 | 'github_user': 'mvantellingen', 129 | 'github_banner': True, 130 | 'github_repo': 'django-aws-xray', 131 | 'travis_button': True, 132 | 'codecov_button': True, 133 | 'analytics_id': 'UA-75907833-X', 134 | } 135 | 136 | # Add any paths that contain custom themes here, relative to this directory. 137 | # html_theme_path = [] 138 | 139 | # The name for this set of Sphinx documents. 140 | # " v documentation" by default. 141 | # 142 | # html_title = u'django-aws-xray v0.0.1' 143 | 144 | # A shorter title for the navigation bar. Default is the same as html_title. 145 | # 146 | # html_short_title = None 147 | 148 | # The name of an image file (relative to this directory) to place at the top 149 | # of the sidebar. 150 | # 151 | # html_logo = None 152 | 153 | # The name of an image file (relative to this directory) to use as a favicon of 154 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 155 | # pixels large. 156 | # 157 | # html_favicon = None 158 | 159 | # Add any paths that contain custom static files (such as style sheets) here, 160 | # relative to this directory. They are copied after the builtin static files, 161 | # so a file named "default.css" will overwrite the builtin "default.css". 162 | html_static_path = ['_static'] 163 | 164 | # Add any extra paths that contain custom files (such as robots.txt or 165 | # .htaccess) here, relative to this directory. These files are copied 166 | # directly to the root of the documentation. 167 | # 168 | # html_extra_path = [] 169 | 170 | # If not None, a 'Last updated on:' timestamp is inserted at every page 171 | # bottom, using the given strftime format. 172 | # The empty string is equivalent to '%b %d, %Y'. 173 | # 174 | # html_last_updated_fmt = None 175 | 176 | # If true, SmartyPants will be used to convert quotes and dashes to 177 | # typographically correct entities. 178 | # 179 | # html_use_smartypants = True 180 | 181 | # Custom sidebar templates, maps document names to template names. 182 | # 183 | # html_sidebars = {} 184 | # Custom sidebar templates, maps document names to template names. 185 | html_sidebars = { 186 | '*': [ 187 | 'sidebar-intro.html', 188 | ] 189 | } 190 | 191 | 192 | # Additional templates that should be rendered to pages, maps page names to 193 | # template names. 194 | # 195 | # html_additional_pages = {} 196 | 197 | # If false, no module index is generated. 198 | # 199 | # html_domain_indices = True 200 | 201 | # If false, no index is generated. 202 | # 203 | # html_use_index = True 204 | 205 | # If true, the index is split into individual pages for each letter. 206 | # 207 | # html_split_index = False 208 | 209 | # If true, links to the reST sources are added to the pages. 210 | # 211 | # html_show_sourcelink = True 212 | 213 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 214 | # 215 | # html_show_sphinx = True 216 | 217 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 218 | # 219 | # html_show_copyright = True 220 | 221 | # If true, an OpenSearch description file will be output, and all pages will 222 | # contain a tag referring to it. The value of this option must be the 223 | # base URL from which the finished HTML is served. 224 | # 225 | # html_use_opensearch = '' 226 | 227 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 228 | # html_file_suffix = None 229 | 230 | # Language to be used for generating the HTML full-text search index. 231 | # Sphinx supports the following languages: 232 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 233 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' 234 | # 235 | # html_search_language = 'en' 236 | 237 | # A dictionary with options for the search language support, empty by default. 238 | # 'ja' uses this config value. 239 | # 'zh' user can custom change `jieba` dictionary path. 240 | # 241 | # html_search_options = {'type': 'default'} 242 | 243 | # The name of a javascript file (relative to the configuration directory) that 244 | # implements a search results scorer. If empty, the default will be used. 245 | # 246 | # html_search_scorer = 'scorer.js' 247 | 248 | # Output file base name for HTML help builder. 249 | htmlhelp_basename = 'django-aws-xray-doc' 250 | 251 | # -- Options for LaTeX output --------------------------------------------- 252 | 253 | latex_elements = { 254 | # The paper size ('letterpaper' or 'a4paper'). 255 | # 256 | # 'papersize': 'letterpaper', 257 | 258 | # The font size ('10pt', '11pt' or '12pt'). 259 | # 260 | # 'pointsize': '10pt', 261 | 262 | # Additional stuff for the LaTeX preamble. 263 | # 264 | # 'preamble': '', 265 | 266 | # Latex figure (float) alignment 267 | # 268 | # 'figure_align': 'htbp', 269 | } 270 | 271 | # Grouping the document tree into LaTeX files. List of tuples 272 | # (source start file, target name, title, 273 | # author, documentclass [howto, manual, or own class]). 274 | latex_documents = [ 275 | (master_doc, 'django-aws-xray.tex', u'django-aws-xray Documentation', 276 | u'Michael van Tellingen', 'manual'), 277 | ] 278 | 279 | # The name of an image file (relative to this directory) to place at the top of 280 | # the title page. 281 | # 282 | # latex_logo = None 283 | 284 | # For "manual" documents, if this is true, then toplevel headings are parts, 285 | # not chapters. 286 | # 287 | # latex_use_parts = False 288 | 289 | # If true, show page references after internal links. 290 | # 291 | # latex_show_pagerefs = False 292 | 293 | # If true, show URL addresses after external links. 294 | # 295 | # latex_show_urls = False 296 | 297 | # Documents to append as an appendix to all manuals. 298 | # 299 | # latex_appendices = [] 300 | 301 | # It false, will not define \strong, \code, itleref, \crossref ... but only 302 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added 303 | # packages. 304 | # 305 | # latex_keep_old_macro_names = True 306 | 307 | # If false, no module index is generated. 308 | # 309 | # latex_domain_indices = True 310 | 311 | 312 | # -- Options for manual page output --------------------------------------- 313 | 314 | # One entry per manual page. List of tuples 315 | # (source start file, name, description, authors, manual section). 316 | man_pages = [ 317 | (master_doc, 'django-aws-xray', u'django-aws-xray Documentation', 318 | [author], 1) 319 | ] 320 | 321 | # If true, show URL addresses after external links. 322 | # 323 | # man_show_urls = False 324 | 325 | 326 | # -- Options for Texinfo output ------------------------------------------- 327 | 328 | # Grouping the document tree into Texinfo files. List of tuples 329 | # (source start file, target name, title, author, 330 | # dir menu entry, description, category) 331 | texinfo_documents = [ 332 | (master_doc, 'django-aws-xray', u'django-aws-xray Documentation', 333 | author, 'django-aws-xray', 'One line description of project.', 334 | 'Miscellaneous'), 335 | ] 336 | 337 | # Documents to append as an appendix to all manuals. 338 | # 339 | # texinfo_appendices = [] 340 | 341 | # If false, no module index is generated. 342 | # 343 | # texinfo_domain_indices = True 344 | 345 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 346 | # 347 | # texinfo_show_urls = 'footnote' 348 | 349 | # If true, do not generate a @detailmenu in the "Top" node's menu. 350 | # 351 | # texinfo_no_detailmenu = False 352 | 353 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | =================== 2 | django-xray 3 | =================== 4 | 5 | 6 | Installation 7 | ============ 8 | 9 | .. code-block:: shell 10 | 11 | pip install django_aws_xray 12 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. epub3 to make an epub3 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. xml to make Docutils-native XML files 38 | echo. pseudoxml to make pseudoxml-XML files for display purposes 39 | echo. linkcheck to check all external links for integrity 40 | echo. doctest to run all doctests embedded in the documentation if enabled 41 | echo. coverage to run coverage check of the documentation if enabled 42 | echo. dummy to check syntax errors of document sources 43 | goto end 44 | ) 45 | 46 | if "%1" == "clean" ( 47 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 48 | del /q /s %BUILDDIR%\* 49 | goto end 50 | ) 51 | 52 | 53 | REM Check if sphinx-build is available and fallback to Python version if any 54 | %SPHINXBUILD% 1>NUL 2>NUL 55 | if errorlevel 9009 goto sphinx_python 56 | goto sphinx_ok 57 | 58 | :sphinx_python 59 | 60 | set SPHINXBUILD=python -m sphinx.__init__ 61 | %SPHINXBUILD% 2> nul 62 | if errorlevel 9009 ( 63 | echo. 64 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 65 | echo.installed, then set the SPHINXBUILD environment variable to point 66 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 67 | echo.may add the Sphinx directory to PATH. 68 | echo. 69 | echo.If you don't have Sphinx installed, grab it from 70 | echo.http://sphinx-doc.org/ 71 | exit /b 1 72 | ) 73 | 74 | :sphinx_ok 75 | 76 | 77 | if "%1" == "html" ( 78 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 79 | if errorlevel 1 exit /b 1 80 | echo. 81 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 82 | goto end 83 | ) 84 | 85 | if "%1" == "dirhtml" ( 86 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 87 | if errorlevel 1 exit /b 1 88 | echo. 89 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 90 | goto end 91 | ) 92 | 93 | if "%1" == "singlehtml" ( 94 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 95 | if errorlevel 1 exit /b 1 96 | echo. 97 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 98 | goto end 99 | ) 100 | 101 | if "%1" == "pickle" ( 102 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 103 | if errorlevel 1 exit /b 1 104 | echo. 105 | echo.Build finished; now you can process the pickle files. 106 | goto end 107 | ) 108 | 109 | if "%1" == "json" ( 110 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 111 | if errorlevel 1 exit /b 1 112 | echo. 113 | echo.Build finished; now you can process the JSON files. 114 | goto end 115 | ) 116 | 117 | if "%1" == "htmlhelp" ( 118 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 119 | if errorlevel 1 exit /b 1 120 | echo. 121 | echo.Build finished; now you can run HTML Help Workshop with the ^ 122 | .hhp project file in %BUILDDIR%/htmlhelp. 123 | goto end 124 | ) 125 | 126 | if "%1" == "qthelp" ( 127 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 128 | if errorlevel 1 exit /b 1 129 | echo. 130 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 131 | .qhcp project file in %BUILDDIR%/qthelp, like this: 132 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django_aws_xray.qhcp 133 | echo.To view the help file: 134 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django_aws_xray.ghc 135 | goto end 136 | ) 137 | 138 | if "%1" == "devhelp" ( 139 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 140 | if errorlevel 1 exit /b 1 141 | echo. 142 | echo.Build finished. 143 | goto end 144 | ) 145 | 146 | if "%1" == "epub" ( 147 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 148 | if errorlevel 1 exit /b 1 149 | echo. 150 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 151 | goto end 152 | ) 153 | 154 | if "%1" == "epub3" ( 155 | %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 156 | if errorlevel 1 exit /b 1 157 | echo. 158 | echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. 159 | goto end 160 | ) 161 | 162 | if "%1" == "latex" ( 163 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 164 | if errorlevel 1 exit /b 1 165 | echo. 166 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdf" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "latexpdfja" ( 181 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 182 | cd %BUILDDIR%/latex 183 | make all-pdf-ja 184 | cd %~dp0 185 | echo. 186 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 187 | goto end 188 | ) 189 | 190 | if "%1" == "text" ( 191 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 192 | if errorlevel 1 exit /b 1 193 | echo. 194 | echo.Build finished. The text files are in %BUILDDIR%/text. 195 | goto end 196 | ) 197 | 198 | if "%1" == "man" ( 199 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 200 | if errorlevel 1 exit /b 1 201 | echo. 202 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 203 | goto end 204 | ) 205 | 206 | if "%1" == "texinfo" ( 207 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 208 | if errorlevel 1 exit /b 1 209 | echo. 210 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 211 | goto end 212 | ) 213 | 214 | if "%1" == "gettext" ( 215 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 216 | if errorlevel 1 exit /b 1 217 | echo. 218 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 219 | goto end 220 | ) 221 | 222 | if "%1" == "changes" ( 223 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 224 | if errorlevel 1 exit /b 1 225 | echo. 226 | echo.The overview file is in %BUILDDIR%/changes. 227 | goto end 228 | ) 229 | 230 | if "%1" == "linkcheck" ( 231 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 232 | if errorlevel 1 exit /b 1 233 | echo. 234 | echo.Link check complete; look for any errors in the above output ^ 235 | or in %BUILDDIR%/linkcheck/output.txt. 236 | goto end 237 | ) 238 | 239 | if "%1" == "doctest" ( 240 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 241 | if errorlevel 1 exit /b 1 242 | echo. 243 | echo.Testing of doctests in the sources finished, look at the ^ 244 | results in %BUILDDIR%/doctest/output.txt. 245 | goto end 246 | ) 247 | 248 | if "%1" == "coverage" ( 249 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 250 | if errorlevel 1 exit /b 1 251 | echo. 252 | echo.Testing of coverage in the sources finished, look at the ^ 253 | results in %BUILDDIR%/coverage/python.txt. 254 | goto end 255 | ) 256 | 257 | if "%1" == "xml" ( 258 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 259 | if errorlevel 1 exit /b 1 260 | echo. 261 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 262 | goto end 263 | ) 264 | 265 | if "%1" == "pseudoxml" ( 266 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 267 | if errorlevel 1 exit /b 1 268 | echo. 269 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 270 | goto end 271 | ) 272 | 273 | if "%1" == "dummy" ( 274 | %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy 275 | if errorlevel 1 exit /b 1 276 | echo. 277 | echo.Build finished. Dummy builder generates no files. 278 | goto end 279 | ) 280 | 281 | :end 282 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | -e .[docs] 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.2.2 3 | commit = true 4 | tag = true 5 | tag_name = {new_version} 6 | 7 | [tool:pytest] 8 | minversion = 3.0 9 | strict = true 10 | testpaths = tests 11 | 12 | [wheel] 13 | universal = 1 14 | 15 | [flake8] 16 | max-line-length = 99 17 | 18 | [bumpversion:file:setup.py] 19 | 20 | [bumpversion:file:docs/conf.py] 21 | 22 | [bumpversion:file:src/django_aws_xray/__init__.py] 23 | 24 | [coverage:run] 25 | branch = True 26 | source = 27 | django_aws_xray 28 | 29 | [coverage:paths] 30 | source = 31 | src/django_aws_xray 32 | .tox/*/lib/python*/site-packages/django_aws_xray 33 | .tox/pypy*/site-packages/django_aws_xray 34 | 35 | [coverage:report] 36 | show_missing = True 37 | 38 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import re 2 | from setuptools import find_packages, setup 3 | 4 | install_requires = [ 5 | 'attrs>=17.2.0', 6 | 'Django>=1.8', 7 | 'six>=1.1', 8 | 'wrapt>=1.10.10,<2', 9 | ] 10 | 11 | docs_require = [ 12 | 'sphinx>=1.4.0', 13 | ] 14 | 15 | tests_require = [ 16 | 'bumpversion==0.5.3', 17 | 'coverage==.4.2', 18 | 'pytest==3.0.5', 19 | 'pytest-cov==2.5.1', 20 | 'pytest-django==3.1.2', 21 | 22 | # Linting 23 | 'isort==4.2.5', 24 | 'flake8==3.0.3', 25 | 'flake8-blind-except==0.1.1', 26 | 'flake8-debugger==1.4.0', 27 | ] 28 | 29 | with open('README.rst') as fh: 30 | long_description = re.sub( 31 | '^.. start-no-pypi.*^.. end-no-pypi', '', fh.read(), flags=re.M | re.S) 32 | 33 | 34 | setup( 35 | name='django-aws-xray', 36 | version='0.2.2', 37 | description="Django AWS X-Ray", 38 | long_description=long_description, 39 | url='https://github.com/mvantellingen/django-aws-xray', 40 | author="Michael van Tellingen", 41 | author_email="", 42 | install_requires=install_requires, 43 | tests_require=tests_require, 44 | extras_require={ 45 | 'docs': docs_require, 46 | 'test': tests_require, 47 | }, 48 | use_scm_version=True, 49 | entry_points={}, 50 | package_dir={'': 'src'}, 51 | packages=find_packages('src'), 52 | include_package_data=True, 53 | license='MIT', 54 | classifiers=[ 55 | 'Development Status :: 5 - Production/Stable', 56 | 'Environment :: Web Environment', 57 | 'Framework :: Django', 58 | 'Framework :: Django :: 1.11', 59 | 'License :: OSI Approved :: MIT License', 60 | 'Programming Language :: Python', 61 | 'Programming Language :: Python :: 3', 62 | 'Programming Language :: Python :: 3.4', 63 | 'Programming Language :: Python :: 3.5', 64 | 'Programming Language :: Python :: 3.6', 65 | ], 66 | zip_safe=False, 67 | ) 68 | -------------------------------------------------------------------------------- /src/django_aws_xray/__init__.py: -------------------------------------------------------------------------------- 1 | default_app_config = 'django_aws_xray.apps.DjangoXRayConfig' 2 | __version__ = '0.2.2' 3 | -------------------------------------------------------------------------------- /src/django_aws_xray/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class DjangoXRayConfig(AppConfig): 5 | name = 'django_aws_xray' 6 | verbose_name = "Django AWS X-Ray" 7 | 8 | def ready(self): 9 | from . import patches # noqa 10 | -------------------------------------------------------------------------------- /src/django_aws_xray/connection.py: -------------------------------------------------------------------------------- 1 | import json 2 | import socket 3 | 4 | from django.conf import settings 5 | 6 | 7 | class Connection: 8 | 9 | def __init__(self): 10 | self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 11 | 12 | hostname = getattr(settings, 'AWS_XRAY_HOST', '127.0.0.1') 13 | port = getattr(settings, 'AWS_XRAY_PORT', 2000) 14 | self._address = (hostname, port) 15 | 16 | def serialize(self, msg): 17 | data = '\n'.join([ 18 | json.dumps({'format': 'json', 'version': 1}), 19 | json.dumps(msg.serialize()) 20 | ]) 21 | return data.encode('utf-8') 22 | 23 | def send(self, record): 24 | if not record: 25 | return 26 | 27 | data = self.serialize(record) 28 | self._socket.sendto(data, self._address) 29 | -------------------------------------------------------------------------------- /src/django_aws_xray/middleware.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import random 3 | import time 4 | 5 | from django.conf import settings 6 | 7 | from django_aws_xray import records, xray 8 | 9 | 10 | class XRayMiddleware: 11 | def __init__(self, get_response): 12 | self.get_response = get_response 13 | self.sampling_rate = getattr(settings, 'AWS_XRAY_SAMPLING_RATE', 100) 14 | self.exclude_paths = getattr(settings, 'AWS_XRAY_EXCLUDE_PATHS', []) 15 | self.logger = logging.getLogger(__name__) 16 | 17 | def __call__(self, request): 18 | trace = self._create_trace(request) 19 | 20 | # Set the thread local trace object 21 | xray.set_current_trace(trace) 22 | 23 | with trace.track('django.request') as record: 24 | response = self.get_response(request) 25 | record.http = self._create_http_record(request, response) 26 | 27 | # Send out the traces 28 | trace.send() 29 | 30 | # Set the HTTP header 31 | response['X-Amzn-Trace-Id'] = trace.http_header 32 | 33 | # Cleanup the thread local trace object 34 | xray.set_current_trace(None) 35 | 36 | return response 37 | 38 | def _create_trace(self, request): 39 | # Decide if we need to sample this request 40 | sampled = random.randint(0, 100) <= self.sampling_rate 41 | for path in self.exclude_paths: 42 | if request.path.startswith(path): 43 | sampled = False 44 | 45 | trace_header = request.META.get('HTTP_X_AMZN_TRACE_ID') 46 | if trace_header: 47 | trace = xray.Trace.from_http_header(trace_header, sampled) 48 | else: 49 | trace = xray.Trace.generate_new(sampled) 50 | 51 | return trace 52 | 53 | def _create_http_record(self, request, response): 54 | return records.HttpRecord( 55 | request_method=request.method, 56 | request_url=request.get_full_path(), 57 | request_user_agent=request.META.get('User-Agent'), 58 | response_status_code=response.status_code) 59 | -------------------------------------------------------------------------------- /src/django_aws_xray/patches/__init__.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | try: 4 | from importlib import import_module 5 | except ImportError: 6 | from django.utils.importlib import import_module 7 | 8 | patches = getattr(settings, 'AWS_XRAY_PATCHES', []) 9 | 10 | print(patches) 11 | 12 | for patch in patches: 13 | import_module(patch).patch() 14 | -------------------------------------------------------------------------------- /src/django_aws_xray/patches/cache.py: -------------------------------------------------------------------------------- 1 | import wrapt 2 | from django.core import cache 3 | from django.core.cache.backends.base import BaseCache 4 | 5 | from django_aws_xray.patches.utils import wrap 6 | 7 | 8 | def key(cache, attr): 9 | return 'cache.%s.%s' % (cache.__module__.split('.')[-1], attr) 10 | 11 | 12 | class XRayTracker(BaseCache): 13 | 14 | def __init__(self, cache): 15 | self.cache = cache 16 | 17 | def __getattribute__(self, attr): 18 | if attr == 'cache': 19 | return BaseCache.__getattribute__(self, attr) 20 | 21 | return wrap(getattr(self.cache, attr), key(self.cache, attr)) 22 | 23 | 24 | def patch(): 25 | cache.cache = XRayTracker(cache.cache) 26 | -------------------------------------------------------------------------------- /src/django_aws_xray/patches/db.py: -------------------------------------------------------------------------------- 1 | import wrapt 2 | 3 | from django_aws_xray.traces import trace_sql 4 | 5 | 6 | def key(db, attr): 7 | return 'db.%s.%s.%s' % (db.client.executable_name, db.alias, attr) 8 | 9 | 10 | def _get_query_type(query): 11 | return (query.split(None, 1) or ['__empty__'])[0].lower() 12 | 13 | 14 | def patched_execute(func, instance, args, kwargs): 15 | query = args[0] 16 | name = key(instance.db, 'execute.%s' % _get_query_type(query)) 17 | with trace_sql(name, instance.db, query): 18 | return func(*args, **kwargs) 19 | 20 | 21 | def patched_executemany(func, instance, args, kwargs): 22 | query = args[0] 23 | name = key(instance.db, 'executemany.%s' % _get_query_type(query)) 24 | with trace_sql(name, instance.db, query): 25 | return func(*args, **kwargs) 26 | 27 | 28 | def patched_callproc(func, instance, args, kwargs): 29 | query = args[0] 30 | name = key(instance.db, 'callproc.%s' % _get_query_type(query)) 31 | with trace_sql(name, instance.db, query): 32 | return func(*args, **kwargs) 33 | 34 | 35 | def patch(): 36 | wrapt.wrap_function_wrapper( 37 | 'django.db.backends.utils', 'CursorWrapper.execute', patched_execute) 38 | wrapt.wrap_function_wrapper( 39 | 'django.db.backends.utils', 'CursorWrapper.executemany', patched_executemany) 40 | wrapt.wrap_function_wrapper( 41 | 'django.db.backends.utils', 'CursorWrapper.callproc', patched_callproc) 42 | -------------------------------------------------------------------------------- /src/django_aws_xray/patches/redis.py: -------------------------------------------------------------------------------- 1 | import wrapt 2 | 3 | from django_aws_xray.traces import trace_http 4 | 5 | 6 | def patched_execute_command(func, instance, args, kwargs): 7 | 8 | # TODO: Metadata / Annotations 9 | # instance.connection_pool.connection_kwargs['host'] 10 | # instance.connection_pool.connection_kwargs['db'] 11 | 12 | command = args[0] 13 | key = None 14 | if command in ('GET', 'SET', 'DELETE', 'INCR', 'DECR'): 15 | key = str(args[1]) 16 | 17 | with trace_http('redis', command, key): 18 | response = func(*args, **kwargs) 19 | return response 20 | 21 | 22 | def patch(): 23 | """ Monkeypatch the requests library to trace http calls. """ 24 | try: 25 | wrapt.wrap_function_wrapper( 26 | 'redis.client', 'Redis.execute_command', patched_execute_command) 27 | wrapt.wrap_function_wrapper( 28 | 'redis.client', 'StrictRedis.execute_command', patched_execute_command) 29 | except ModuleNotFoundError: 30 | pass 31 | -------------------------------------------------------------------------------- /src/django_aws_xray/patches/requests.py: -------------------------------------------------------------------------------- 1 | import wrapt 2 | 3 | from django_aws_xray.traces import trace_http 4 | 5 | 6 | def patched_request(func, instance, args, kwargs): 7 | method = kwargs.get('method') or args[0] 8 | url = kwargs.get('url') or args[1] 9 | name = 'requests.request' 10 | 11 | with trace_http(name, method, url) as trace: 12 | response = func(*args, **kwargs) 13 | trace.response_status_code = response.status_code 14 | return response 15 | 16 | 17 | def patch(): 18 | """ Monkeypatch the requests library to trace http calls. """ 19 | wrapt.wrap_function_wrapper('requests', 'Session.request', patched_request) 20 | -------------------------------------------------------------------------------- /src/django_aws_xray/patches/templates.py: -------------------------------------------------------------------------------- 1 | import wrapt 2 | 3 | from django_aws_xray.traces import trace_http 4 | 5 | 6 | def patched_render(func, instance, args, kwargs): 7 | name = 'django.template' 8 | 9 | with trace_http(name, 'render', instance.name): 10 | return func(*args, **kwargs) 11 | 12 | 13 | def patch(): 14 | wrapt.wrap_function_wrapper( 15 | 'django.template', 'Template.render', patched_render) 16 | -------------------------------------------------------------------------------- /src/django_aws_xray/patches/utils.py: -------------------------------------------------------------------------------- 1 | from functools import partial, wraps 2 | 3 | from django_aws_xray import traces 4 | 5 | 6 | def patch_method(target, name, external_decorator=None): 7 | 8 | def decorator(patch_function): 9 | original_function = getattr(target, name) 10 | 11 | @wraps(patch_function) 12 | def wrapper(*args, **kw): 13 | return patch_function(original_function, *args, **kw) 14 | 15 | setattr(target, name, wrapper) 16 | return wrapper 17 | 18 | return decorator 19 | 20 | 21 | def wrapped(method, key, *args, **kw): 22 | with traces.trace(key): 23 | return method(*args, **kw) 24 | 25 | 26 | def wrap(method, key, *args, **kw): 27 | return partial(wrapped, method, key, *args, **kw) 28 | -------------------------------------------------------------------------------- /src/django_aws_xray/records.py: -------------------------------------------------------------------------------- 1 | import uuid 2 | 3 | import attr 4 | 5 | from django_aws_xray.connection import Connection 6 | 7 | 8 | @attr.s 9 | class SegmentRecord: 10 | id = attr.ib(init=False, default=attr.Factory(lambda: uuid.uuid4().hex[16:])) 11 | name = attr.ib() 12 | trace_id = attr.ib(default=None) 13 | start_time = attr.ib(default=None) 14 | end_time = attr.ib(default=None) 15 | http = attr.ib(default=None) 16 | subsegments = attr.ib(default=attr.Factory(list)) 17 | 18 | def serialize(self): 19 | data = { 20 | 'name': self.name, 21 | 'id': self.id, 22 | 'start_time': self.start_time, 23 | 'trace_id': self.trace_id, 24 | 'end_time': self.end_time, 25 | } 26 | 27 | if self.http: 28 | data['http'] = self.http.serialize() 29 | 30 | return data 31 | 32 | 33 | @attr.s 34 | class SubSegmentRecord: 35 | id = attr.ib(init=False, default=attr.Factory(lambda: uuid.uuid4().hex[16:])) 36 | name = attr.ib() 37 | start_time = attr.ib(default=None) 38 | end_time = attr.ib(default=None) 39 | trace_id = attr.ib(default=None) 40 | parent_id = attr.ib(default=None) 41 | namespace = attr.ib(default='remote') 42 | subsegments = attr.ib(default=attr.Factory(list)) 43 | http = attr.ib(default=None) 44 | sql = attr.ib(default=None) 45 | 46 | def serialize(self): 47 | data = { 48 | 'name': self.name, 49 | 'id': self.id, 50 | 'start_time': self.start_time, 51 | 'end_time': self.end_time, 52 | 'type': 'subsegment', 53 | 'trace_id': self.trace_id, 54 | 'parent_id': self.parent_id, 55 | 'namespace': self.namespace, 56 | } 57 | 58 | if self.http: 59 | data['http'] = self.http.serialize() 60 | 61 | if self.sql: 62 | data['sql'] = self.sql.serialize() 63 | 64 | return data 65 | 66 | 67 | @attr.s 68 | class HttpRecord: 69 | request_method = attr.ib(default=None) 70 | request_url = attr.ib(default=None) 71 | request_user_agent = attr.ib(default=None) 72 | 73 | response_status_code = attr.ib(default=None) 74 | 75 | def serialize(self): 76 | return { 77 | 'request': { 78 | 'method': self.request_method, 79 | 'url': self.request_url, 80 | 'user_agent': self.request_user_agent, 81 | }, 82 | 'response': { 83 | 'status': self.response_status_code 84 | } 85 | } 86 | 87 | 88 | @attr.s 89 | class SqlRecord: 90 | sanitized_query = attr.ib() 91 | database_type = attr.ib() 92 | 93 | def serialize(self): 94 | return { 95 | 'sanitized_query': self.sanitized_query, 96 | 'database_type': self.database_type, 97 | } 98 | -------------------------------------------------------------------------------- /src/django_aws_xray/traces.py: -------------------------------------------------------------------------------- 1 | from contextlib import contextmanager 2 | 3 | from django_aws_xray import records, xray 4 | 5 | MAX_SQL_QUERY_LENGTH = 8192 6 | 7 | 8 | @contextmanager 9 | def trace(name): 10 | trace = xray.get_current_trace() 11 | if trace: 12 | with trace.track(name): 13 | yield 14 | else: 15 | yield 16 | 17 | 18 | @contextmanager 19 | def trace_sql(name, db, query): 20 | sql_record = records.SqlRecord( 21 | sanitized_query=query.strip()[:MAX_SQL_QUERY_LENGTH], 22 | database_type=db.vendor) 23 | 24 | trace = xray.get_current_trace() 25 | if trace: 26 | with trace.track(name) as record: 27 | record.sql = sql_record 28 | yield sql_record 29 | else: 30 | yield sql_record 31 | 32 | 33 | @contextmanager 34 | def trace_http(name, method, url): 35 | http_record = records.HttpRecord( 36 | request_method=method, 37 | request_url=url) 38 | 39 | trace = xray.get_current_trace() 40 | if trace: 41 | with trace.track(name) as record: 42 | record.http = http_record 43 | yield http_record 44 | else: 45 | yield http_record 46 | -------------------------------------------------------------------------------- /src/django_aws_xray/xray.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import time 3 | import uuid 4 | from contextlib import contextmanager 5 | 6 | from django_aws_xray import records 7 | from django_aws_xray.connection import Connection 8 | 9 | tls = threading.local() 10 | tls.trace_id = None 11 | tls.current_trace = None 12 | 13 | 14 | def set_current_trace(trace): 15 | tls.current_trace = trace 16 | 17 | 18 | def get_current_trace(): 19 | return getattr(tls, 'current_trace', None) 20 | 21 | 22 | class Trace: 23 | 24 | def __init__(self, root, parent=None, sampled=None): 25 | self.root = root 26 | self.parent = parent 27 | self.sampled = sampled 28 | self._connection = Connection() 29 | self._segment_stack = list() 30 | self._segment_buffer = list() 31 | 32 | def send(self): 33 | if self.sampled: 34 | for record in self._segment_buffer: 35 | self._connection.send(record) 36 | self._segment_buffer.clear() 37 | 38 | @property 39 | def http_header(self): 40 | parts = [ 41 | ('Root', self.root), 42 | ('Parent', self.parent), 43 | ('Sampled', '1' if self.sampled else None), 44 | ] 45 | return ';'.join('%s=%s' % (k, v) for k, v in parts if v is not None) 46 | 47 | @contextmanager 48 | def track(self, name): 49 | # Create the correct record type 50 | if len(self._segment_stack) == 0: 51 | record = records.SegmentRecord( 52 | name=name, 53 | trace_id=self.root) 54 | else: 55 | parent = self._segment_stack[-1] 56 | record = records.SubSegmentRecord( 57 | name=name, 58 | trace_id=self.root, 59 | parent_id=parent.id) 60 | 61 | # Push the record on our stack 62 | self._segment_stack.append(record) 63 | 64 | record.trace_id = self.root 65 | record.start_time = time.time() 66 | try: 67 | yield record 68 | finally: 69 | assert self._segment_stack.pop() is record 70 | record.end_time = time.time() 71 | self._segment_buffer.append(record) 72 | 73 | @classmethod 74 | def generate_new(cls, sampled=True): 75 | root = '1-%08x-%s' % (int(time.time()), uuid.uuid4().hex[:24]) 76 | return cls(root=root, parent=None, sampled=sampled) 77 | 78 | @classmethod 79 | def from_http_header(cls, header_value, sampled): 80 | """ 81 | 82 | Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1 83 | 84 | """ 85 | parts = header_value.lower().split(';') 86 | data = { 87 | 'sampled': '1' if sampled else '0' 88 | } 89 | 90 | for part in parts: 91 | subparts = part.split('=', 1) 92 | if len(subparts) == 2: 93 | data[subparts[0]] = subparts[1] 94 | 95 | root = data.get('root') 96 | parent = data.get('parent') 97 | sampled = data.get('sampled') == '1' 98 | return cls(root=root, parent=parent, sampled=sampled) 99 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mvantellingen/django-aws-xray/03e43fa39fe898a14133cdf2d67a8a8eb633eacd/tests/__init__.py -------------------------------------------------------------------------------- /tests/app/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from tests.app import views 4 | 5 | 6 | urlpatterns = [ 7 | url(r'', views.dummy_view) 8 | ] 9 | -------------------------------------------------------------------------------- /tests/app/views.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponse 2 | 3 | 4 | def dummy_view(request): 5 | return HttpResponse('hello world') 6 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import json 2 | import attr 3 | import socket 4 | import threading 5 | import pytest 6 | import select 7 | import queue 8 | 9 | from django.conf import settings 10 | 11 | 12 | def pytest_configure(): 13 | settings.configure( 14 | MIDDLEWARE=[ 15 | 'django_aws_xray.middleware.XRayMiddleware' 16 | ], 17 | INSTALLED_APPS=[ 18 | 'django_aws_xray', 19 | 'tests.app', 20 | ], 21 | CACHES={ 22 | 'default': { 23 | 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 24 | 'LOCATION': 'unique-snowflake', 25 | } 26 | }, 27 | DATABASES={ 28 | 'default': { 29 | 'ENGINE': 'django.db.backends.sqlite3', 30 | 'NAME': 'db.sqlite', 31 | }, 32 | }, 33 | ROOT_URLCONF='tests.app.urls', 34 | AWS_XRAY_HOST='127.0.0.1', 35 | AWS_XRAY_PORT=2399, 36 | ) 37 | 38 | 39 | @attr.s 40 | class XRayDaemon: 41 | messages = attr.ib(default=attr.Factory(queue.Queue)) 42 | 43 | def get_new_messages(self): 44 | result = [] 45 | while True: 46 | try: 47 | data = self.messages.get(block=True, timeout=0.200) 48 | except queue.Empty: 49 | break 50 | 51 | header, body = data.split(b'\n', 1) 52 | header = json.loads(header) 53 | body = json.loads(body) 54 | 55 | assert header == { 56 | 'format': 'json', 57 | 'version': 1 58 | } 59 | result.append(body) 60 | return result 61 | 62 | 63 | @pytest.fixture 64 | def xray_daemon(): 65 | address = ('127.0.0.1', 2399) 66 | 67 | is_completed = threading.Event() 68 | is_running = threading.Event() 69 | daemon = XRayDaemon() 70 | 71 | def run(): 72 | sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 73 | sock.bind(address) 74 | 75 | while True: 76 | is_running.set() 77 | ready = select.select([sock], [], [], 0.100) 78 | if ready[0]: 79 | data, addr = sock.recvfrom(64 * 1024) 80 | daemon.messages.put(data) 81 | 82 | if is_completed.is_set(): 83 | break 84 | 85 | thread = threading.Thread(target=run) 86 | thread.start() 87 | 88 | if is_running.wait(): 89 | yield daemon 90 | 91 | is_completed.set() 92 | thread.join() 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /tests/test_connection.py: -------------------------------------------------------------------------------- 1 | import time 2 | from django_aws_xray import connection, records 3 | 4 | 5 | def test_send(xray_daemon): 6 | 7 | record = records.SegmentRecord( 8 | name='test', 9 | start_time=1501314262.7056608, 10 | end_time=1501314262.901, 11 | trace_id='my-id') 12 | 13 | conn = connection.Connection() 14 | conn.send(record) 15 | 16 | messages = xray_daemon.get_new_messages() 17 | assert len(messages) == 1 18 | -------------------------------------------------------------------------------- /tests/test_functional.py: -------------------------------------------------------------------------------- 1 | def test_dummy_view(client, xray_daemon): 2 | response = client.get('/') 3 | assert response.status_code == 200 4 | assert response.content == b'hello world' 5 | 6 | messages = xray_daemon.get_new_messages() 7 | assert len(messages) >= 1 8 | -------------------------------------------------------------------------------- /tests/test_trace.py: -------------------------------------------------------------------------------- 1 | from django_aws_xray import xray, records 2 | 3 | 4 | def test_trace_from_http_header_root(): 5 | header_value = 'Root=1-5759e988-bd862e3fe1be46a994272793' 6 | trace_object = xray.Trace.from_http_header(header_value, sampled=True) 7 | assert trace_object.root == '1-5759e988-bd862e3fe1be46a994272793' 8 | assert trace_object.parent is None 9 | assert trace_object.sampled is True 10 | 11 | 12 | def test_trace_from_http_header_root_force_sampled(): 13 | header_value = 'Root=1-5759e988-bd862e3fe1be46a994272793;Sampled=1' 14 | trace_object = xray.Trace.from_http_header(header_value, sampled=False) 15 | assert trace_object.root == '1-5759e988-bd862e3fe1be46a994272793' 16 | assert trace_object.parent is None 17 | assert trace_object.sampled is True 18 | 19 | 20 | def test_trace_from_http_header_parent(): 21 | header_value = 'Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8' 22 | trace_object = xray.Trace.from_http_header(header_value, sampled=True) 23 | assert trace_object.root == '1-5759e988-bd862e3fe1be46a994272793' 24 | assert trace_object.parent == '53995c3f42cd8ad8' 25 | assert trace_object.sampled is True 26 | 27 | 28 | def test_trace_from_http_header_parent_force_sampled(): 29 | header_value = 'Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1' 30 | trace_object = xray.Trace.from_http_header(header_value, sampled=False) 31 | assert trace_object.root == '1-5759e988-bd862e3fe1be46a994272793' 32 | assert trace_object.parent == '53995c3f42cd8ad8' 33 | assert trace_object.sampled is True 34 | 35 | 36 | def test_trace_from_http_header_errors(): 37 | header_value = 'Root=1-5759e988-bd862e3fe1be46a994272793;Onzin;;;===;' 38 | trace_object = xray.Trace.from_http_header(header_value, sampled=True) 39 | assert trace_object.root == '1-5759e988-bd862e3fe1be46a994272793' 40 | assert trace_object.parent is None 41 | assert trace_object.sampled is True 42 | 43 | 44 | def test_trace_stack(): 45 | trace = xray.Trace.generate_new() 46 | 47 | record = records.SegmentRecord(name='root') 48 | 49 | with trace.track(record): 50 | assert len(trace._segment_stack) == 1 51 | 52 | subrecord = records.SubSegmentRecord(name='subitem') 53 | with trace.track(subrecord): 54 | assert len(trace._segment_stack) == 2 55 | 56 | assert len(trace._segment_stack) == 1 57 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py36-django111 3 | 4 | [testenv] 5 | commands = coverage run --parallel -m pytest {posargs} 6 | deps = 7 | django111: Django>=1.11,<1.12 8 | extras = test 9 | 10 | # Uses default basepython otherwise reporting doesn't work on Travis where 11 | # Python 3.5 is only available in 3.5 jobs. 12 | [testenv:coverage-report] 13 | deps = coverage 14 | skip_install = true 15 | commands = 16 | coverage combine 17 | coverage report 18 | --------------------------------------------------------------------------------