【发布时间】:2020-12-15 14:01:37
【问题描述】:
在 Azure Functions 中使用 Python (3.8) 时,是否可以将结构化日志发送到 Application Insights?更具体地说,我正在尝试使用日志消息发送自定义维度。我能找到的关于日志记录的只有this 非常简短的部分。
【问题讨论】:
标签: python azure azure-functions azure-application-insights
在 Azure Functions 中使用 Python (3.8) 时,是否可以将结构化日志发送到 Application Insights?更具体地说,我正在尝试使用日志消息发送自定义维度。我能找到的关于日志记录的只有this 非常简短的部分。
【问题讨论】:
标签: python azure azure-functions azure-application-insights
更新 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")
示例代码在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)
【讨论】: