使用 OpenCensus Python 跟踪传入请求

注意

OpenCensus Python SDK 已弃用,但 Microsoft 会提供对它的支持,直至 2024 年 9 月 30 日停用它。 我们现在推荐基于 OpenTelemetry 的 Python 产品/服务并提供迁移指南

OpenCensus Python 及其集成会收集传入请求数据。 可以跟踪发送到基于常用 Web 框架 Django、Flask、Pyramid 构建的 Web 应用程序的传入请求数据。 Application Insights 以 requests 遥测数据的形式接收数据。

首先,使用最新版 OpenCensus Python SDK 检测 Python 应用程序。

跟踪 Django 应用程序

  1. PyPI 下载并安装 opencensus-ext-django。 使用 django 中间件检测应用程序。 系统会跟踪发送到 Django 应用程序的传入请求。

  2. opencensus.ext.django.middleware.OpencensusMiddleware 添加到 settings.py 文件中的 MIDDLEWARE 下。

    MIDDLEWARE = (
        ...
        'opencensus.ext.django.middleware.OpencensusMiddleware',
        ...
    )
    
  3. 确保已在 settings.py 中的 OPENCENSUS 下正确配置 AzureExporter。 对于来自不想要跟踪的 URL 的请求,请将其添加到 EXCLUDELIST_PATHS 中。

    OPENCENSUS = {
        'TRACE': {
            'SAMPLER': 'opencensus.trace.samplers.ProbabilitySampler(rate=1)',
            'EXPORTER': '''opencensus.ext.azure.trace_exporter.AzureExporter(
                connection_string="InstrumentationKey=<your-ikey-here>"
            )''',
            'EXCLUDELIST_PATHS': ['https://example.com'],  <--- These sites will not be traced if a request is sent to it.
        }
    }
    

可以在 Azure Monitor OpenCensus Python 示例存储库中找到 Django 示例应用程序。

跟踪 Flask 应用程序

  1. PyPI 下载并安装 opencensus-ext-flask。 使用 flask 中间件检测应用程序。 系统会跟踪发送到 Flask 应用程序的传入请求。

    
    from flask import Flask
    from opencensus.ext.azure.trace_exporter import AzureExporter
    from opencensus.ext.flask.flask_middleware import FlaskMiddleware
    from opencensus.trace.samplers import ProbabilitySampler
    
    app = Flask(__name__)
    middleware = FlaskMiddleware(
        app,
        exporter=AzureExporter(connection_string="InstrumentationKey=<your-ikey-here>"),
        sampler=ProbabilitySampler(rate=1.0),
    )
    
    @app.route('/')
    def hello():
        return 'Hello World!'
    
    if __name__ == '__main__':
        app.run(host='localhost', port=8080, threaded=True)
    
    
  2. 你也可通过 app.config 配置 flask 应用程序。 对于来自不想要跟踪的 URL 的请求,请将其添加到 EXCLUDELIST_PATHS 中。

    app.config['OPENCENSUS'] = {
        'TRACE': {
            'SAMPLER': 'opencensus.trace.samplers.ProbabilitySampler(rate=1.0)',
            'EXPORTER': '''opencensus.ext.azure.trace_exporter.AzureExporter(
                connection_string="InstrumentationKey=<your-ikey-here>",
            )''',
            'EXCLUDELIST_PATHS': ['https://example.com'],  <--- These sites will not be traced if a request is sent to it.
        }
    }
    

    注意

    要在 Docker 环境中在 uWSGI 下运行 Flask,必须首先将 lazy-apps = true 添加到 uWSGI 配置文件 (uwsgi.ini)。 有关详细信息,请参阅问题说明

可以在 Azure Monitor OpenCensus Python 示例存储库中找到跟踪请求的 Django 示例应用程序。

跟踪 Pyramid 应用程序

  1. PyPI 下载并安装 opencensus-ext-django。 使用 pyramid 中间件检测应用程序。 系统会跟踪发送到 Pyramid 应用程序的传入请求。

    def main(global_config, **settings):
        config = Configurator(settings=settings)
    
        config.add_tween('opencensus.ext.pyramid'
                         '.pyramid_middleware.OpenCensusTweenFactory')
    
  2. 可以直接在代码中配置 pyramid 中间件。 对于来自不想要跟踪的 URL 的请求,请将其添加到 EXCLUDELIST_PATHS 中。

    settings = {
        'OPENCENSUS': {
            'TRACE': {
                'SAMPLER': 'opencensus.trace.samplers.ProbabilitySampler(rate=1.0)',
                'EXPORTER': '''opencensus.ext.azure.trace_exporter.AzureExporter(
                    connection_string="InstrumentationKey=<your-ikey-here>",
                )''',
                'EXCLUDELIST_PATHS': ['https://example.com'],  <--- These sites will not be traced if a request is sent to it.
            }
        }
    }
    config = Configurator(settings=settings)
    

跟踪 FastAPI 应用程序

  1. 需要以下依赖项:

  2. PyPI 下载并安装 opencensus-ext-fastapi

    pip install opencensus-ext-fastapi

  3. 使用 fastapi 中间件检测应用程序。

    from fastapi import FastAPI
    from opencensus.ext.fastapi.fastapi_middleware import FastAPIMiddleware
    
    app = FastAPI(__name__)
    app.add_middleware(FastAPIMiddleware)
    
    @app.get('/')
    def hello():
        return 'Hello World!'
    
  4. 运行应用程序。 应自动跟踪对 FastAPI 应用程序进行的调用。 遥测应直接记录到 Azure Monitor。

后续步骤