【问题标题】:Azure Functions for python, structured logging to Application Insights?Azure Functions for python,结构化日志记录到 Application Insights?
【发布时间】:2020-12-15 14:01:37
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    更新 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)
    

    【讨论】:

    • 谢谢,我知道那部分(并且正在另一个非函数应用程序中使用它。但理想情况下,我不想添加另一个记录器,因为函数中已经有可用的记录器。恐怕这样做,我可能会失去任何相关性
    • 这个 Github 讨论实际上产生了一个工作示例,与您的示例相差不远。如果您想修改答案,我会将其标记为已接受github.com/Azure/azure-functions-python-worker/issues/…
    • @silent,将其包含在答案中。如果它有帮助,请接受它作为答案:)。
    • @ivan-young 抱歉,我高兴得太早了……事实证明,相关性不适用于该代码 sn-p。我目前正在与支持/PG 联系以解决此问题
    • @silent 感谢您指出这一点。让我们等待支持团队的回应:)。
    猜你喜欢
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多