├── .gitignore ├── .gitmodules ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── VERSION ├── docs ├── Makefile ├── conf.py └── index.rst ├── example ├── README.md ├── client.py ├── img │ ├── jaeger.png │ ├── jaeger_0.png │ └── jaeger_1.png └── server.py ├── flask_opentracing ├── LICENSE ├── __init__.py └── tracing.py ├── requirements-test.txt ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── README.rst ├── __init__.py ├── test_flask_api.py ├── test_flask_tracing.py └── test_flask_tracing_span_callbacks.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | cache 2 | 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *,cover 48 | .hypothesis/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | 58 | # Flask stuff: 59 | instance/ 60 | .webassets-cache 61 | 62 | # Scrapy stuff: 63 | .scrapy 64 | 65 | # Sphinx documentation 66 | docs/_build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # IPython Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # dotenv 81 | .env 82 | 83 | # virtualenv 84 | venv/ 85 | ENV/ 86 | 87 | # Spyder project settings 88 | .spyderproject 89 | 90 | # Rope project settings 91 | .ropeproject 92 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "docs/_themes"] 2 | path = docs/_themes 3 | url = https://github.com/pallets/flask-sphinx-themes 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | language: python 3 | python: 4 | - '2.7' 5 | - '3.5' 6 | - '3.6' 7 | - '3.7' 8 | - '3.8' 9 | - 'nightly' 10 | - 'pypy' 11 | - 'pypy3.5' 12 | 13 | stages: 14 | - lint 15 | - test 16 | - name: deploy 17 | if: tag is present 18 | 19 | matrix: 20 | include: 21 | - stage: lint 22 | name: flake8 23 | python: '3.7' 24 | - stage: deploy 25 | name: Deploy to PyPI 26 | python: '3.7' 27 | install: skip 28 | script: skip 29 | allow_failures: 30 | - python: 'nightly' 31 | 32 | install: 33 | - pip install tox-travis 34 | 35 | script: 36 | - tox 37 | 38 | deploy: 39 | provider: pypi 40 | distributions: sdist 41 | user: '__token__' 42 | password: 43 | secure: 'YkwqdS/sPOcu43pPEAz3YvkJPp+FoSZ39xCM+3wXC5K+SpJW+APn5FH7izivs5DzqRtEP/dLwxUrtk4O+IvFxMgOeRXkGUszRUCYNV819iJwXlcVtODJfdjB+B/pFz6WERh13GhVl6PsG+SBgVE4GNu8F7svCepDX7kcHw1xa+tjkSg1mzmDuZuAhth8Gkph/7LHupx5VP8p96oOViLjI98SCnGDHbmzpDVzW1GZjO5wsTuCc6YYsc0ydKxMYUjaE+7PIMqziK3FjvZj6drnR8SV6e+9kWPNYQ8kodQTfeQuXqwq7s2Va/5lx9iZ+tdBCnCBEb+ehV43M13cqk6jnkZMbC2OZ7TY5Mtm/JWZe9QNcAutdeiqqaSCuGCWP7RT+jgyJaWtHGbAlRj8loHKCFgyzhwK77N/as9oyIxQSVYBIYNtSsvgG33BJQXO9oLf85qZ/C4WkFCX2JeZLAAvMv8Pm0r1lhmtN1nKEdOl6H0VQUls9S2u7s+HnEoTu9TXQ6FiDwV3iF9lZAr1kfPsGhZyEm/rxnMBrPnbbr7puLRJwOp5u1GT0nyp9C2Bpg1XrgpmrK14mpsd0eOMYIdEMc0v1qflze+DyVSEyccj/WbvXlW788bnoGd8svapRbo2ZUf+EfUaIi/S0dzNzQJMx7BHGprpuqHkEmmUbTO8o4Q=' 44 | on: 45 | condition: $TRAVIS_BUILD_STAGE_NAME = Deploy 46 | tags: true 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016, opentracing-contrib 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of python-flask nor the names of its 15 | contributors may be used to endorse or promote products derived from 16 | this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include VERSION LICENSE -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | project := flask_opentracing 2 | 3 | pytest := PYTHONDONTWRITEBYTECODE=1 py.test --tb short -rxs \ 4 | --cov-report term-missing:skip-covered --cov=$(project) tests 5 | 6 | .PHONY: test publish install clean clean-build clean-pyc clean-test build upload-docs 7 | 8 | install: 9 | python setup.py install 10 | 11 | check-virtual-env: 12 | @echo virtual-env: $${VIRTUAL_ENV?"Please run in virtual-env"} 13 | 14 | bootstrap: check-virtual-env 15 | pip install -r requirements.txt 16 | pip install -r requirements-test.txt 17 | python setup.py develop 18 | 19 | clean: clean-build clean-pyc clean-test 20 | 21 | clean-build: 22 | python setup.py clean 23 | rm -fr build/ 24 | rm -fr dist/ 25 | rm -fr .eggs/ 26 | rm -fr .cache/ 27 | find . -name '*.egg-info' -exec rm -fr {} + 28 | find . -name '*.egg' -exec rm -rf {} + 29 | 30 | clean-pyc: 31 | find . -name '*.pyc' -exec rm -f {} + 32 | find . -name '*.pyo' -exec rm -f {} + 33 | find . -name '*~' -exec rm -f {} + 34 | find . -name '__pycache__' -exec rm -fr {} + 35 | 36 | clean-test: 37 | rm -f .coverage 38 | rm -f coverage.xml 39 | rm -fr htmlcov/ 40 | 41 | lint: 42 | flake8 $(project) tests 43 | 44 | test: 45 | $(pytest) 46 | 47 | build: 48 | python setup.py build 49 | 50 | docs: 51 | make -C docs doctest 52 | 53 | upload-docs: 54 | git submodule update --init # for sphinx flask theme 55 | python setup.py build_sphinx 56 | python setup.py upload_docs 57 | 58 | publish: clean test build 59 | @git diff-index --quiet HEAD || (echo "git has uncommitted changes. Refusing to publish." && false) 60 | awk 'BEGIN { FS = "." }; { printf("%d.%d.%d", $$1, $$2, $$3+1) }' VERSION > VERSION.incr 61 | mv VERSION.incr VERSION 62 | git add VERSION 63 | git commit -m "Update VERSION" 64 | git tag `cat VERSION` 65 | git push 66 | git push --tags 67 | python setup.py register -r pypi || (echo "Was unable to register to pypi, aborting publish." && false) 68 | python setup.py sdist upload -r pypi || (echo "Was unable to upload to pypi, publish failed." && false) 69 | $(MAKE) upload-docs 70 | @echo 71 | @echo "\033[92mSUCCESS: published v`cat VERSION` \033[0m" 72 | @echo 73 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ################# 2 | Flask-OpenTracing 3 | ################# 4 | 5 | **Note:** *This package is no longer maintained or supported. Migrate your application 6 | to use* `opentelemetry-api`_. 7 | 8 | 9 | This package enables distributed tracing in Flask applications via `The OpenTracing Project`_. Once a production system contends with real concurrency or splits into many services, crucial (and formerly easy) tasks become difficult: user-facing latency optimization, root-cause analysis of backend errors, communication about distinct pieces of a now-distributed system, etc. Distributed tracing follows a request on its journey from inception to completion from mobile/browser all the way to the microservices. 10 | 11 | As core services and libraries adopt OpenTracing, the application builder is no longer burdened with the task of adding basic tracing instrumentation to their own code. In this way, developers can build their applications with the tools they prefer and benefit from built-in tracing instrumentation. OpenTracing implementations exist for major distributed tracing systems and can be bound or swapped with a one-line configuration change. 12 | 13 | If you want to learn more about the underlying python API, visit the python `source code`_. 14 | 15 | If you are migrating from the 0.x series, you may want to read the list of `breaking changes`_. 16 | 17 | .. _The OpenTracing Project: http://opentracing.io/ 18 | .. _source code: https://github.com/opentracing/opentracing-python 19 | .. _breaking changes: #breaking-changes-from-0-x 20 | .. _opentelemetry-api: https://pypi.org/project/opentelemetry-api/ 21 | 22 | Installation 23 | ============ 24 | 25 | Run the following command: 26 | 27 | .. code-block:: 28 | 29 | $ pip install Flask-Opentracing 30 | 31 | Usage 32 | ===== 33 | 34 | This Flask extension allows for tracing of Flask apps using the OpenTracing API. All 35 | that it requires is for a ``FlaskTracing`` tracer to be initialized using an 36 | instance of an OpenTracing tracer. You can either trace all requests to your site, or use function decorators to trace certain individual requests. 37 | 38 | **Note:** `optional_args` in both cases are any number of attributes (as strings) of `flask.Request` that you wish to set as tags on the created span 39 | 40 | Initialize 41 | ---------- 42 | 43 | `FlaskTracing` wraps the tracer instance that's supported by opentracing. To create a `FlaskTracing` object, you can either pass in a tracer object directly or a callable that returns the tracer object. For example: 44 | 45 | .. code-block:: python 46 | 47 | import opentracing 48 | from flask_opentracing import FlaskTracing 49 | 50 | opentracing_tracer = ## some OpenTracing tracer implementation 51 | tracing = FlaskTracing(opentracing_tracer, ...) 52 | 53 | or 54 | 55 | .. code-block:: python 56 | 57 | import opentracing 58 | from flask_opentracing import FlaskTracing 59 | 60 | def initialize_tracer(): 61 | ... 62 | return opentracing_tracer 63 | 64 | tracing = FlaskTracing(initialize_tracer, ...) 65 | 66 | 67 | Trace All Requests 68 | ------------------ 69 | 70 | .. code-block:: python 71 | 72 | import opentracing 73 | from flask_opentracing import FlaskTracing 74 | 75 | app = Flask(__name__) 76 | 77 | opentracing_tracer = ## some OpenTracing tracer implementation 78 | tracing = FlaskTracing(opentracing_tracer, True, app, [optional_args]) 79 | 80 | Trace Individual Requests 81 | ------------------------- 82 | 83 | .. code-block:: python 84 | 85 | import opentracing 86 | from flask_opentracing import FlaskTracing 87 | 88 | app = Flask(__name__) 89 | 90 | opentracing_tracer = ## some OpenTracing tracer implementation 91 | tracing = FlaskTracing(opentracing_tracer) 92 | 93 | @app.route('/some_url') 94 | @tracing.trace(optional_args) 95 | def some_view_func(): 96 | ... 97 | return some_view 98 | 99 | Accessing Spans Manually 100 | ------------------------ 101 | 102 | In order to access the span for a request, we've provided an method `FlaskTracing.get_span(request)` that returns the span for the request, if it is exists and is not finished. This can be used to log important events to the span, set tags, or create child spans to trace non-RPC events. If no request is passed in, the current request will be used. 103 | 104 | Tracing an RPC 105 | -------------- 106 | 107 | If you want to make an RPC and continue an existing trace, you can inject the current span into the RPC. For example, if making an http request, the following code will continue your trace across the wire: 108 | 109 | .. code-block:: python 110 | 111 | @tracing.trace() 112 | def some_view_func(request): 113 | new_request = some_http_request 114 | current_span = tracing.get_span(request) 115 | text_carrier = {} 116 | opentracing_tracer.inject(span, opentracing.Format.TEXT_MAP, text_carrier) 117 | for k, v in text_carrier.iteritems(): 118 | new_request.add_header(k,v) 119 | ... # make request 120 | 121 | Examples 122 | ======== 123 | 124 | See `examples`_ to view and run an example of two Flask applications 125 | with integrated OpenTracing tracers. 126 | 127 | .. _examples: https://github.com/opentracing-contrib/python-flask/tree/master/example 128 | 129 | `This tutorial `_ has a step-by-step guide for using `Flask-Opentracing` with `Jaeger `_. 130 | 131 | Breaking changes from 0.x 132 | ========================= 133 | 134 | Starting with the 1.0 version, a few changes have taken place from previous versions: 135 | 136 | * ``FlaskTracer`` has been renamed to ``FlaskTracing``, although ``FlaskTracing`` 137 | can be used still as a deprecated name. 138 | * When passing an ``Application`` object at ``FlaskTracing`` creation time, 139 | ``trace_all_requests`` defaults to ``True``. 140 | * When no ``opentracing.Tracer`` is provided, ``FlaskTracing`` will rely on the 141 | global tracer. 142 | 143 | Further Information 144 | =================== 145 | 146 | If you're interested in learning more about the OpenTracing standard, please visit `opentracing.io`_ or `join the mailing list`_. If you would like to implement OpenTracing in your project and need help, feel free to send us a note at `community@opentracing.io`_. 147 | 148 | .. _opentracing.io: http://opentracing.io/ 149 | .. _join the mailing list: http://opentracing.us13.list-manage.com/subscribe?u=180afe03860541dae59e84153&id=19117aa6cd 150 | .. _community@opentracing.io: community@opentracing.io 151 | 152 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 2.0.0 2 | -------------------------------------------------------------------------------- /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/flask_opentracing.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/flask_opentracing.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/flask_opentracing" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/flask_opentracing" 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/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # flask_opentracing documentation build configuration file, created by 4 | # sphinx-quickstart on Fri Jul 8 09:35:17 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 = [ 33 | 'sphinx.ext.autodoc', 34 | 'sphinx.ext.doctest', 35 | 'sphinx.ext.todo', 36 | 'sphinx.ext.coverage', 37 | 'sphinx.ext.viewcode', 38 | ] 39 | 40 | # Add any paths that contain templates here, relative to this directory. 41 | templates_path = ['_templates'] 42 | 43 | # The suffix(es) of source filenames. 44 | # You can specify multiple suffix as a list of string: 45 | # 46 | # source_suffix = ['.rst', '.md'] 47 | source_suffix = '.rst' 48 | 49 | # The encoding of source files. 50 | # 51 | # source_encoding = 'utf-8-sig' 52 | 53 | # The master toctree document. 54 | master_doc = 'index' 55 | 56 | # General information about the project. 57 | project = u'flask_opentracing' 58 | copyright = u'2016, Kathy Camenzind' 59 | author = u'Kathy Camenzind' 60 | 61 | # The version info for the project you're documenting, acts as replacement for 62 | # |version| and |release|, also used in various other places throughout the 63 | # built documents. 64 | # 65 | # The short X.Y version. 66 | version = u'0.1' 67 | # The full version, including alpha/beta/rc tags. 68 | release = open('../VERSION').read() 69 | 70 | # The language for content autogenerated by Sphinx. Refer to documentation 71 | # for a list of supported languages. 72 | # 73 | # This is also used if you do content translation via gettext catalogs. 74 | # Usually you set "language" from the command line for these cases. 75 | language = None 76 | 77 | # There are two options for replacing |today|: either, you set today to some 78 | # non-false value, then it is used: 79 | # 80 | # today = '' 81 | # 82 | # Else, today_fmt is used as the format for a strftime call. 83 | # 84 | # today_fmt = '%B %d, %Y' 85 | 86 | # List of patterns, relative to source directory, that match files and 87 | # directories to ignore when looking for source files. 88 | # This patterns also effect to html_static_path and html_extra_path 89 | exclude_patterns = [] 90 | 91 | # The reST default role (used for this markup: `text`) to use for all 92 | # documents. 93 | # 94 | # default_role = None 95 | 96 | # If true, '()' will be appended to :func: etc. cross-reference text. 97 | # 98 | # add_function_parentheses = True 99 | 100 | # If true, the current module name will be prepended to all description 101 | # unit titles (such as .. function::). 102 | # 103 | # add_module_names = True 104 | 105 | # If true, sectionauthor and moduleauthor directives will be shown in the 106 | # output. They are ignored by default. 107 | # 108 | # show_authors = False 109 | 110 | # The name of the Pygments (syntax highlighting) style to use. 111 | pygments_style = 'sphinx' 112 | 113 | # A list of ignored prefixes for module index sorting. 114 | # modindex_common_prefix = [] 115 | 116 | # If true, keep warnings as "system message" paragraphs in the built documents. 117 | # keep_warnings = False 118 | 119 | # If true, `todo` and `todoList` produce output, else they produce nothing. 120 | todo_include_todos = True 121 | 122 | 123 | # -- Options for HTML output ---------------------------------------------- 124 | 125 | # The theme to use for HTML and HTML Help pages. See the documentation for 126 | # a list of builtin themes. 127 | # 128 | html_theme = 'flask_small' 129 | 130 | # Theme options are theme-specific and customize the look and feel of a theme 131 | # further. For a list of options available for each theme, see the 132 | # documentation. 133 | # 134 | html_theme_options = {'index_logo': False} 135 | 136 | # Add any paths that contain custom themes here, relative to this directory. 137 | html_theme_path = ['_themes'] 138 | 139 | # The name for this set of Sphinx documents. 140 | # " v documentation" by default. 141 | # 142 | # html_title = u'flask_opentracing v0.1.0' 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 | 185 | # Additional templates that should be rendered to pages, maps page names to 186 | # template names. 187 | # 188 | # html_additional_pages = {} 189 | 190 | # If false, no module index is generated. 191 | # 192 | # html_domain_indices = True 193 | 194 | # If false, no index is generated. 195 | # 196 | # html_use_index = True 197 | 198 | # If true, the index is split into individual pages for each letter. 199 | # 200 | # html_split_index = False 201 | 202 | # If true, links to the reST sources are added to the pages. 203 | # 204 | # html_show_sourcelink = True 205 | 206 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 207 | # 208 | # html_show_sphinx = True 209 | 210 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 211 | # 212 | # html_show_copyright = True 213 | 214 | # If true, an OpenSearch description file will be output, and all pages will 215 | # contain a tag referring to it. The value of this option must be the 216 | # base URL from which the finished HTML is served. 217 | # 218 | # html_use_opensearch = '' 219 | 220 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 221 | # html_file_suffix = None 222 | 223 | # Language to be used for generating the HTML full-text search index. 224 | # Sphinx supports the following languages: 225 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 226 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' 227 | # 228 | # html_search_language = 'en' 229 | 230 | # A dictionary with options for the search language support, empty by default. 231 | # 'ja' uses this config value. 232 | # 'zh' user can custom change `jieba` dictionary path. 233 | # 234 | # html_search_options = {'type': 'default'} 235 | 236 | # The name of a javascript file (relative to the configuration directory) that 237 | # implements a search results scorer. If empty, the default will be used. 238 | # 239 | # html_search_scorer = 'scorer.js' 240 | 241 | # Output file base name for HTML help builder. 242 | htmlhelp_basename = 'flask_opentracingdoc' 243 | 244 | # -- Options for LaTeX output --------------------------------------------- 245 | 246 | latex_elements = { 247 | # The paper size ('letterpaper' or 'a4paper'). 248 | # 249 | # 'papersize': 'letterpaper', 250 | 251 | # The font size ('10pt', '11pt' or '12pt'). 252 | # 253 | # 'pointsize': '10pt', 254 | 255 | # Additional stuff for the LaTeX preamble. 256 | # 257 | # 'preamble': '', 258 | 259 | # Latex figure (float) alignment 260 | # 261 | # 'figure_align': 'htbp', 262 | } 263 | 264 | # Grouping the document tree into LaTeX files. List of tuples 265 | # (source start file, target name, title, 266 | # author, documentclass [howto, manual, or own class]). 267 | latex_documents = [ 268 | (master_doc, 'flask_opentracing.tex', u'flask\\_opentracing Documentation', 269 | u'Kathy Camenzind', 'manual'), 270 | ] 271 | 272 | # The name of an image file (relative to this directory) to place at the top of 273 | # the title page. 274 | # 275 | # latex_logo = None 276 | 277 | # For "manual" documents, if this is true, then toplevel headings are parts, 278 | # not chapters. 279 | # 280 | # latex_use_parts = False 281 | 282 | # If true, show page references after internal links. 283 | # 284 | # latex_show_pagerefs = False 285 | 286 | # If true, show URL addresses after external links. 287 | # 288 | # latex_show_urls = False 289 | 290 | # Documents to append as an appendix to all manuals. 291 | # 292 | # latex_appendices = [] 293 | 294 | # If false, no module index is generated. 295 | # 296 | # latex_domain_indices = True 297 | 298 | 299 | # -- Options for manual page output --------------------------------------- 300 | 301 | # One entry per manual page. List of tuples 302 | # (source start file, name, description, authors, manual section). 303 | man_pages = [ 304 | (master_doc, 'flask_opentracing', u'flask_opentracing Documentation', 305 | [author], 1) 306 | ] 307 | 308 | # If true, show URL addresses after external links. 309 | # 310 | # man_show_urls = False 311 | 312 | 313 | # -- Options for Texinfo output ------------------------------------------- 314 | 315 | # Grouping the document tree into Texinfo files. List of tuples 316 | # (source start file, target name, title, author, 317 | # dir menu entry, description, category) 318 | texinfo_documents = [ 319 | (master_doc, 'flask_opentracing', u'flask_opentracing Documentation', 320 | author, 'flask_opentracing', 'OpenTracing support for Flask', 321 | 'Tracing'), 322 | ] 323 | 324 | # Documents to append as an appendix to all manuals. 325 | # 326 | # texinfo_appendices = [] 327 | 328 | # If false, no module index is generated. 329 | # 330 | # texinfo_domain_indices = True 331 | 332 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 333 | # 334 | # texinfo_show_urls = 'footnote' 335 | 336 | # If true, do not generate a @detailmenu in the "Top" node's menu. 337 | # 338 | # texinfo_no_detailmenu = False 339 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Flask-OpenTracing 2 | ================= 3 | 4 | This package enables distributed tracing in `Flask`_ applications via `The OpenTracing Project`_. Once a production system contends with real concurrency or splits into many services, crucial (and formerly easy) tasks become difficult: user-facing latency optimization, root-cause analysis of backend errors, communication about distinct pieces of a now-distributed system, etc. Distributed tracing follows a request on its journey from inception to completion from mobile/browser all the way to the microservices. 5 | 6 | As core services and libraries adopt OpenTracing, the application builder is no longer burdened with the task of adding basic tracing instrumentation to their own code. In this way, developers can build their applications with the tools they prefer and benefit from built-in tracing instrumentation. OpenTracing implementations exist for major distributed tracing systems and can be bound or swapped with a one-line configuration change. 7 | 8 | If you want to learn more about the underlying python API, visit the python `source code`_. 9 | 10 | .. _Flask: http://flask.pocoo.org/ 11 | .. _The OpenTracing Project: http://opentracing.io/ 12 | .. _source code: https://github.com/opentracing/opentracing-python 13 | 14 | 15 | Installation 16 | ------------ 17 | 18 | Install the extension with the following command:: 19 | 20 | $ pip install Flask-OpenTracing 21 | 22 | Usage 23 | ----- 24 | 25 | All that is required is for a FlaskTracing tracer to be initialized using an 26 | instance of an OpenTracing tracer. You can either trace all requests to your site, 27 | or use function decorators to trace certain individual requests. 28 | 29 | **Note:** `optional_args` in both cases are any number of attributes (as strings) of `flask.Request` that you wish to set as tags on the created span 30 | 31 | Trace All Requests 32 | ~~~~~~~~~~~~~~~~~~ 33 | 34 | .. code-block:: python 35 | 36 | import opentracing 37 | from flask_opentracing import FlaskTracing 38 | 39 | app = Flask(__name__) 40 | 41 | opentracing_tracer = ## some OpenTracing tracer implementation 42 | tracing = FlaskTracing(opentracing_tracer, True, app, [optional_args]) 43 | 44 | Trace Individual Requests 45 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 46 | 47 | .. code-block:: python 48 | 49 | import opentracing 50 | from flask_opentracing import FlaskTracing 51 | 52 | app = Flask(__name__) 53 | 54 | opentracing_tracer = ## some OpenTracing tracer implementation 55 | tracing = FlaskTracing(opentracing_tracer) 56 | 57 | @app.route('/some_url') 58 | @tracing.trace(optional_args) 59 | def some_view_func(): 60 | ... 61 | return some_view 62 | 63 | Accessing Spans Manually 64 | ~~~~~~~~~~~~~~~~~~~~~~~~ 65 | 66 | In order to access the span for a request, we've provided an method `FlaskTracing.get_span(request)` that returns the span for the request, if it is exists and is not finished. This can be used to log important events to the span, set tags, or create child spans to trace non-RPC events. If no request is passed in, the current request will be used. 67 | 68 | Tracing an RPC 69 | ~~~~~~~~~~~~~~ 70 | 71 | If you want to make an RPC and continue an existing trace, you can inject the current span into the RPC. For example, if making an http request, the following code will continue your trace across the wire: 72 | 73 | .. code-block:: python 74 | 75 | @tracing.trace() 76 | def some_view_func(request): 77 | new_request = some_http_request 78 | current_span = tracing.get_span(request) 79 | text_carrier = {} 80 | opentracing_tracer.inject(span, opentracing.Format.TEXT_MAP, text_carrier) 81 | for k, v in text_carrier.iteritems(): 82 | new_request.add_header(k,v) 83 | ... # make request 84 | 85 | Examples 86 | -------- 87 | 88 | See `examples`_ to view and run an example of two Flask applications 89 | with integrated OpenTracing tracers. 90 | 91 | .. _examples: https://github.com/opentracing-contrib/python-flask/tree/master/example 92 | 93 | Further Information 94 | ------------------- 95 | 96 | If you’re interested in learning more about the OpenTracing standard, please visit `opentracing.io`_ or `join the mailing list`_. If you would like to implement OpenTracing in your project and need help, feel free to send us a note at `community@opentracing.io`_. 97 | 98 | .. _opentracing.io: http://opentracing.io/ 99 | .. _join the mailing list: http://opentracing.us13.list-manage.com/subscribe?u=180afe03860541dae59e84153&id=19117aa6cd 100 | .. _community@opentracing.io: community@opentracing.io 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | ## Example 2 | 3 | This example has a flask client and server and shows how to trace the requests 4 | to a webserver from a client using the flask_opentracing extension and 5 | a concrete variant of an OpenTracing tracer. To run, make sure that you run pip 6 | install for flask, opentracing, jaeger_client. 7 | 8 | ### Set up Jaeger: 9 | 10 | First, we'll have to download and run our Jaeger instance. It collects and displays 11 | traces in neat graphical format. 12 | 13 | If you already have Docker installed, run this: 14 | 15 | ``` 16 | docker run -d -e \ 17 | COLLECTOR_ZIPKIN_HTTP_PORT=9411 \ 18 | -p 5775:5775/udp \ 19 | -p 6831:6831/udp \ 20 | -p 6832:6832/udp \ 21 | -p 5778:5778 \ 22 | -p 16686:16686 \ 23 | -p 14268:14268 \ 24 | -p 9411:9411 \ 25 | jaegertracing/all-in-one:latest 26 | ``` 27 | 28 | You should be able to see a web interface by browsing to http://localhost:16686/search 29 | 30 | ![traced request](https://raw.githubusercontent.com/opentracing-contrib/python-flask/example/example/img/jaeger_0.png) 31 | 32 | Now, open two terminals and navigate to this directory. Run the following commands in 33 | each terminal: 34 | 35 | First window: 36 | 37 | ``` 38 | > python3 server.py 39 | ``` 40 | 41 | Give it few seconds to start and run this in second window: 42 | 43 | ``` 44 | > python3 client.py 45 | ``` 46 | 47 | To see the traced requests, go to Jaeger web interface and refresh the page. 48 | Select your service name from dropdown on the left (it's 49 | "jaeger_opentracing_example" in our case) and press Find traces button at the bottom of the page. 50 | 51 | 52 | ![traced request](https://raw.githubusercontent.com/opentracing-contrib/python-flask/example/example/img/jaeger.png) 53 | 54 | 55 | (NOTE: if you wish to use a different OpenTracing tracer instead of Jaeger, simply replace 56 | `jaeger_tracer` with the OpenTracing tracer instance of your choice.) 57 | 58 | ### Trace a request from browser: 59 | 60 | Browse to http://localhost:5000/log and compare the trace in Jaeger. 61 | The last one has 2 spans instead of 3. The span of webserver's GET method is missing. 62 | That is because client.py starts a trace and passes trace context over the wire, whereas the request from your browser has no tracing context in it. 63 | 64 | ### Add spans to the trace manually: 65 | 66 | In log function of the server app, we are creating current_span. This is done to 67 | trace the work that is being done to render the response to /log endpoint. Suppose there's 68 | a database connection happening. By creating a separate span for it, you'll be able 69 | to trace the DB request separately from rendering or the response. This gives a 70 | lot of flexibility to the user. 71 | 72 | Speaking about databases, using install_all_patches() method from 73 | opentracing_instrumentation package gives you a way to trace 74 | your MySQLdb, SQLAlchemy, Redis queries without writing boilerplate code. 75 | 76 | Following code shows how to create a span based on already existing one. 77 | 78 | ```python 79 | # child_scope.span automatically inherits from the Span created 80 | # for this request by the Flask instrumentation. 81 | child_scope = jaeger_tracer.start_active_span('inside create_child_span') 82 | ... do some stuff 83 | child_scope.close() 84 | ``` 85 | 86 | ![traced request](https://raw.githubusercontent.com/opentracing-contrib/python-flask/example/example/img/jaeger_1.png) 87 | -------------------------------------------------------------------------------- /example/client.py: -------------------------------------------------------------------------------- 1 | import sys 2 | if sys.version_info[:2] >= (3, 10): 3 | # compat for Python written pre-3.10 4 | import collections 5 | import collections.abc 6 | collections.MutableMapping = collections.abc.MutableMapping 7 | 8 | import requests 9 | import time 10 | from opentracing_instrumentation.client_hooks import install_all_patches 11 | from jaeger_client import Config 12 | 13 | from os import getenv 14 | 15 | JAEGER_HOST = getenv('JAEGER_HOST', 'localhost') 16 | WEBSERVER_HOST = getenv('WEBSERVER_HOST', 'localhost') 17 | 18 | # Create configuration object with enabled logging and sampling of all requests. 19 | config = Config(config={'sampler': {'type': 'const', 'param': 1}, 20 | 'logging': True, 21 | 'local_agent': {'reporting_host': JAEGER_HOST}}, 22 | service_name="jaeger_opentracing_example") 23 | tracer = config.initialize_tracer() 24 | 25 | # Automatically trace all requests made with 'requests' library. 26 | install_all_patches() 27 | 28 | url = "http://{}:5000/log".format(WEBSERVER_HOST) 29 | # Make the actual request to webserver. 30 | requests.get(url) 31 | 32 | # allow tracer to flush the spans - https://github.com/jaegertracing/jaeger-client-python/issues/50 33 | time.sleep(2) 34 | tracer.close() 35 | -------------------------------------------------------------------------------- /example/img/jaeger.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opentracing-contrib/python-flask/c5a027c9f11efbc47e77a78cb5faae88ac0797ed/example/img/jaeger.png -------------------------------------------------------------------------------- /example/img/jaeger_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opentracing-contrib/python-flask/c5a027c9f11efbc47e77a78cb5faae88ac0797ed/example/img/jaeger_0.png -------------------------------------------------------------------------------- /example/img/jaeger_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opentracing-contrib/python-flask/c5a027c9f11efbc47e77a78cb5faae88ac0797ed/example/img/jaeger_1.png -------------------------------------------------------------------------------- /example/server.py: -------------------------------------------------------------------------------- 1 | import sys 2 | if sys.version_info[:2] >= (3, 10): 3 | # compat for Python written pre-3.10 4 | import collections 5 | import collections.abc 6 | collections.MutableMapping = collections.abc.MutableMapping 7 | 8 | import logging 9 | from jaeger_client import Config 10 | from flask_opentracing import FlaskTracing 11 | from flask import Flask, request 12 | from os import getenv 13 | JAEGER_HOST = getenv('JAEGER_HOST', 'localhost') 14 | 15 | if __name__ == '__main__': 16 | app = Flask(__name__) 17 | log_level = logging.DEBUG 18 | logging.getLogger('').handlers = [] 19 | logging.basicConfig(format='%(asctime)s %(message)s', level=log_level) 20 | # Create configuration object with enabled logging and sampling of all requests. 21 | config = Config(config={'sampler': {'type': 'const', 'param': 1}, 22 | 'logging': True, 23 | 'local_agent': 24 | # Also, provide a hostname of Jaeger instance to send traces to. 25 | {'reporting_host': JAEGER_HOST}}, 26 | # Service name can be arbitrary string describing this particular web service. 27 | service_name="jaeger_opentracing_example") 28 | jaeger_tracer = config.initialize_tracer() 29 | tracing = FlaskTracing(jaeger_tracer) 30 | 31 | @app.route('/log') 32 | @tracing.trace() # Indicate that /log endpoint should be traced 33 | def log(): 34 | # Extract the span information for request object. 35 | with jaeger_tracer.start_active_span( 36 | 'python webserver internal span of log method') as scope: 37 | # Perform some computations to be traced. 38 | 39 | a = 1 40 | b = 2 41 | c = a + b 42 | 43 | scope.span.log_kv({'event': 'my computer knows math!', 'result': c}) 44 | 45 | return "log" 46 | 47 | app.run(debug=True, host='0.0.0.0', port=5000) 48 | -------------------------------------------------------------------------------- /flask_opentracing/LICENSE: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opentracing-contrib/python-flask/c5a027c9f11efbc47e77a78cb5faae88ac0797ed/flask_opentracing/LICENSE -------------------------------------------------------------------------------- /flask_opentracing/__init__.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | 3 | from .tracing import FlaskTracing # noqa 4 | from .tracing import FlaskTracing as FlaskTracer # noqa, deprecated 5 | 6 | warnings.warn( 7 | 'This package is no longer supported.' 8 | ' Migrate to using opentelemetry-api.', 9 | DeprecationWarning, 10 | stacklevel=2 11 | ) 12 | -------------------------------------------------------------------------------- /flask_opentracing/tracing.py: -------------------------------------------------------------------------------- 1 | import opentracing 2 | from opentracing.ext import tags 3 | from flask import request as flask_current_request 4 | 5 | 6 | class FlaskTracing(opentracing.Tracer): 7 | """ 8 | Tracer that can trace certain requests to a Flask app. 9 | 10 | @param tracer the OpenTracing tracer implementation to trace requests with 11 | """ 12 | def __init__(self, tracer=None, trace_all_requests=None, app=None, 13 | traced_attributes=[], start_span_cb=None): 14 | 15 | if start_span_cb is not None and not callable(start_span_cb): 16 | raise ValueError('start_span_cb is not callable') 17 | 18 | if trace_all_requests is True and app is None: 19 | raise ValueError('trace_all_requests=True requires an app object') 20 | 21 | if trace_all_requests is None: 22 | trace_all_requests = False if app is None else True 23 | 24 | if not callable(tracer): 25 | self.__tracer = tracer 26 | self.__tracer_getter = None 27 | else: 28 | self.__tracer = None 29 | self.__tracer_getter = tracer 30 | 31 | self._trace_all_requests = trace_all_requests 32 | self._start_span_cb = start_span_cb 33 | self._current_scopes = {} 34 | 35 | # tracing all requests requires that app != None 36 | if self._trace_all_requests: 37 | @app.before_request 38 | def start_trace(): 39 | self._before_request_fn(traced_attributes) 40 | 41 | @app.after_request 42 | def end_trace(response): 43 | self._after_request_fn(response) 44 | return response 45 | 46 | @app.teardown_request 47 | def end_trace_with_error(error): 48 | if error is not None: 49 | self._after_request_fn(error=error) 50 | 51 | @property 52 | def _tracer(self): 53 | """DEPRECATED""" 54 | return self.tracer 55 | 56 | @property 57 | def tracer(self): 58 | if not self.__tracer: 59 | if self.__tracer_getter is None: 60 | return opentracing.tracer 61 | 62 | self.__tracer = self.__tracer_getter() 63 | 64 | return self.__tracer 65 | 66 | def trace(self, *attributes): 67 | """ 68 | Function decorator that traces functions 69 | 70 | NOTE: Must be placed after the @app.route decorator 71 | 72 | @param attributes any number of flask.Request attributes 73 | (strings) to be set as tags on the created span 74 | """ 75 | def decorator(f): 76 | def wrapper(*args, **kwargs): 77 | if self._trace_all_requests: 78 | return f(*args, **kwargs) 79 | 80 | self._before_request_fn(list(attributes)) 81 | 82 | try: 83 | r = f(*args, **kwargs) 84 | except Exception as e: 85 | self._after_request_fn(error=e) 86 | raise 87 | 88 | self._after_request_fn(response=r) 89 | 90 | return r 91 | 92 | wrapper.__name__ = f.__name__ 93 | return wrapper 94 | return decorator 95 | 96 | def get_span(self, request=None): 97 | """ 98 | Returns the span tracing `request`, or the current request if 99 | `request==None`. 100 | 101 | If there is no such span, get_span returns None. 102 | 103 | @param request the request to get the span from 104 | """ 105 | if request is None: 106 | request = flask_current_request 107 | 108 | scope = self._current_scopes.get(request, None) 109 | return None if scope is None else scope.span 110 | 111 | def _before_request_fn(self, attributes): 112 | request = flask_current_request 113 | operation_name = request.endpoint 114 | headers = {} 115 | for k, v in request.headers: 116 | headers[k.lower()] = v 117 | 118 | try: 119 | span_ctx = self.tracer.extract(opentracing.Format.HTTP_HEADERS, 120 | headers) 121 | scope = self.tracer.start_active_span(operation_name, 122 | child_of=span_ctx) 123 | except (opentracing.InvalidCarrierException, 124 | opentracing.SpanContextCorruptedException): 125 | scope = self.tracer.start_active_span(operation_name) 126 | 127 | self._current_scopes[request] = scope 128 | 129 | span = scope.span 130 | span.set_tag(tags.COMPONENT, 'Flask') 131 | span.set_tag(tags.HTTP_METHOD, request.method) 132 | span.set_tag(tags.HTTP_URL, request.base_url) 133 | span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER) 134 | 135 | for attr in attributes: 136 | if hasattr(request, attr): 137 | payload = getattr(request, attr) 138 | if payload not in ('', b''): # python3 139 | span.set_tag(attr, str(payload)) 140 | 141 | self._call_start_span_cb(span, request) 142 | 143 | def _after_request_fn(self, response=None, error=None): 144 | request = flask_current_request 145 | 146 | # the pop call can fail if the request is interrupted by a 147 | # `before_request` method so we need a default 148 | scope = self._current_scopes.pop(request, None) 149 | if scope is None: 150 | return 151 | 152 | if response is not None: 153 | scope.span.set_tag(tags.HTTP_STATUS_CODE, response.status_code) 154 | if error is not None: 155 | scope.span.set_tag(tags.ERROR, True) 156 | scope.span.log_kv({ 157 | 'event': tags.ERROR, 158 | 'error.object': error, 159 | }) 160 | 161 | scope.close() 162 | 163 | def _call_start_span_cb(self, span, request): 164 | if self._start_span_cb is None: 165 | return 166 | 167 | try: 168 | self._start_span_cb(span, request) 169 | except Exception: 170 | pass 171 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | # add dependencies in setup.py 2 | 3 | -r requirements.txt 4 | tox 5 | 6 | -e .[tests] 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # add dependencies in setup.py 2 | 3 | -e . 4 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [aliases] 2 | test=pytest 3 | 4 | [metadata] 5 | description_file = README.rst 6 | 7 | [tool:pytest] 8 | addopts = 9 | --tb short 10 | -rxs 11 | --cov-report term-missing:skip-covered 12 | --cov flask_opentracing 13 | tests 14 | 15 | [coverage:run] 16 | branch = True 17 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | ''' 4 | Flask-OpenTracing 5 | ----------------- 6 | 7 | This extension provides simple integration of OpenTracing in Flask applications. 8 | ''' 9 | version = open('VERSION').read().strip() 10 | setup( 11 | name='Flask-OpenTracing', 12 | version=version, 13 | url='http://github.com/opentracing-contrib/python-flask', 14 | download_url='https://github.com/opentracing-contrib/python-flask/tarball/'+version, 15 | license='BSD', 16 | author='Kathy Camenzind', 17 | author_email='kcamenzind@lightstep.com', 18 | description='OpenTracing support for Flask applications', 19 | long_description=open('README.rst').read(), 20 | long_description_content_type='text/x-rst', 21 | packages=['flask_opentracing', 'tests'], 22 | zip_safe=False, 23 | include_package_data=True, 24 | platforms='any', 25 | install_requires=[ 26 | 'Flask', 27 | 'opentracing>=2.0,<3', 28 | ], 29 | extras_require={ 30 | 'tests': [ 31 | 'flake8', 32 | 'flake8-quotes', 33 | 'mock', 34 | 'pytest', 35 | 'pytest-cov', 36 | 'tox', 37 | ], 38 | }, 39 | classifiers=[ 40 | 'Environment :: Web Environment', 41 | 'Intended Audience :: Developers', 42 | 'License :: OSI Approved :: BSD License', 43 | 'Operating System :: OS Independent', 44 | 'Programming Language :: Python', 45 | 'Programming Language :: Python :: 3', 46 | 'Programming Language :: Python :: 3.8', 47 | 'Programming Language :: Python :: 3.9', 48 | 'Programming Language :: Python :: 3.10', 49 | 'Programming Language :: Python :: 3.11', 50 | 'Programming Language :: Python :: 3.12', 51 | 'Programming Language :: Python :: Implementation :: CPython', 52 | 'Programming Language :: Python :: Implementation :: PyPy', 53 | 'Development Status :: 7 - Inactive', 54 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 55 | 'Topic :: Software Development :: Libraries :: Python Modules' 56 | ] 57 | ) 58 | -------------------------------------------------------------------------------- /tests/README.rst: -------------------------------------------------------------------------------- 1 | Tests 2 | ===== 3 | 4 | Run the tests with the following command: 5 | 6 | .. code-block:: 7 | 8 | $ pip install -r requirements-test.txt 9 | $ tox -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opentracing-contrib/python-flask/c5a027c9f11efbc47e77a78cb5faae88ac0797ed/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_flask_api.py: -------------------------------------------------------------------------------- 1 | import mock 2 | import pytest 3 | import unittest 4 | 5 | import opentracing 6 | from flask import Flask 7 | from flask_opentracing import FlaskTracing 8 | 9 | 10 | class TestValues(unittest.TestCase): 11 | def test_tracer(self): 12 | tracer = opentracing.Tracer() 13 | tracing = FlaskTracing(tracer) 14 | assert tracing.tracer is tracer 15 | assert tracing.tracer is tracing._tracer 16 | assert tracing._trace_all_requests is False 17 | 18 | def test_global_tracer(self): 19 | tracing = FlaskTracing() 20 | with mock.patch('opentracing.tracer'): 21 | assert tracing.tracer is opentracing.tracer 22 | opentracing.tracer = object() 23 | assert tracing.tracer is opentracing.tracer 24 | 25 | def test_trace_all_requests(self): 26 | app = Flask('dummy_app') 27 | tracing = FlaskTracing(app=app) 28 | assert tracing._trace_all_requests is True 29 | 30 | tracing = FlaskTracing(app=app, trace_all_requests=False) 31 | assert tracing._trace_all_requests is False 32 | 33 | def test_trace_all_requests_no_app(self): 34 | # when trace_all_requests is True, an app object is *required* 35 | with pytest.raises(ValueError): 36 | FlaskTracing(trace_all_requests=True) 37 | 38 | def test_start_span_invalid(self): 39 | with pytest.raises(ValueError): 40 | FlaskTracing(start_span_cb=0) 41 | -------------------------------------------------------------------------------- /tests/test_flask_tracing.py: -------------------------------------------------------------------------------- 1 | import mock 2 | import unittest 3 | 4 | from flask import (Flask, Response, request) 5 | import opentracing 6 | from opentracing.ext import tags 7 | from opentracing.mocktracer import MockTracer 8 | from flask_opentracing import FlaskTracing 9 | from flaky import flaky 10 | 11 | 12 | app = Flask(__name__) 13 | test_app = app.test_client() 14 | 15 | 16 | tracing_all = FlaskTracing(MockTracer(), True, app, ['url']) 17 | tracing = FlaskTracing(MockTracer()) 18 | tracing_deferred = FlaskTracing(lambda: MockTracer(), 19 | True, app, ['url']) 20 | 21 | 22 | def flush_spans(tcr): 23 | for span in tcr._current_scopes.values(): 24 | span.close() 25 | tcr._current_scopes = {} 26 | 27 | 28 | @app.route('/test') 29 | def check_test_works(): 30 | return Response('Success') 31 | 32 | 33 | @app.route('/another_test') 34 | @tracing.trace('url', 'url_rule') 35 | def decorated_fn(): 36 | return Response('Success again') 37 | 38 | 39 | @app.route('/another_test_simple') 40 | @tracing.trace('query_string', 'is_xhr') 41 | def decorated_fn_simple(): 42 | return Response('Success again') 43 | 44 | 45 | @app.route('/error_test') 46 | @tracing.trace() 47 | def decorated_fn_with_error(): 48 | raise RuntimeError('Intentional testing exception') 49 | 50 | 51 | @app.route('/decorated_child_span_test') 52 | @tracing.trace() 53 | def decorated_fn_with_child_span(): 54 | with tracing.tracer.start_active_span('child'): 55 | return Response('Success') 56 | 57 | 58 | @app.route('/wire') 59 | def send_request(): 60 | span = tracing_all.get_span() 61 | headers = {} 62 | tracing_all.tracer.inject(span.context, 63 | opentracing.Format.TEXT_MAP, 64 | headers) 65 | rv = test_app.get('/test', headers=headers) 66 | return str(rv.status_code) 67 | 68 | 69 | class TestTracing(unittest.TestCase): 70 | def setUp(self): 71 | tracing_all._tracer.reset() 72 | tracing._tracer.reset() 73 | tracing_deferred._tracer.reset() 74 | 75 | def test_span_creation(self): 76 | with app.test_request_context('/test'): 77 | app.preprocess_request() 78 | assert tracing_all.get_span(request) 79 | assert not tracing.get_span(request) 80 | assert tracing_deferred.get_span(request) 81 | 82 | active_span = tracing_all.tracer.active_span 83 | assert tracing_all.get_span(request) is active_span 84 | 85 | flush_spans(tracing_all) 86 | flush_spans(tracing_deferred) 87 | 88 | def test_span_deletion(self): 89 | assert not tracing_all._current_scopes 90 | assert not tracing_deferred._current_scopes 91 | test_app.get('/test') 92 | assert not tracing_all._current_scopes 93 | assert not tracing_deferred._current_scopes 94 | 95 | def test_span_tags(self): 96 | response = test_app.get('/another_test_simple') 97 | 98 | spans = tracing._tracer.finished_spans() 99 | assert len(spans) == 1 100 | assert spans[0].tags == { 101 | tags.COMPONENT: 'Flask', 102 | tags.HTTP_METHOD: 'GET', 103 | tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER, 104 | tags.HTTP_URL: 'http://localhost/another_test_simple', 105 | tags.HTTP_STATUS_CODE: response.status_code, 106 | } 107 | 108 | @flaky(max_runs=5) 109 | def test_requests_distinct(self): 110 | with app.test_request_context('/test'): 111 | app.preprocess_request() 112 | with app.test_request_context('/test'): 113 | app.preprocess_request() 114 | second_scope = tracing_all._current_scopes.pop(request) 115 | assert second_scope 116 | second_scope.close() 117 | assert not tracing_all.get_span(request) 118 | # clear current spans 119 | flush_spans(tracing_all) 120 | flush_spans(tracing_deferred) 121 | 122 | def test_decorator(self): 123 | with app.test_request_context('/another_test'): 124 | app.preprocess_request() 125 | assert not tracing.get_span(request) 126 | assert len(tracing_deferred._current_scopes) == 1 127 | assert len(tracing_all._current_scopes) == 1 128 | 129 | active_span = tracing_all.tracer.active_span 130 | assert tracing_all.get_span(request) is active_span 131 | 132 | flush_spans(tracing) 133 | flush_spans(tracing_all) 134 | flush_spans(tracing_deferred) 135 | 136 | test_app.get('/another_test') 137 | assert not tracing_all._current_scopes 138 | assert not tracing._current_scopes 139 | assert not tracing_deferred._current_scopes 140 | 141 | def test_decorator_trace_all(self): 142 | # Fake we are tracing all, which should disable 143 | # tracing through our decorator. 144 | with mock.patch.object(tracing, '_trace_all_requests', new=True): 145 | rv = test_app.get('/another_test_simple') 146 | assert '200' in str(rv.status_code) 147 | 148 | spans = tracing.tracer.finished_spans() 149 | assert len(spans) == 0 150 | 151 | def test_error(self): 152 | try: 153 | test_app.get('/error_test') 154 | except RuntimeError: 155 | pass 156 | 157 | assert len(tracing._current_scopes) == 0 158 | assert len(tracing_all._current_scopes) == 0 159 | assert len(tracing_deferred._current_scopes) == 0 160 | 161 | # Registered handler. 162 | spans = tracing.tracer.finished_spans() 163 | assert len(spans) == 1 164 | self._verify_error(spans[0]) 165 | 166 | # Decorator. 167 | spans = tracing.tracer.finished_spans() 168 | assert len(spans) == 1 169 | self._verify_error(spans[0]) 170 | 171 | def _verify_error(self, span): 172 | assert span.tags.get(tags.ERROR) is True 173 | 174 | assert len(span.logs) == 1 175 | assert span.logs[0].key_values.get('event', None) is tags.ERROR 176 | assert isinstance( 177 | span.logs[0].key_values.get('error.object', None), 178 | RuntimeError 179 | ) 180 | 181 | @flaky(max_runs=5) 182 | def test_over_wire(self): 183 | rv = test_app.get('/wire') 184 | assert '200' in str(rv.status_code) 185 | 186 | spans = tracing_all.tracer.finished_spans() 187 | assert len(spans) == 2 188 | assert spans[0].context.trace_id == spans[1].context.trace_id 189 | assert spans[0].parent_id == spans[1].context.span_id 190 | 191 | def test_child_span(self): 192 | rv = test_app.get('/decorated_child_span_test') 193 | assert '200' in str(rv.status_code) 194 | 195 | spans = tracing.tracer.finished_spans() 196 | assert len(spans) == 2 197 | assert spans[0].context.trace_id == spans[1].context.trace_id 198 | assert spans[0].parent_id == spans[1].context.span_id 199 | -------------------------------------------------------------------------------- /tests/test_flask_tracing_span_callbacks.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from abc import abstractmethod 3 | 4 | from flask import Flask 5 | from opentracing.ext import tags 6 | from opentracing.mocktracer import MockTracer 7 | from flask_opentracing import FlaskTracing 8 | 9 | 10 | class _StartSpanCallbackTestCase(unittest.TestCase): 11 | @staticmethod 12 | @abstractmethod 13 | def start_span_cb(span, request): 14 | pass 15 | 16 | def setUp(self): 17 | self.app = Flask(__name__) 18 | self.tracing = FlaskTracing( 19 | MockTracer(), True, self.app, start_span_cb=self.start_span_cb 20 | ) 21 | self.test_app = self.app.test_client() 22 | 23 | @self.app.route('/test') 24 | def check_test_works(): 25 | return 'Success' 26 | 27 | 28 | class TestFlaskTracingStartSpanCallbackSetTags(_StartSpanCallbackTestCase): 29 | @staticmethod 30 | def start_span_cb(span, request): 31 | print('setting tags') 32 | span.set_tag('component', 'not-flask') 33 | span.set_tag('mytag', 'myvalue') 34 | 35 | def test_simple(self): 36 | rv = self.test_app.get('/test') 37 | assert '200' in str(rv.status_code) 38 | 39 | spans = self.tracing.tracer.finished_spans() 40 | assert len(spans) == 1 41 | assert spans[0].tags.get(tags.COMPONENT, None) == 'not-flask' 42 | assert spans[0].tags.get('mytag', None) == 'myvalue' 43 | 44 | 45 | class TestFlaskTracingStartSpanCallbackRaisesError( 46 | _StartSpanCallbackTestCase 47 | ): 48 | @staticmethod 49 | def start_span_cb(span, request): 50 | print('raising exception') 51 | raise RuntimeError('Should not happen') 52 | 53 | def test_error(self): 54 | rv = self.test_app.get('/test') 55 | assert '200' in str(rv.status_code) 56 | 57 | spans = self.tracing.tracer.finished_spans() 58 | assert len(spans) == 1 59 | assert spans[0].tags.get(tags.ERROR, None) is None 60 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py3{8,9,10,11,12},pypy{,3},flake8 3 | skip_missing_interpreters = true 4 | 5 | [travis] 6 | python = 7 | 3.9: py39,flake8 8 | 9 | [travis:env] 10 | TRAVIS_BUILD_STAGE_NAME = 11 | Lint: flake8 12 | Test: py3{8,9,10,11,12},pypy{,3} 13 | 14 | [testenv:flake8] 15 | basepython = python3.9 16 | deps = 17 | flake8 18 | flake8-quotes 19 | commands = flake8 flask_opentracing tests 20 | 21 | [testenv] 22 | deps = 23 | flaky 24 | extras = tests 25 | commands = 26 | pytest {posargs} 27 | --------------------------------------------------------------------------------