为 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 will walk 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, though other versions will likely work with minor changes. SDK 仅支持 Python 2.7、3.4-3.7。The SDK only supports Python v2.7, v3.4-v3.7.
  • 创建 Application Insights 资源Create an Application Insights resource. 系统将针对你的资源为你分配自己的检测密钥 (ikey)。You will 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

有关包和集成的完整列表,请参阅 OpenCensus 包For a full list of packages and integrations, see OpenCensus packages.

备注

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: 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 will 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 will continuously ask 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. 将连接字符串直接传入导出程序,也可以在 APPLICATIONINSIGHTS_CONNECTION_STRING 环境变量中指定它。Pass your connection string directly into the exporter, 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 will send log data to Azure Monitor. 可在 traces 下找到数据。You can find the data under traces.

    备注

    此上下文中的 tracesTracing 不同。traces in this context is not the same as Tracing. traces 指在利用 AzureLogHandler 时将在 Azure Monitor 中看到的遥测的类型。traces refers to the type of telemetry that you will see in Azure Monitor when utilizing the AzureLogHandler. Tracing 是 OpenCensus 中的一个概念,与分布式跟踪相关。Tracing refers to a concept in OpenCensus and relates to distributed tracing.

    备注

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

  5. 还可使用 custom_dimensions 字段在 extra 关键字参数中将自定义属性添加到日志消息中。You can also add custom properties to your log messages in the extra keyword argument using the custom_dimensions field. 这些属性将作为键值对在 Azure Monitor 的 customDimensions 中显示。These will 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 will ignore 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 设置,参阅 Django 日志记录了解有关配置日志记录的详细信息。See Django settings for how to configure Django settings and Django logging for more information on configuring 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 are using 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")

发送异常Sending exceptions

OpenCensus Python 不会自动跟踪和发送 exception 遥测。OpenCensus Python does not automatically track and send exception telemetry. 借助 Python 日志记录库使用异常,可通过 AzureLogHandler 发送它们。They are sent through the 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)

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

发送事件Sending Events

可以使用与发送 trace 遥测完全相同的方式来发送 customEvent 遥测,只是后者应该使用 AzureEventHandlerYou can send customEvent telemetry in exactly the same way you would send trace telemetry except using the 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 is 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 presses Enter.

    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 will repeatedly prompt you to press Enter. 创建一个指标以跟踪按下 Enter 的次数。A metric is created to track the number of times Enter is pressed. 对于每次输入,该值将递增,并且指标信息将在控制台中显示。With each entry, the value will be incremented and the metric information will be displayed 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. 将连接字符串直接传入导出程序,也可以在 APPLICATIONINSIGHTS_CONNECTION_STRING 环境变量中指定它。Pass your connection string directly into the exporter, 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 will send 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, will be sent every interval. 可在 customMetrics 下找到数据。You can find the data under customMetrics.

性能计数器Performance counters

默认情况下,指标导出程序将向 Azure Monitor 发送一组性能计数器。By default, the metrics exporter will send 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>')
...

下面列出了当前已发送的性能计数器:Below is a list of performance counters that 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 details on how to modify tracked telemetry before it is sent to Azure Monitor, see OpenCensus Python telemetry processors.

跟踪Tracing

备注

OpenCensus 中的 Tracing分布式跟踪Tracing in OpenCensus 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 will repeatedly prompt you to enter a value. 每次输入时,值都会输出到 shell,且 OpenCensus Python 模块将生成相应的 SpanData 块。With each entry, the value will be printed to the shell, and the OpenCensus Python Module will generate 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. 尽管输入值有助于演示,但最终我们希望向 Azure Monitor 发出 SpanDataAlthough entering values is helpful for demonstration purposes, ultimately we want to emit the SpanData to Azure Monitor. 将连接字符串直接传入导出程序,也可以在 APPLICATIONINSIGHTS_CONNECTION_STRING 环境变量中指定它。Pass your connection string directly into the exporter, 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 will be sent to Azure Monitor. 可在 dependencies 下找到发出的 span 数据。You can find the emitted span data under dependencies. 有关传出请求的更多详细信息,请参阅 OpenCensus Python 依赖项For more details on outgoing requests, see OpenCensus Python dependencies. 有关传入请求的更多详细信息,请参阅 OpenCensus Python 请求For more details 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 details on telemetry correlation in your trace data, take a look at OpenCensus Python telemetry correlation.

修改遥测Modify telemetry

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

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

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

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

  1. connection_string - 用于连接到 Azure Monitor 资源的连接字符串。connection_string - The connection string used to connect to your Azure Monitor resource. 其优先级高于 instrumentation_keyTakes priority over instrumentation_key.
  2. 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.
  3. export_interval - 用于指定导出频率(秒)。export_interval - Used to specify the frequency in seconds of exporting.
  4. instrumentation_key - 用于连接到 Azure Monitor 资源的检测密钥。instrumentation_key - The instrumentation key used to connect to your Azure Monitor resource.
  5. 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.
  6. max_batch_size - 指定一次性导出的最大遥测大小。max_batch_size - Specifies max size of telemetry that are exported at once.
  7. proxies - 指定用于将数据发送到 Azure Monitor 的代理序列。proxies - Specifies a sequence of proxies to use for sending data to Azure Monitor. 请参阅代理了解更多详细信息。See proxies for more details.
  8. storage_path - 指向本地存储文件夹(未发送的遥测)所在位置的路径。storage_path - A path to where the local storage folder exists (unsent telemetry). opencensus-ext-azure 1.0.3 起,默认路径为 os 临时目录 + opencensus-python + your-ikeyAs of opencensus-ext-azure v1.0.3, default path is the os temp directory + opencensus-python + your-ikey. 对于 1.0.3 之前的版本,默认路径为 $USER + .opencensus + .azure + python-file-nameFor pre v1.0.3, 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.