在用于 Python 的 Azure 库中配置日志记录

基于 azure.core 的用于 Python 的 Azure 库使用标准 Python 日志记录库提供日志记录输出。

使用日志记录的一般过程如下所示:

  1. 获取所需库的日志记录对象,并设置日志记录级别。
  2. 注册日志记录流的处理程序。
  3. 若要包含 HTTP 信息,请将 logging_enable=True 参数传递给客户端对象构造函数、凭据对象构造函数或特定方法。

本文余下部分提供了详细信息。

一般来说,了解库中日志记录使用情况的最佳方法是在 github.com/Azure/azure-sdk-for-python 中浏览 SDK 源代码。 建议你在本地克隆此存储库,以便可以在需要时轻松搜索详细信息,如以下部分所示。

设置日志记录级别

import logging

# ...

# Acquire the logger for a library (azure.mgmt.resource in this example)
logger = logging.getLogger('azure.mgmt.resource')

# Set the desired logging level
logger.setLevel(logging.DEBUG)
  • 此示例获取 azure.mgmt.resource 库的记录器,然后将日志记录级别设置为 logging.DEBUG
  • 你可以随时调用 logger.setLevel 以更改不同代码片段的日志记录级别。

若要设置不同库的级别,请在 logging.getLogger 调用中使用该库的名称。 例如,azure eventhubs 库提供名为 azure.eventhubs 的记录器,azure-storage-queue 库提供名为 azure.storage.queue 的记录器,依此类推。 (SDK 源代码经常使用 logging.getLogger(__name__) 语句,该语句使用包含模块的名称获取记录器。)

你还可以使用更常见的命名空间。 例如,

import logging

# Set the logging level for all azure-storage-* libraries
logger = logging.getLogger('azure.storage')
logger.setLevel(logging.INFO)

# Set the logging level for all azure-* libraries
logger = logging.getLogger('azure')
logger.setLevel(logging.ERROR)

记录 azure 器由某些库而不是特定的记录器使用。 例如,azure-storage-blob 库使用 azure 记录器。

可使用 logger.isEnabledFor 方法来检查是否已启用任何给定的日志记录级别:

print(
    f"Logger enabled for ERROR={logger.isEnabledFor(logging.ERROR)}, "
    f"WARNING={logger.isEnabledFor(logging.WARNING)}, "
    f"INFO={logger.isEnabledFor(logging.INFO)}, "
    f"DEBUG={logger.isEnabledFor(logging.DEBUG)}"
)

日志记录级别与标准日志记录库级别相同。 下表描述了这些用于 Python 的 Azure 库中的日志记录级别的一般用法:

日志记录级别 典型用法
logging.ERROR 应用程序不太可能恢复的故障(如内存不足)。
logging.WARNING(默认) 函数无法执行其预期任务(但不是在函数可以恢复时,如重试 REST API 调用)。 函数通常会在引发异常时记录警告。 警告级别会自动启用错误级别。
logging.INFO 函数正常运行,或者服务调用被取消。 信息事件通常包括请求、响应和标头。 信息级别会自动启用错误和警告级别。
logging.DEBUG 通常用于故障排除的详细信息,其中包括异常的堆栈跟踪。 调试级别会自动启用信息、警告和错误级别。 警告:如果还设置 logging_enable=True,调试级别包括敏感信息,例如标头和其他凭据中的帐户密钥。 确保保护这些日志,以避免危及安全性。
logging.NOTSET 禁用所有日志记录。

特定于库的日志记录级别行为

每个级别的确切日志记录行为取决于相关的库。 某些库(如 azure.eventhub)执行广泛的日志记录,而其他库则很少执行。

检查库的确切日志记录的最佳方式是在 Azure SDK for Python 源代码搜索日志记录级别:

  1. 在存储库文件夹中,导航到“sdk”文件夹,然后导航到所需特定服务的文件夹。

  2. 在该文件夹中,搜索以下任何字符串:

    • _LOGGER.error
    • _LOGGER.warning
    • _LOGGER.info
    • _LOGGER.debug

注册日志流处理程序

若要捕获日志记录输出,必须在代码中注册至少一个日志流处理程序:

import logging
# Direct logging output to stdout. Without adding a handler,
# no logging output is visible.
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

此示例注册的处理程序可将日志输出定向到 stdout。 可以使用 Python 文档中 logging.handlers 部分所述的其他类型的处理程序,也可以使用标准的 logging.basicConfig 方法。

为客户端对象或操作启用 HTTP 日志记录

默认情况下,Azure 库中的日志记录不包含任何 HTTP 信息。 若要在日志输出中包含 HTTP 信息(作为 DEBUG 级别),必须显式传递给 logging_enable=True 客户端或凭据对象构造函数或特定方法。

注意

HTTP 日志记录可以包括敏感信息,例如标头和其他凭据中的帐户密钥。 确保保护这些日志,以避免危及安全性。

