設定 Python 應用程式的 Azure 監視器

注意

OpenCensus Python SDK 已被取代,但 Microsoft 支援它,直到 2024 年 9 月 30 日淘汰為止。 我們現在建議 使用以 OpenTelemetry 為基礎的 Python 供應專案 ,並提供 移轉指引

Azure 監視器支援 Python 應用程式的分散式追蹤、計量收集和記錄。

Microsoft 支援的 Python 應用程式追蹤和匯出資料的解決方案,是利用透過 Azure 監視器匯出工具OpenCensus Python SDK

Microsoft 不建議使用任何其他適用于 Python 的遙測 SDK 作為遙測解決方案,因為它們不受支援。

OpenCensus 正聚集到 OpenTelemetry。 雖然 OpenTelemetry 逐漸成熟,我們還是會繼續建議使用 OpenCensus。

必要條件

您需要 Azure 訂用帳戶。 如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

注意

針對檢測金鑰擷取的支援將在 2025 年 3 月 31 日結束。 檢測金鑰擷取將會繼續運作,但我們將不再提供該功能的更新或支援。 轉換至連接字串以利用新功能

OpenCensus Python SDK 簡介

OpenCensus 是一組開放原始碼程式庫,可允許收集分散式追蹤、計量和記錄遙測。 使用 Azure 監視器匯出工具,即可將此收集的遙測傳送至 Application Insights。 本文會逐步引導您完成設定適用於 Python 的 OpenCensus 和 Azure 監視器匯出工具,並將監視資料傳送至 Azure 監視器的程序。

使用 OpenCensus Python SDK 和 Azure 監視器匯出工具進行檢測

安裝 OpenCensus Azure 監視器匯出工具:

python -m pip install opencensus-ext-azure

SDK 會使用三個 Azure 監視器匯出工具,將不同類型的遙測傳送至 Azure 監視器。 分別是 tracemetricslogs。 如需這些遙測類型的詳細資訊,請參閱資料平台概觀。 使用下列指示,透過這三個匯出工具傳送這些遙測類型。

遙測類型對應

OpenCensus 會將下列匯出工具對應至您在 Azure 監視器中看到的遙測類型。

可檢視性的要素 Azure 監視器中的遙測類型 說明
記錄 追蹤、例外狀況、customEvents 記錄遙測、例外狀況遙測、事件遙測
計量 customMetrics、performanceCounters 自訂計量效能計數器
追蹤 要求相依性 連入要求、傳出要求

記錄

  1. 首先,讓我們產生一些本機記錄資料。

    
    import logging
    
    logger = logging.getLogger(__name__)
    
    def main():
        """Generate random log data."""
        for num in range(5):
            logger.warning(f"Log Entry - {num}")
    
    if __name__ == "__main__":
        main()
    
  2. 系統會針對範圍中的每個數位發出記錄專案。

    Log Entry - 0
    Log Entry - 1
    Log Entry - 2
    Log Entry - 3
    Log Entry - 4
    
  3. 我們想要查看此記錄資料至 Azure 監視器。 您可以在環境變數 APPLICATIONINSIGHTS_CONNECTION_STRING 中指定它。 您也可以將connection_string直接傳遞至 AzureLogHandler ,但不應該將連接字串新增至版本控制。

    APPLICATIONINSIGHTS_CONNECTION_STRING=<appinsights-connection-string>
    

    我們建議使用連接字串來具現化用來將遙測傳送至 Application Insights 的匯出工具。 根據下列程式碼範例,修改得自上一個步驟的程式碼:

    import logging
    from opencensus.ext.azure.log_exporter import AzureLogHandler
    
    logger = logging.getLogger(__name__)
    logger.addHandler(AzureLogHandler())
    
    # Alternatively manually pass in the connection_string
    # logger.addHandler(AzureLogHandler(connection_string=<appinsights-connection-string>))
    
    """Generate random log data."""
    for num in range(5):
        logger.warning(f"Log Entry - {num}")
    
  4. 匯出工具會將記錄資料傳送至 Azure 監視器。 您可以在 traces 底下找到該資料。

    在此內容中,tracestracing 不同。 在這裡, traces 指的是使用 AzureLogHandler 時,您在 Azure 監視器中看到的遙測類型。 但是 tracing 是指 OpenCensus 中的概念,且與分散式追蹤有關。

    注意

    根記錄器會設定為 warning 層級。 這表示您傳送且嚴重性較低的任何記錄都會遭到忽略,而且不會傳送至 Azure 監視器。 如需詳細資訊,請參閱記錄文件

  5. 您也可使用 extra 欄位,在 custom_dimensions 關鍵字引數中將自訂屬性新增至記錄訊息。 在 Azure 監視器的 customDimensions 中,這些屬性會以索引鍵/值組的形式顯示。

    注意

    若要讓此功能運作,您必須將字典傳遞至 custom_dimensions 欄位。 如果您傳遞任何其他類型的引數,記錄器會將其忽略。

    import logging
    
    from opencensus.ext.azure.log_exporter import AzureLogHandler
    
    logger = logging.getLogger(__name__)
    logger.addHandler(AzureLogHandler())
    # Alternatively manually pass in the connection_string
    # logger.addHandler(AzureLogHandler(connection_string=<appinsights-connection-string>))
    
    properties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}
    
    # Use properties in logging statements
    logger.warning('action', extra=properties)
    

