为 Python 应用程序设置 Azure MonitorSet up Azure Monitor for your Python application

通过与 OpenCensus 集成,Azure Monitor 支持对 Python 应用程序进行分布式跟踪、指标收集和日志记录。Azure Monitor supports distributed tracing, metric collection, and logging of Python applications through integration with OpenCensus. 本文分步介绍设置 OpenCensus for Python 并将监视数据发送到 Azure Monitor 的过程。This article walks you through the process of setting up OpenCensus for Python and sending your monitoring data to Azure Monitor.

先决条件Prerequisites

  • Azure 订阅。An Azure subscription. 如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a Trial before you begin.
  • Python 安装。Python installation. 本文使用 Python 3.7.0,但其他版本在经过轻微的更改后也可能适用。This article uses Python 3.7.0, although other versions will likely work with minor changes. SDK 仅支持 Python v2.7 和 v3.4-v3.7。The SDK only supports Python v2.7 and v3.4-v3.7.
  • 创建 Application Insights 资源Create an Application Insights resource. 系统将针对你的资源为你分配自己的检测密钥 (ikey)。You'll be assigned your own instrumentation key (ikey) for your resource.

检测适用于 Azure Monitor 的 OpenCensus Python SDKInstrument with OpenCensus Python SDK for Azure Monitor

安装 OpenCensus Azure Monitor 导出程序:Install the OpenCensus Azure Monitor exporters:

python -m pip install opencensus-ext-azure

备注

python -m pip install opencensus-ext-azure 命令假定你已为 Python 安装设置了 PATH 环境变量。The python -m pip install opencensus-ext-azure command assumes that you have a PATH environment variable set for your Python installation. 如果尚未配置此变量,则需要提供 Python 可执行文件所在位置的完整目录路径。If you haven't configured this variable, you need to give the full directory path to where your Python executable is located. 结果为如下所示的命令:C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\python.exe -m pip install opencensus-ext-azureThe result is a command like this: C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\python.exe -m pip install opencensus-ext-azure.

SDK 使用三个 Azure Monitor 导出程序将不同类型的遥测数据发送到 Azure Monitor。The SDK uses three Azure Monitor exporters to send different types of telemetry to Azure Monitor. 分别是跟踪、指标和日志。They're trace, metrics, and logs. 有关这些遥测类型的详细信息,请参阅数据平台概述For more information on these telemetry types, see the data platform overview. 按照以下说明通过三个导出程序发送这些遥测类型。Use the following instructions to send these telemetry types via the three exporters.

遥测类型映射Telemetry type mappings

下面是 OpenCensus 提供的导出程序,它映射到会在 Azure Monitor 中出现的遥测类型。Here are the exporters that OpenCensus provides mapped to the types of telemetry that you see in Azure Monitor.

可观测性的支柱Pillar of observability Azure Monitor 中的遥测类型Telemetry type in Azure Monitor 说明Explanation
日志Logs Traces、exceptions、customEventsTraces, exceptions, customEvents 日志遥测、异常遥测、事件遥测Log telemetry, exception telemetry, event telemetry
指标Metrics customMetrics、performanceCounterscustomMetrics, performanceCounters 自定义指标、性能计数器Custom metrics performance counters
跟踪Tracing requests dependenciesRequests dependencies 传入的请求数、传出的请求数Incoming requests, outgoing requests