为客户端对象启用 HTTP 日志记录(调试级别)

from azure.storage.blob import BlobClient
from azure.identity import DefaultAzureCredential

# Enable HTTP logging on the client object when using DEBUG level
# endpoint is the Blob storage URL.
client = BlobClient(endpoint, DefaultAzureCredential(), logging_enable=True)

为客户端对象启用 HTTP 日志记录可为通过该对象调用的所有操作启用日志记录。

为凭据对象启用 HTTP 日志记录(调试级别)

from azure.storage.blob import BlobClient
from azure.identity import DefaultAzureCredential

# Enable HTTP logging on the credential object when using DEBUG level
credential = DefaultAzureCredential(logging_enable=True)

# endpoint is the Blob storage URL.
client = BlobClient(endpoint, credential)

为凭据对象启用 HTTP 日志记录可以记录通过该对象调用的所有操作,但对于不涉及身份验证的客户端对象中的操作,则启用日志记录。

为单个方法启用日志记录(调试级别)

from azure.storage.blob import BlobClient
from azure.identity import DefaultAzureCredential

# endpoint is the Blob storage URL.
client = BlobClient(endpoint, DefaultAzureCredential())

# Enable HTTP logging for only this operation when using DEBUG level
client.create_container("container01", logging_enable=True)

日志记录输出示例

以下代码显示在示例:使用存储帐户中,并且附带有启用 DEBUG 和 HTTP 日志记录的代码:

import logging
import os
import sys
import uuid

from azure.core import exceptions
from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobClient

logger = logging.getLogger("azure")
logger.setLevel(logging.DEBUG)

# Set the logging level for the azure.storage.blob library
logger = logging.getLogger("azure.storage.blob")
logger.setLevel(logging.DEBUG)

# Direct logging output to stdout. Without adding a handler,
# no logging output is visible.
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

print(
    f"Logger enabled for ERROR={logger.isEnabledFor(logging.ERROR)}, "
    f"WARNING={logger.isEnabledFor(logging.WARNING)}, "
    f"INFO={logger.isEnabledFor(logging.INFO)}, "
    f"DEBUG={logger.isEnabledFor(logging.DEBUG)}"
)

try:
    credential = DefaultAzureCredential()
    storage_url = os.environ["AZURE_STORAGE_BLOB_URL"]
    unique_str = str(uuid.uuid4())[0:5]

    # Enable logging on the client object
    blob_client = BlobClient(
        storage_url,
        container_name="blob-container-01",
        blob_name=f"sample-blob-{unique_str}.txt",
        credential=credential,
    )

    with open("./sample-source.txt", "rb") as data:
        blob_client.upload_blob(data, logging_body=True, logging_enable=True)

except (
    exceptions.ClientAuthenticationError,
    exceptions.HttpResponseError
) as e:
    print(e.message)

输出如下所示:

Logger enabled for ERROR=True, WARNING=True, INFO=True, DEBUG=True
Request URL: 'https://pythonazurestorage12345.blob.core.windows.net/blob-container-01/sample-blob-5588e.txt'
Request method: 'PUT'
Request headers:
    'Content-Length': '77'
    'x-ms-blob-type': 'BlockBlob'
    'If-None-Match': '*'
    'x-ms-version': '2023-11-03'
    'Content-Type': 'application/octet-stream'
    'Accept': 'application/xml'
    'User-Agent': 'azsdk-python-storage-blob/12.19.0 Python/3.10.11 (Windows-10-10.0.22631-SP0)'
    'x-ms-date': 'Fri, 19 Jan 2024 19:25:53 GMT'
    'x-ms-client-request-id': '8f7b1b0b-b700-11ee-b391-782b46f5c56b'
    'Authorization': '*****'
Request body:
b"Hello there, Azure Storage. I'm a friendly file ready to be stored in a blob."
Response status: 201
Response headers:
    'Content-Length': '0'
    'Content-MD5': 'SUytm0872jZh+KYqtgjbTA=='
    'Last-Modified': 'Fri, 19 Jan 2024 19:25:54 GMT'
    'ETag': '"0x8DC1924749AE3C3"'
    'Server': 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0'
    'x-ms-request-id': '7ac499fa-601e-006d-3f0d-4bdf28000000'
    'x-ms-client-request-id': '8f7b1b0b-b700-11ee-b391-782b46f5c56b'
    'x-ms-version': '2023-11-03'
    'x-ms-content-crc64': 'rtHLUlztgxc='
    'x-ms-request-server-encrypted': 'true'
    'Date': 'Fri, 19 Jan 2024 19:25:53 GMT'
Response content:
b''

注意

如果收到授权错误,请确保在 Blob 容器上为正在运行的标识分配了“存储 Blob 数据参与者”角色。 若要了解详细信息,请参阅 将 Blob 存储与身份验证配合使用。