注意

在使用 Application Insights 檢測的過程中,我們會收集診斷資料並且傳送給 Microsoft。 此資料可協助我們執行及改善 Application Insights。 您可以選擇停用非必要的資料收集。 若要深入了解,請參閱 Azure Application Insights 中的 Statsbeat

設定 Django 應用程式的記錄

您可針對 Django 應用程式在前述的應用程式程式碼中明確設定記錄,也可以在 Django 的記錄組態中指定記錄。 此程式碼可以進入您用於 Django 網站設定設定的任何檔案,通常是 settings.py

如需進行 Django 設定的相關資訊,請參閱 Django 設定。 如需如何設定記錄的詳細資訊,請參閱 Django 記錄

LOGGING = {
    "handlers": {
        "azure": {
            "level": "DEBUG",
            "class": "opencensus.ext.azure.log_exporter.AzureLogHandler",
            "connection_string": "<appinsights-connection-string>",
        },
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "stream": sys.stdout,
        },
      },
    "loggers": {
        "logger_name": {"handlers": ["azure", "console"]},
    },
}

請務必使用與組態中指定的記錄器名稱相同的記錄器。

# views.py

import logging
from django.shortcuts import request

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

傳送例外狀況

OpenCensus Python 不會自動追蹤和傳送 exception 遙測。 系統會透過 Python 記錄程式庫,使用例外狀況透過 AzureLogHandler 加以傳送。 您可以新增自訂屬性,就如同處理一般記錄一樣。

import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
logger.addHandler(AzureLogHandler())
# Alternatively, manually pass in the connection_string
# logger.addHandler(AzureLogHandler(connection_string=<appinsights-connection-string>))

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)

因為您必須明確地記錄例外狀況,所以您可自己決定要如何記錄未處理的例外狀況。 OpenCensus 不會限制進行此記錄的方式,但您必須明確記錄例外狀況遙測。

傳送事件

除了改為使用 AzureEventHandler 之外,您可以使用與傳送 trace 遙測完全相同的方式傳送 customEvent 遙測。

import logging
from opencensus.ext.azure.log_exporter import AzureEventHandler

logger = logging.getLogger(__name__)
logger.addHandler(AzureEventHandler())
# Alternatively manually pass in the connection_string
# logger.addHandler(AzureEventHandler(connection_string=<appinsights-connection-string>))

logger.setLevel(logging.INFO)
logger.info('Hello, World!')

取樣

如需如何在 OpenCensus 中取樣的相關資訊,請參閱 OpenCensus 中的取樣

記錄相互關聯

如需如何使用追蹤內容資料來擴充記錄的相關資訊,請參閱 OpenCensus Python 記錄整合

修改遙測

如需如何先修改所追蹤的遙測再將其傳送至 Azure 監視器的詳細資訊,請參閱 OpenCensus Python 遙測處理器

