python - Azure Functions for python、结构化日志记录到 Application Insights?

标签 python azure azure-functions azure-application-insights

在 Azure Functions 中使用 Python (3.8) 时,是否有办法将结构化日志发送到 Application Insights?更具体地说,我正在尝试发送带有日志消息的自定义维度。我能找到的关于日志记录的所有内容是 this非常简短的部分。

最佳答案

更新0127:

已按照 this github issue 解决。这是示例代码:

# Change Instrumentation Key and Ingestion Endpoint before you run this function app

import logging

import azure.functions as func
from opencensus.ext.azure.log_exporter import AzureLogHandler

logger_opencensus = logging.getLogger('opencensus')
logger_opencensus.addHandler(
    AzureLogHandler(
        connection_string='InstrumentationKey=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee;IngestionEndpoint=https://eastus-6.in.applicationinsights.azure.com/'
    )
)

def main(req: func.HttpRequest) -> func.HttpResponse:
    properties = {
        'custom_dimensions': {
            'key_1': 'value_1',
            'key_2': 'value_2'
        }
    }

    logger_opencensus.info('logger_opencensus.info Custom Dimension', extra=properties)
    logger_opencensus.info('logger_opencensus.info Statement')
    return func.HttpResponse("OK")
<小时/>

请尝试OpenCensus Python SDK .

示例代码位于 Logs部分,步骤 5:

说明:您还可以使用 custom_dimensions 字段在额外关键字参数中向日志消息添加自定义属性。这些属性在 Azure Monitor 的 customDimensions 中显示为键值对。

示例:

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)

关于python - Azure Functions for python、结构化日志记录到 Application Insights?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65307435/

相关文章:

python - 与 SQLAlchemy 中列的切片和转换值的关系

azure - 如何命名Azure存储帐户?

azure - 嵌套模板中引用listKeys()

azure - 在 CQRS 中实现基于集合的约束

azure - 创建函数App时出现错误 "scale operation is not allowed for this subscription in this region"

azure - 在 Azure 中,如何在不使用 git 的情况下部署 functionapp 代码?

python - 日期顺序输出?

python - 如何从 for 循环中获取多个值?

python - Plotly Geoscatter 与聚合 : show aggregation in hover Info

azure - 来自带有 .net core 的 Azure function 2.0 的引用文件