Python Configuration - Configuring the Instana package

General

The Instana Python package aims to be a fully no-touch automatic solution for Python monitoring but still be fully configurable when needed. This page outlines the options available in configuring this package.

AutoProfile™

AutoProfile generates and reports process profiles to Instana automatically and continuously. Learn more about profiles in Analyze Profiles section.

To enable AutoProfile set the environment variable INSTANA_AUTOPROFILE=true. AutoProfile is currently supported for manual installation only. Please make sure the Instana sensor is initialized in the main thread.

Host Agent Communication

The Instana Python package tries to communicate with the Instana agent via IP 127.0.0.1 and as a fallback via the host's default gateway for containerized environments. Should the agent not be available at either of these locations, you can use environment variables to configure where to look for the Instana Host Agent.

The environment variables should be set in the environment of the running process.

export INSTANA_AGENT_HOST = '127.0.0.1'
export INSTANA_AGENT_PORT = '42699'

See also:

Setting the Service Name

By default, the Instana will make a best effort in naming your services appropriately. If for any reason you wish to customize how services are named, you can do so by setting an environment variable:

export INSTANA_SERVICE_NAME=myservice

See also the General Reference: Environment Variables for Language Sensors

Setting the Process Name

Use INSTANA_PROCESS_NAME to set a custom label for infrastructure entity that represents the Python process.

Package Configuration

The Instana package includes a runtime configuration module that manages the configuration of various components.

Note: as the package evolves, more options will be added here

from instana.configurator import config

# To enable tracing context propagation across Asyncio ensure_future and create_task calls
# Default is false
config['asyncio_task_context_propagation']['enabled'] = True

Debugging & More Verbosity

Setting INSTANA_DEBUG to a non nil value will enable extra logging output generally useful for development and troubleshooting.

export INSTANA_DEBUG="true"

See also the General Reference: Environment Variables for Language Sensors

Disabling Automatic instrumentation

This Instana package includes automatic instrumentation that is initialized on package load. This instrumentation provides distributed tracing information to your Instana dashboard. To see the full list of automatic instrumentation, see the Supported Versions document.

You can this disable automatic instrumentation (tracing) by setting the environment variable INSTANA_DISABLE_AUTO_INSTR. This will suppress the loading of instrumentation built-into the sensor.

Kubernetes

In certain scenarios on this platform, the Python sensor may not be able to automatically locate and contact the Instana host agent. To resolve this, see the Configuring Agent Network Access for Kubernetes section in the documentation.

See also:

Frameworks

Django (Manual)

When the AUTOWRAPT_BOOTSTRAP=instana environment variable is set, the Django framework should be automatically detected and instrumented. If for some reason, you prefer to or need to manually instrument Django, you can instead add instana.instrumentation.django.middleware.InstanaMiddleware to your MIDDLEWARE list in settings.py:

import os
import instana

# ... <snip> ...