計量

OpenCensus.stats 支援四種彙總方法,但是提供 Azure 監視器的部分支援:

  • 計數:測量點數目的計數。 此值為累積值,只能夠增加並且只能在重新啟動時重設為 0。
  • 總和:測量點的總和。 此值為累積值,只能夠增加並且只能在重新啟動時重設為 0。
  • LastValue:保留最後一筆記錄的值並捨棄其他所有項目。
  • 分佈:Azure 匯出工具不支援測量點的長條圖分佈。

計數彙總範例

  1. 首先,讓我們產生一些本機計量資料。 我們會建立計量來追蹤使用者選取 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 main():
        for _ in range(4):
            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])
    
    if __name__ == "__main__":
        main()
    
  2. 系統會建立計量來追蹤多次。 隨著每次輸入,值會遞增,而且計量資訊會顯示在主控台中。 此資訊包括目前的值,以及計量更新當時的時間戳記。

    Point(value=ValueLong(5), timestamp=2019-10-09 20:58:04.930426)
    Point(value=ValueLong(6), timestamp=2019-10-09 20:58:05.170167)
    Point(value=ValueLong(7), timestamp=2019-10-09 20:58:05.438614)
    Point(value=ValueLong(7), timestamp=2019-10-09 20:58:05.834216)
    
  3. 輸入值對於示範有所幫助,但我們還是想要將計量資料發給 Azure 監視器。 將連接字串直接傳遞至匯出工具。 或者,您可以在環境變數 APPLICATIONINSIGHTS_CONNECTION_STRING 中指定。 我們建議使用連接字串來具現化用來將遙測傳送至 Application Insights 的匯出工具。 根據下列程式碼範例,修改得自上一個步驟的程式碼:

    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()
    
    exporter = metrics_exporter.new_metrics_exporter()
    # Alternatively manually pass in the connection_string
    # exporter = metrics_exporter.new_metrics_exporter(connection_string='<appinsights-connection-string>')
    
    view_manager.register_exporter(exporter)
    
    def main():
        for _ in range(10):
            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])
    
    if __name__ == "__main__":
        main()
    
  4. 匯出工具會以固定間隔將計量資料傳送至 Azure 監視器。 您必須將此值設定為 60 秒,因為 Application Insights 後端假設計量點的匯總間隔為 60 秒。 我們追蹤的是單一計量,因此此計量資料 (包含其內含的任何值和時間戳記) 會在每個間隔時傳送。 資料是累積的、只能增加,並在重新開機時重設為 0。

    您可以在 customMetrics 之下找到資料,但 customMetrics 屬性 valueCountvalueSumvalueMinvalueMaxvalueStdDev 並未有效使用。

在計量中設定自訂維度

OpenCensus Python SDK 可讓您使用 tags 將自訂維度新增至計量遙測,這像是索引鍵/值組的字典。

  1. 將您想要使用的標記插入標記對應中。 標記對應就像是您可以使用的所有可用標記的一種「集區」。

    ...
    tmap = tag_map_module.TagMap()
    tmap.insert("url", "http://example.com")
    ...
    
  2. 針對特定 View,指定透過標記索引鍵記錄計量時要使用的標記。

    ...
    prompt_view = view_module.View("prompt view",
                                "number of prompts",
                                ["url"], # <-- A sequence of tag keys used to specify which tag key/value to use from the tag map
                                prompt_measure,
                                aggregation_module.CountAggregation())
    ...
    
  3. 請務必在測量對應中記錄時使用標記對應。 在 View 中指定的標記索引鍵,必須在用來記錄的標記對應中找到。

    ...
    mmap = stats_recorder.new_measurement_map()
    mmap.measure_int_put(prompt_measure, 1)
    mmap.record(tmap) # <-- pass the tag map in here
    ...
    
  4. customMetrics 資料表下,使用 prompt_view 發出的所有計量記錄都有自訂維度 {"url":"http://example.com"}

  5. 若要使用相同的索引鍵產生具有不同值的標記,請為其建立新的標記對應。

    ...
    tmap = tag_map_module.TagMap()
    tmap2 = tag_map_module.TagMap()
    tmap.insert("url", "http://example.com")
    tmap2.insert("url", "https://www.wikipedia.org/wiki/")
    ...
    