日志Logs

  1. 首先,让我们生成一些本地日志数据。First, let's generate some local log data.

    import logging
    
    logger = logging.getLogger(__name__)
    
    def valuePrompt():
        line = input("Enter a value: ")
        logger.warning(line)
    
    def main():
        while True:
            valuePrompt()
    
    if __name__ == "__main__":
        main()
    
  2. 代码会持续请求输入值。The code continuously asks for a value to be entered. 对于输入的每个值,将发出一个日志条目。A log entry is emitted for every entered value.

    Enter a value: 24
    24
    Enter a value: 55
    55
    Enter a value: 123
    123
    Enter a value: 90
    90
    
  3. 尽管输入值有助于演示,但最终我们希望向 Azure Monitor 发出日志数据。Although entering values is helpful for demonstration purposes, ultimately we want to emit the log data to Azure Monitor. 将连接字符串直接传递到导出程序。Pass your connection string directly into the exporter. 也可以在环境变量 APPLICATIONINSIGHTS_CONNECTION_STRING 中指定它。Or, you can specify it in an environment variable, APPLICATIONINSIGHTS_CONNECTION_STRING. 根据以下代码示例,修改上一步中的代码:Modify your code from the previous step based on the following code sample:

    import logging
    from opencensus.ext.azure.log_exporter import AzureLogHandler
    
    logger = logging.getLogger(__name__)
    
    # TODO: replace the all-zero GUID with your instrumentation key.
    logger.addHandler(AzureLogHandler(
        connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
    )
    
    def valuePrompt():
        line = input("Enter a value: ")
        logger.warning(line)
    
    def main():
        while True:
            valuePrompt()
    
    if __name__ == "__main__":
        main()
    
  4. 导出程序会将日志数据发送到 Azure Monitor。The exporter sends log data to Azure Monitor. 可在 traces 下找到数据。You can find the data under traces.

    备注

    在此上下文中,tracestracing 不同。In this context, traces isn't the same as tracing. 此处,traces 是指使用 AzureLogHandler 时 Azure Monitor 中会出现的遥测类型。Here, traces refers to the type of telemetry that you'll see in Azure Monitor when you utilize AzureLogHandler. tracing 是指 OpenCensus 中的一种概念,与分布式跟踪相关。But tracing refers to a concept in OpenCensus and relates to distributed tracing.

    备注

    根记录器配置为“警告”级别。The root logger is configured with the level of WARNING. 这意味着如果所发送的任何日志的严重性低于此级别,则其将被忽略,不会发送到 Azure Monitor。That means any logs that you send that have less of a severity are ignored, and in turn, won't be sent to Azure Monitor. 有关详细信息,请参阅这篇文档For more information, see documentation.

  5. 还可以在 extra 关键字参数中通过使用 custom_dimensions 字段向日志消息添加自定义属性。You can also add custom properties to your log messages in the extra keyword argument by using the custom_dimensions field. 这些属性会显示为 Azure Monitor 的 customDimensions 中的键值对。These properties appear as key-value pairs in customDimensions in Azure Monitor.

    备注

    若要使此功能正常运行,需要将字典传递给 custom_dimensions 字段。For this feature to work, you need to pass a dictionary to the custom_dimensions field. 如果传递任何其他类型的参数,记录器会忽略它们。If you pass arguments of any other type, the logger ignores them.

    import logging
    
    from opencensus.ext.azure.log_exporter import AzureLogHandler
    
    logger = logging.getLogger(__name__)
    # TODO: replace the all-zero GUID with your instrumentation key.
    logger.addHandler(AzureLogHandler(
        connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
    )
    
    properties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}
    
    # Use properties in logging statements
    logger.warning('action', extra=properties)
    

配置 Django 应用程序的日志记录Configure logging for Django applications

可以按照上文所述在应用程序代码中为 Django 应用程序显式配置日志记录,也可以在 Django 的日志记录配置中指定日志记录。You can configure logging explicitly in your application code like above for your Django applications, or you can specify it in Django's logging configuration. 此代码可以包含在用于 Django 设置配置的任何文件中。This code can go into whatever file you use for Django settings configuration. 有关如何配置 Django 设置的信息,请参阅 Django 设置For how to configure Django settings, see Django settings. 有关配置记录的详细信息,请参阅 Django 设置For more information on configuring logging, see Django logging.

LOGGING = {
    "handlers": {
        "azure": {
            "level": "DEBUG",
        "class": "opencensus.ext.azure.log_exporter.AzureLogHandler",
            "instrumentation_key": "<your-ikey-here>",
         },
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "stream": sys.stdout,
         },
      },
    "loggers": {
        "logger_name": {"handlers": ["azure", "console"]},
    },
}