MIDDLEWARE = [
    'instana.instrumentation.django.middleware.InstanaMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Pyramid

Since: Instana Python Package 1.22.0

The Instana package includes manual support for Pyramid. To add visibility to your Pyramid based application:

  1. Assure that the instana package is added to the requirements.txt and installed in the virtual environment or container
  2. Add import instana to the top of your __init__.py file for your Pyramid application
  3. Add the Instana instrumentation Tween to your configuration
import instana

with Configurator(settings=settings) as config:
    # ...
    config.include('instana.instrumentation.pyramid.tweens')
    # ...

For example:

pyramid

In case you have the pyramid.tweens option set in your production.ini config, make sure that instana.instrumentation.pyramid.tweens.InstanaTweenFactory is the first entry in this list:

pyramid.tweens =
    instana.instrumentation.pyramid.tweens.InstanaTweenFactory
    # other tweens

In a future version of the Instana package, these manual steps will not be required and will happen automatically when Pyramid is detected.

WSGI & ASGI Stacks

The Instana sensor includes WSGI & ASGI middleware that can be added to any compliant stack. This is automated for various stacks but can also be done manually for those we haven't added implicit support for yet.

Once the Instana Python package is installed (via pip install instana), the general usage is:

import instana

from instana.middleware import InstanaWSGIMiddleware
# or
from instana.middleware import InstanaASGIMiddleware

# Wrap the wsgi app in Instana middleware (InstanaWSGIMiddleware)
wsgiapp = InstanaWSGIMiddleware(MyWSGIApplication())

We are working to automate this for all major frameworks but in the meantime, here are some specific quick starts for those we don't have automatic support for yet.

Note: The previous import form of from instana.wsgi import iWSGIMiddleware still works but has been deprecated. Support for that import form will be removed in a future version.

Bottle WSGI

# Import Instana and the Instana WSGI middleware wrapper
import instana
from instana.middleware import InstanaWSGIMiddleware

from bottle import Bottle, run

app = Bottle()

@app.route('/hello')
def hello():
    return "Hello World!"

# Wrap the application with the Instana WSGI Middleware
app = InstanaWSGIMiddleware(app)

# Alternative method for reference
# app = InstanaWSGIMiddleware(bottle.default_app())

run(app, host='localhost', port=8080)

CherryPy WSGI

import cherrypy

# Import Instana and the Instana WSGI middleware wrapper
import instana
from instana.middleware import InstanaWSGIMiddleware

# My CherryPy application
class Root(object):
    @cherrypy.expose
    def index(self):
        return "hello world"

cherrypy.config.update({'engine.autoreload.on': False})
cherrypy.server.unsubscribe()
cherrypy.engine.start()

# Wrap the application with the Instana WSGI Middleware
wsgiapp = InstanaWSGIMiddleware(cherrypy.tree.mount(Root()))

In this example, we use uwsgi as the webserver and booted with:

uwsgi --socket 127.0.0.1:8080 --enable-threads --protocol=http --wsgi-file mycherry.py --callable wsgiapp -H ~/.local/share/virtualenvs/cherrypyapp-C1BUba0z

Where ~/.local/share/virtualenvs/cherrypyapp-C1BUba0z is the path to my local virtualenv from pipenv

Falcon WSGI

The Falcon framework can also be instrumented via the WSGI wrapper as such:

import falcon

# Import Instana and the Instana WSGI middleware wrapper
import instana
from instana.middleware import InstanaWSGIMiddleware

app = falcon.API()

# ...

# Wrap the application with the Instana WSGI Middleware
app = InstanaWSGIMiddleware(app)

Then booting your stack with uwsgi --http :9000 --enable-threads --module=myfalcon.app as an example

gevent Based Applications

Instana supports applications based on gevent versions 1.4 and greater.

If you are manually importing the Instana Python package, make sure that the gevent import and monkey patching happen first.

    from gevent import monkey
    monkey.patch_all()
    import instana # <--- after the gevent monkey patching of stdlib

Before Instana Python Tracer 2.5.0, the gevent-based applications must not use the Activating without code changes method of package activation (that uses the AUTOWRAPT_BOOTSTRAP environment variable). This method doesn't work due to gevent's first-order monkey patching requirements as described earlier. In this case, use the Activating with code changes method.

Starting with Instana Python Tracer 2.5.0, the tracer automatically performs monkey.patch_all() when the AutoTrace webhook or the Activating without code changes method is used. You can fine tune this monkey patching by setting the INSTANA_GEVENT_MONKEY_OPTIONS environment variable. With this comma-separated list, you can specify the modules to include or exclude from monkey pactching as MONKEY OPTIONS to gevent's gevent.monkey.main function. The following examples show options available for customizing modules for monkey patching:

export INSTANA_GEVENT_MONKEY_OPTIONS='--no-socket, --dns, --no-time, --select, --no-ssl'
export INSTANA_GEVENT_MONKEY_OPTIONS='no-socket, dns, no-time, select, no-ssl'
export INSTANA_GEVENT_MONKEY_OPTIONS='no-socket,dns,no-time,select,no-ssl'

If you use Django together with gevent and Instana autotracing, then ensure that you set the DJANGO_SETTINGS_MODULE environment variable before the autotracing starts. For more information about the DJANGO_SETTINGS_MODULE environment variable, see the Django documentation.

If this level of customization is still insufficient, then use the Activating with code changes method of package activation.

Tools

Webservers

uWSGI Webserver

tldr; Make sure enable-threads is enabled for uwsgi.

Threads

This Python instrumentation spawns a lightweight background thread to periodically collect and report process metrics. By default, the GIL and threading is disabled under uWSGI. If you wish to instrument your application running under uWSGI, make sure that you enable threads by passing --enable-threads (or enable-threads = true in ini style). More details in the uWSGI documentation.

uWSGI Example: Command-line

uwsgi --socket 0.0.0.0:5000 --protocol=http -w wsgi -p 4 --enable-threads

uWSGI Example: ini file

[uwsgi]
http = :5000
master = true
processes = 4
enable-threads = true # required

End-user monitoring (EUM)

Instana provides deep end-user monitoring that links server side traces with browser events to give you a complete view from server to browser.

See the end-user monitoring page for more details.

See Also