效能計數器

根據預設,計量匯出工具會將一組效能計數器傳送至 Azure 監視器。 若要停用此功能,您可以在計量匯出工具的建構函式中將 enable_standard_metrics 旗標設定為 False

...
exporter = metrics_exporter.new_metrics_exporter(
  enable_standard_metrics=False,
  )
...

目前已傳送下列效能計數器:

  • 可用的記憶體 (位元組)
  • CPU 處理器時間 (百分比)
  • 連入要求速率 (每秒)
  • 連入要求平均執行時間 (毫秒)
  • 處理序 CPU 使用量 (百分比)
  • 處理序私用位元組 (位元組)

您應該能夠在 performanceCounters 中看到這些計量。 如需詳細資訊,請參閱效能計數器

修改遙測

如需如何先修改所追蹤的遙測再將其傳送至 Azure 監視器的詳細資訊,請參閱 OpenCensus Python 遙測處理器

追蹤

注意

OpenCensus 中的 tracing 是指分散式追蹤AzureExporter 參數會將 requestsdependency 遙測傳送至 Azure 監視器。

  1. 首先,讓我們在本機產生一些追蹤資料。 在 Python IDLE 或您選擇的編輯器中,輸入下列程式碼:

    from opencensus.trace.samplers import ProbabilitySampler
    from opencensus.trace.tracer import Tracer
    
    tracer = Tracer(sampler=ProbabilitySampler(1.0))
    
    def main():
        with tracer.span(name="test") as span:
            for value in range(5):
                print(value)
    
    
    if __name__ == "__main__":
        main()
    
  2. 每次輸入,值會列印至殼層。 OpenCensus Python 模組會產生 SpanData 的對應片段。 OpenCensus 專案會將追蹤定義為範圍樹狀結構

    0
    [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)]
    1
    [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)]
    2
    [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 監視器。 將連接字串直接傳遞至匯出工具。 或者,您可以在環境變數 APPLICATIONINSIGHTS_CONNECTION_STRING 中指定。 我們建議使用連接字串來具現化用來將遙測傳送至 Application Insights 的匯出工具。 根據下列程式碼範例,修改得自上一個步驟的程式碼:

    from opencensus.ext.azure.trace_exporter import AzureExporter
    from opencensus.trace.samplers import ProbabilitySampler
    from opencensus.trace.tracer import Tracer
    
    tracer = Tracer(
        exporter=AzureExporter(),
        sampler=ProbabilitySampler(1.0),
    )
    # Alternatively manually pass in the connection_string
    # exporter = AzureExporter(
    #   connection_string='<appinsights-connection-string>',
    #   ...
    # )
    
    def main():
        with tracer.span(name="test") as span:
            for value in range(5):
                print(value)
    
    if __name__ == "__main__":
        main()
    
  4. 現在當您執行 Python 腳本時,只會在殼層中列印值。 建立的 SpanData 會傳送至 Azure 監視器。 您可以在 dependencies 底下找到發出的範圍資料。

    如需連出要求的詳細資訊,請參閱 OpenCensus Python 相依性。 如需連入要求的詳細資訊,請參閱 OpenCensus Python 要求

取樣

如需如何在 OpenCensus 中取樣的相關資訊,請參閱 OpenCensus 中的取樣

追蹤相互關聯

如需追蹤資料中遙測相互關聯的詳細資訊,請參閱 OpenCensus Python 遙測相互關聯

修改遙測

如需如何先修改所追蹤的遙測再將其傳送至 Azure 監視器的詳細資訊,請參閱 OpenCensus Python 遙測處理器

設定 Azure 監視器匯出工具

如下所示,有三個不同的 Azure 監視器匯出工具支援 OpenCensus。 每一個匯出工具都會將不同類型的遙測傳送至 Azure 監視器。 若要查看每個匯出工具傳送的遙測類型,請參閱下表。

每個匯出工具都接受設定的相同引數,並透過建構函式傳遞。 您可以在此看到每一個匯出工具的相關資料:

匯出工具遙測 描述
connection_string 用於連線至您的 Azure 監視器資源的連接字串。 優先於 instrumentation_key
credential Azure Active Directory 驗證所使用的認證類別。 請參閱後續的「驗證」一節。
enable_standard_metrics 用於 AzureMetricsExporter。 提示匯出工具自動將效能計數器計量傳送至 Azure 監視器。 預設值為 True
export_interval 用於指定匯出的頻率 (以秒為單位)。 預設值為 15s。 針對計量,您必須將其設定為 60 秒,否則計量匯總在計量總管中沒有意義。
grace_period 用於指定匯出工具關閉的逾時 (以秒為單位)。 預設值為 5s
instrumentation_key 用於連線至您的 Azure 監視器資源的檢測金鑰。
logging_sampling_rate 用於 AzureLogHandlerAzureEventHandler。 提供匯出記錄/事件的取樣率 [0,1.0]。 預設值為 1.0
max_batch_size 指定一次匯出的遙測大小上限。
proxies 指定要用來將資料傳送至 Azure 監視器的 Proxy 序列。 如需詳細資訊,請參閱 Proxy
storage_path 本機儲存體資料夾存在的路徑 (未傳送遙測)。 從 opencensus-ext-azure v1.0.3 開始,預設路徑是 OS 暫存目錄 + opencensus-python + your-ikey。 在 v1.0.3 之前,預設路徑是 $USER + .opencensus + .azure + python-file-name
timeout 指定將遙測傳送至擷取服務的網路逾時 (以秒為單位)。 預設值為 10s

與 Azure Functions 整合

若要在 Azure Functions 環境中擷取自訂遙測,請使用 OpenCensus Python Azure Functions 延伸模組。 如需詳細資訊,請參閱 Azure Functions Python 開發人員指南

驗證 (預覽)

注意

opencensus-ext-azure v1.1b0 開始提供驗證功能。

每個 Azure 監視器匯出工具都支援透過 OAuth 驗證和 Azure Active Directory 安全地傳送遙測承載的設定。 如需詳細資訊,請參閱驗證文件

使用查詢來檢視資料

您可以透過 [記錄 (分析)] 索引標籤來檢視從應用程式傳來的遙測資料。

[概觀] 窗格的螢幕擷取畫面,其中已選取 [記錄 (分析)] 索引標籤。

在 [使用中] 底下的清單中:

  • 針對使用 Azure 監視器追蹤匯出工具傳送的遙測,連入要求會出現在 requests 底下。 連出要求或處理中要求會出現在 dependencies 底下。
  • 針對使用 Azure 監視器計量匯出工具傳送的遙測,已傳送的計量會出現在 customMetrics 底下。
  • 針對使用 Azure 監視器記錄匯出工具傳送的遙測,記錄會出現在 traces 底下。 例外狀況會出現在 exceptions 底下。

如需如何使用查詢和記錄的詳細資訊,請參閱 Azure 監視器中的記錄

深入了解適用於 Python 的 OpenCensus

疑難排解

測試應用程式主機與擷取服務之間的連線能力

Application Insights SDK 與代理程式會傳送遙測,以便在 REST 呼叫擷取端點時進行擷取。 您可以使用來自 PowerShell 或 curl 命令的原始 REST 用戶端,測試從 Web 伺服器或應用程式主機電腦到擷取服務端點的連線。 請參閱針對 Azure 監視器Application Insights 中的遺漏應用程式遙測進行疑難排解

版本資訊

如需最新版本資訊,請參閱 Python Azure 監視器匯出工具

我們的服務更新也摘要說明主要的 Application Insights 改進。

下一步

警示

  • 可用性概觀:建立測試以確定您的網站在網路上可見。
  • 智慧型診斷︰這些測試會自動執行,您不需要採取任何動作來設定它們。 它們會讓您知道應用程式是否有不尋常的失敗要求率。
  • 計量警示:設定警示以在計量超出臨界值時警告您。 您可以在撰寫於程式碼中的自訂度量上設定它們。