请确保所用记录器的名称与在配置中指定的名称相同。Be sure you use the logger with the same name as the one specified in your configuration.

import logging

logger = logging.getLogger("logger_name")
logger.warning("this will be tracked")

发送异常Send exceptions

OpenCensus Python 不会自动跟踪和发送 exception 遥测。OpenCensus Python doesn't automatically track and send exception telemetry. 借助 Python 日志记录库使用异常,可通过 AzureLogHandler 发送它们。They're sent through AzureLogHandler by using exceptions through the Python logging library. 可以像使用普通日志记录时一样添加自定义属性。You can add custom properties just like with normal logging.

import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
# TODO: replace the all-zero GUID with your instrumentation key.
logger.addHandler(AzureLogHandler(
    connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
)

properties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}

# Use properties in exception logs
try:
    result = 1 / 0  # generate a ZeroDivisionError
except Exception:
    logger.exception('Captured an exception.', extra=properties)

由于必须显式记录异常,这取决于用户想要如何记录未处理的异常。Because you must log exceptions explicitly, it's up to the user how they want to log unhandled exceptions. 只要用户显式记录异常遥测,OpenCensus 就不会对用户想要如何执行此操作施加限制。OpenCensus doesn't place restrictions on how a user wants to do this, as long as they explicitly log an exception telemetry.

发送事件Send events

可以使用与发送 trace 遥测完全相同的方式来发送 customEvent 遥测,只是后者应该使用 AzureEventHandlerYou can send customEvent telemetry in exactly the same way that you send trace telemetry except by using AzureEventHandler instead.

import logging

from opencensus.ext.azure.log_exporter import AzureEventHandler

logger = logging.getLogger(__name__)
logger.addHandler(AzureEventHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))
logger.setLevel(logging.INFO)
logger.info('Hello, World!')

采样Sampling

有关在 OpenCensus 中采样的信息,请查看 OpenCensus 中的采样For information on sampling in OpenCensus, take a look at sampling in OpenCensus.

日志关联Log correlation

有关如何使用跟踪上下文数据扩充日志的详细信息,请参阅 OpenCensus Python 日志集成For details on how to enrich your logs with trace context data, see OpenCensus Python logs integration.

修改遥测Modify telemetry

有关在将跟踪的遥测发送到 Azure Monitor 之前如何对其进行修改的详细信息,请参阅 OpenCensus Python 遥测处理器For details on how to modify tracked telemetry before it's sent to Azure Monitor, see OpenCensus Python telemetry processors.

指标Metrics

  1. 首先,让我们生成一些本地指标数据。First, let's generate some local metric data. 我们将创建一个简单的指标,用于跟踪用户选择 Enter 键的次数。We'll create a simple metric to track the number of times the user selects the Enter key.

    from datetime import datetime
    from opencensus.stats import aggregation as aggregation_module
    from opencensus.stats import measure as measure_module
    from opencensus.stats import stats as stats_module
    from opencensus.stats import view as view_module
    from opencensus.tags import tag_map as tag_map_module
    
    stats = stats_module.stats
    view_manager = stats.view_manager
    stats_recorder = stats.stats_recorder
    
    prompt_measure = measure_module.MeasureInt("prompts",
                                               "number of prompts",
                                               "prompts")
    prompt_view = view_module.View("prompt view",
                                   "number of prompts",
                                   [],
                                   prompt_measure,
                                   aggregation_module.CountAggregation())
    view_manager.register_view(prompt_view)
    mmap = stats_recorder.new_measurement_map()
    tmap = tag_map_module.TagMap()
    
    def prompt():
        input("Press enter.")
        mmap.measure_int_put(prompt_measure, 1)
        mmap.record(tmap)
        metrics = list(mmap.measure_to_view_map.get_metrics(datetime.utcnow()))
        print(metrics[0].time_series[0].points[0])
    
    def main():
        while True:
            prompt()
    
    if __name__ == "__main__":
        main()
    
  2. 运行代码时,系统会重复提示你选择 Enter。Running the code repeatedly prompts you to select Enter. 将创建一个指标用于跟踪选择 Enter 的次数。A metric is created to track the number of times Enter is selected. 每次输入都会递增值,并且指标信息将显示在控制台中。With each entry, the value is incremented and the metric information appears in the console. 该信息包括指标更新时的当前值和当前时间戳。The information includes the current value and the current time stamp when the metric was updated.

    Press enter.
    Point(value=ValueLong(5), timestamp=2019-10-09 20:58:04.930426)
    Press enter.
    Point(value=ValueLong(6), timestamp=2019-10-09 20:58:06.570167)
    Press enter.
    Point(value=ValueLong(7), timestamp=2019-10-09 20:58:07.138614)
    
  3. 尽管输入值有助于演示,但最终我们希望向 Azure Monitor 发出指标数据。Although entering values is helpful for demonstration purposes, ultimately we want to emit the metric data to Azure Monitor. 将连接字符串直接传递到导出程序。Pass your connection string directly into the exporter. 也可以在环境变量 APPLICATIONINSIGHTS_CONNECTION_STRING 中指定它。Or, you can specify it in an environment variable, APPLICATIONINSIGHTS_CONNECTION_STRING. 根据以下代码示例,修改上一步中的代码:Modify your code from the previous step based on the following code sample:

    from datetime import datetime
    from opencensus.ext.azure import metrics_exporter
    from opencensus.stats import aggregation as aggregation_module
    from opencensus.stats import measure as measure_module
    from opencensus.stats import stats as stats_module
    from opencensus.stats import view as view_module
    from opencensus.tags import tag_map as tag_map_module
    
    stats = stats_module.stats
    view_manager = stats.view_manager
    stats_recorder = stats.stats_recorder
    
    prompt_measure = measure_module.MeasureInt("prompts",
                                               "number of prompts",
                                               "prompts")
    prompt_view = view_module.View("prompt view",
                                   "number of prompts",
                                   [],
                                   prompt_measure,
                                   aggregation_module.CountAggregation())
    view_manager.register_view(prompt_view)
    mmap = stats_recorder.new_measurement_map()
    tmap = tag_map_module.TagMap()
    
    # TODO: replace the all-zero GUID with your instrumentation key.
    exporter = metrics_exporter.new_metrics_exporter(
        connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
    
    view_manager.register_exporter(exporter)
    
    def prompt():
        input("Press enter.")
        mmap.measure_int_put(prompt_measure, 1)
        mmap.record(tmap)
        metrics = list(mmap.measure_to_view_map.get_metrics(datetime.utcnow()))
        print(metrics[0].time_series[0].points[0])
    
    def main():
        while True:
            prompt()
    
    if __name__ == "__main__":
        main()
    
  4. 导出程序按固定的间隔将指标数据发送到 Azure Monitor。The exporter sends metric data to Azure Monitor at a fixed interval. 默认值为每 15 秒。The default is every 15 seconds. 我们正在跟踪单个指标,因此,在每个间隔将会发送此指标数据及其包含的任何值和时间戳。We're tracking a single metric, so this metric data, with whatever value and time stamp it contains, is sent every interval. 可在 customMetrics 下找到数据。You can find the data under customMetrics.

性能计数器Performance counters

默认情况下,指标导出程序会向 Azure Monitor 发送一组性能计数器。By default, the metrics exporter sends a set of performance counters to Azure Monitor. 可以通过在指标导出程序的构造函数中将 enable_standard_metrics 标志设为 False 来禁用此功能。You can disable this by setting the enable_standard_metrics flag to False in the constructor of the metrics exporter.

...
exporter = metrics_exporter.new_metrics_exporter(
  enable_standard_metrics=False,
  connection_string='InstrumentationKey=<your-instrumentation-key-here>')
...

当前已发送以下性能计数器:These performance counters are currently sent:

  • 可用内存(字节)Available Memory (bytes)
  • CPU 处理器时间(百分比)CPU Processor Time (percentage)
  • 传入请求速率(每秒)Incoming Request Rate (per second)
  • 传入请求平均执行时间(毫秒)Incoming Request Average Execution Time (milliseconds)
  • 进程 CPU 使用率(百分比)Process CPU Usage (percentage)
  • 进程专用字节数(字节)Process Private Bytes (bytes)

你应该能够在 performanceCounters 中看到这些指标。You should be able to see these metrics in performanceCounters. 有关详细信息,请参阅性能计时器For more information, see performance counters.

修改遥测Modify telemetry

如需了解将跟踪的遥测发送到 Azure Monitor 之前如何对其进行修改,请参阅 OpenCensus Python 遥测处理器For information on how to modify tracked telemetry before it's sent to Azure Monitor, see OpenCensus Python telemetry processors.

跟踪Tracing

备注

在 OpenCensus 中,tracing分布式跟踪In OpenCensus, tracing refers to distributed tracing. AzureExporterrequestsdependency 遥测发送到 Azure Monitor。The AzureExporter sends requests and dependency telemetry to Azure Monitor.

  1. 首先,让我们在本地生成一些跟踪数据。First, let's generate some trace data locally. 在 Python IDLE 或所选编辑器中,输入以下代码:In Python IDLE, or your editor of choice, enter the following code:

    from opencensus.trace.samplers import ProbabilitySampler
    from opencensus.trace.tracer import Tracer
    
    tracer = Tracer(sampler=ProbabilitySampler(1.0))
    
    def valuePrompt():
        with tracer.span(name="test") as span:
            line = input("Enter a value: ")
            print(line)
    
    def main():
        while True:
            valuePrompt()
    
    if __name__ == "__main__":
        main()
    
  2. 运行代码时,系统会重复提示你输入值。Running the code repeatedly prompts you to enter a value. 对于每个条目,值会打印到 shell。With each entry, the value is printed to the shell. OpenCensus Python 模块会生成相应的 SpanData 部分。The OpenCensus Python Module generates a corresponding piece of SpanData. OpenCensus 项目将跟踪定义为 span 树The OpenCensus project defines a trace as a tree of spans.

    Enter a value: 4
    4
    [SpanData(name='test', context=SpanContext(trace_id=8aa41bc469f1a705aed1bdb20c342603, span_id=None, trace_options=TraceOptions(enabled=True), tracestate=None), span_id='15ac5123ac1f6847', parent_span_id=None, attributes=BoundedDict({}, maxlen=32), start_time='2019-06-27T18:21:22.805429Z', end_time='2019-06-27T18:21:44.933405Z', child_span_count=0, stack_trace=None, annotations=BoundedList([], maxlen=32), message_events=BoundedList([], maxlen=128), links=BoundedList([], maxlen=32), status=None, same_process_as_parent_span=None, span_kind=0)]
    Enter a value: 25
    25
    [SpanData(name='test', context=SpanContext(trace_id=8aa41bc469f1a705aed1bdb20c342603, span_id=None, trace_options=TraceOptions(enabled=True), tracestate=None), span_id='2e512f846ba342de', parent_span_id=None, attributes=BoundedDict({}, maxlen=32), start_time='2019-06-27T18:21:44.933405Z', end_time='2019-06-27T18:21:46.156787Z', child_span_count=0, stack_trace=None, annotations=BoundedList([], maxlen=32), message_events=BoundedList([], maxlen=128), links=BoundedList([], maxlen=32), status=None, same_process_as_parent_span=None, span_kind=0)]
    Enter a value: 100
    100
    [SpanData(name='test', context=SpanContext(trace_id=8aa41bc469f1a705aed1bdb20c342603, span_id=None, trace_options=TraceOptions(enabled=True), tracestate=None), span_id='f3f9f9ee6db4740a', parent_span_id=None, attributes=BoundedDict({}, maxlen=32), start_time='2019-06-27T18:21:46.157732Z', end_time='2019-06-27T18:21:47.269583Z', child_span_count=0, stack_trace=None, annotations=BoundedList([], maxlen=32), message_events=BoundedList([], maxlen=128), links=BoundedList([], maxlen=32), status=None, same_process_as_parent_span=None, span_kind=0)]
    
  3. 虽然输入值有助于演示,但最终我们希望将 SpanData 发出到 Azure Monitor。Although entering values is helpful for demonstration purposes, ultimately we want to emit SpanData to Azure Monitor. 将连接字符串直接传递到导出程序。Pass your connection string directly into the exporter. 也可以在环境变量 APPLICATIONINSIGHTS_CONNECTION_STRING 中指定它。Or, you can specify it in an environment variable, APPLICATIONINSIGHTS_CONNECTION_STRING. 根据以下代码示例,修改上一步中的代码:Modify your code from the previous step based on the following code sample:

    from opencensus.ext.azure.trace_exporter import AzureExporter
    from opencensus.trace.samplers import ProbabilitySampler
    from opencensus.trace.tracer import Tracer
    
    # TODO: replace the all-zero GUID with your instrumentation key.
    tracer = Tracer(
        exporter=AzureExporter(
            connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000'),
        sampler=ProbabilitySampler(1.0),
    )
    
    def valuePrompt():
        with tracer.span(name="test") as span:
            line = input("Enter a value: ")
            print(line)
    
    def main():
        while True:
            valuePrompt()
    
    if __name__ == "__main__":
        main()
    
  4. 现在,当你运行 Python 脚本时,系统仍会提示你输入值,但只有该值输出到 shell 中。Now when you run the Python script, you should still be prompted to enter values, but only the value is being printed in the shell. 会将创建的 SpanData 发送到 Azure Monitor。The created SpanData is sent to Azure Monitor. 可在 dependencies 下找到发出的 span 数据。You can find the emitted span data under dependencies. 有关传出请求的详细信息,请参阅 OpenCensus Python 依赖项For more information about outgoing requests, see OpenCensus Python dependencies. 有关传入请求的详细信息,请参阅 OpenCensus Python 请求For more information on incoming requests, see OpenCensus Python requests.

采样Sampling

有关在 OpenCensus 中采样的信息,请查看 OpenCensus 中的采样For information on sampling in OpenCensus, take a look at sampling in OpenCensus.

跟踪关联Trace correlation

有关跟踪数据中遥测关联的详细信息,请参阅 OpenCensus Python 遥测关联For more information on telemetry correlation in your trace data, take a look at OpenCensus Python telemetry correlation.

修改遥测Modify telemetry

有关在将跟踪的遥测发送到 Azure Monitor 之前如何对其进行修改的详细信息,请参阅 OpenCensus Python 遥测处理器For more information on how to modify tracked telemetry before it's sent to Azure Monitor, see OpenCensus Python telemetry processors.

配置 Azure Monitor 导出程序Configure Azure Monitor exporters

如图所示,有三个不同的 Azure Monitor 导出程序支持 OpenCensus。As shown, there are three different Azure Monitor exporters that support OpenCensus. 每个导出程序都将不同类型的遥测发送到 Azure Monitor。Each one sends different types of telemetry to Azure Monitor. 要查看每个导出程序发送的遥测类型,请参阅以下列表。To see what types of telemetry each exporter sends, see the following list.

每个导出程序都接受通过构造函数传递的相同配置参数。Each exporter accepts the same arguments for configuration, passed through the constructors. 可在此处查看有关每个导出程序的详细信息:You can see details about each one here:

  • connection_string:用于连接到 Azure Monitor 资源的连接字符串。connection_string: The connection string used to connect to your Azure Monitor resource. 其优先级高于 instrumentation_keyTakes priority over instrumentation_key.
  • enable_standard_metrics:用于 AzureMetricsExporterenable_standard_metrics: Used for AzureMetricsExporter. 指示导出程序将性能计数器指标自动发送到 Azure Monitor。Signals the exporter to send performance counter metrics automatically to Azure Monitor. 默认为 TrueDefaults to True.
  • export_interval:用于指定导出频率(秒)。export_interval: Used to specify the frequency in seconds of exporting.
  • instrumentation_key:用于连接到 Azure Monitor 资源的检测密钥。instrumentation_key: The instrumentation key used to connect to your Azure Monitor resource.
  • logging_sampling_rate:用于 AzureLogHandlerlogging_sampling_rate: Used for AzureLogHandler. 为导出日志提供采样率 [0,1.0]。Provides a sampling rate [0,1.0] for exporting logs. 默认值为 1.0。Defaults to 1.0.
  • max_batch_size:指定一次性导出的最大遥测大小。max_batch_size: Specifies the maximum size of telemetry that's exported at once.
  • proxies:指定用于将数据发送到 Azure Monitor 的代理序列。proxies: Specifies a sequence of proxies to use for sending data to Azure Monitor. 有关详细信息,请参阅代理For more information, see proxies.
  • storage_path:指向本地存储文件夹(未发送的遥测)所在位置的路径。storage_path: A path to where the local storage folder exists (unsent telemetry). opencensus-ext-azure v1.0.3 起,默认路径为 OS 临时目录 + opencensus-python + your-ikeyAs of opencensus-ext-azure v1.0.3, the default path is the OS temp directory + opencensus-python + your-ikey. 在 v1.0.3 之前,默认路径为 $USER + .opencensus + .azure + python-file-namePrior to v1.0.3, the default path is $USER + .opencensus + .azure + python-file-name.

使用查询查看数据View your data with queries

可以通过“日志(分析)”选项卡查看从应用程序发送的遥测数据。You can view the telemetry data that was sent from your application through the Logs (Analytics) tab.

红色框中选定“日志(分析)”的概述窗格的屏幕截图

在“活动”下的列表中:In the list under Active:

  • 对于使用 Azure Monitor 跟踪导出程序发送的遥测,传入请求在 requests 下显示。For telemetry sent with the Azure Monitor trace exporter, incoming requests appear under requests. 传出或进程内请求在 dependencies 下显示。Outgoing or in-process requests appear under dependencies.
  • 对于使用 Azure Monitor 指标导出程序发送的遥测,发送的指标在 customMetrics 下显示。For telemetry sent with the Azure Monitor metrics exporter, sent metrics appear under customMetrics.
  • 对于使用 Azure Monitor 日志导出程序发送的遥测,日志在 traces 下显示。For telemetry sent with the Azure Monitor logs exporter, logs appear under traces. 异常在 exceptions 下显示。Exceptions appear under exceptions.

有关如何使用查询和日志的更多详细信息,请参阅 Azure Monitor 中的日志For more detailed information about how to use queries and logs, see Logs in Azure Monitor.

了解有关 OpenCensus for Python 的详细信息Learn more about OpenCensus for Python

后续步骤Next steps

警报Alerts

  • 可用性测试:创建测试来确保站点在 Web 上可见。Availability tests: Create tests to make sure your site is visible on the web.
  • 智能诊断:这些测试可自动运行,因此不需要进行任何设置。Smart diagnostics: These tests run automatically, so you don't have to do anything to set them up. 它们会告诉你应用是否具有异常的失败请求速率。They tell you if your app has an unusual rate of failed requests.
  • 指标警报:设置警报以在某个指标超过阈值时发出警告。Metric alerts: Set alerts to warn you if a metric crosses a threshold. 可以在编码到应用中的自定义指标中设置它们。You can set them on custom metrics that you code into your app.